Created
January 3, 2013 15:11
-
-
Save gabrielpascua/4444169 to your computer and use it in GitHub Desktop.
String encryption and decryption
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /****************************************************************************************************** | |
| FOR ENCRYPT AND DECRYPT METHODS TO WORK, THE KEY, INITIALIZATION | |
| VECTOR (IV), AND BYTE ARRAY HAS TO BE IDENTICAL. OTHERWISE THE | |
| PADDING ERROR WILL BE ENCOUNTERED. | |
| *******************************************************************************************************/ | |
| public static string EncryptURLParam(string authKey, string textToEncrypt) | |
| { | |
| string strEncrypt = string.Empty; | |
| try | |
| { | |
| using (Rijndael rDel = Rijndael.Create()) | |
| { | |
| rDel.Key = Encoding.ASCII.GetBytes(authKey); //32bytes | |
| rDel.IV = Encoding.ASCII.GetBytes(authKey.Substring(0,16)); //16bytes | |
| ICryptoTransform encryptor = rDel.CreateEncryptor(rDel.Key, rDel.IV); | |
| using (MemoryStream msEncrypt = new MemoryStream()) | |
| { | |
| using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) | |
| { | |
| using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) | |
| { | |
| swEncrypt.Write(textToEncrypt); | |
| } | |
| } | |
| byte[] bt = msEncrypt.ToArray(); | |
| strEncrypt = HttpContext.Current.Server.UrlEncode(Convert.ToBase64String(bt)); | |
| } | |
| } | |
| } | |
| catch | |
| { | |
| //do nothing | |
| } | |
| return strEncrypt; | |
| } | |
| public static string DecryptURLParam(string authKey, string textToDecrypt) | |
| { | |
| string decryptedId = string.Empty; | |
| try | |
| { | |
| //when urldecode is called, '+' characters are converted to a space | |
| //thus the need to replace those empty spaces to '+' again | |
| byte[] bt = Convert.FromBase64String(HttpContext.Current.Server.UrlDecode(textToDecrypt).Replace(' ', '+')); | |
| using (Rijndael rDel = Rijndael.Create()) | |
| { | |
| rDel.Key = Encoding.ASCII.GetBytes(authKey); //32bytes | |
| rDel.IV = Encoding.ASCII.GetBytes(authKey.Substring(0, 16)); //16bytes | |
| ICryptoTransform decryptor = rDel.CreateDecryptor(rDel.Key, rDel.IV); | |
| using (MemoryStream msDecrypt = new MemoryStream(bt)) | |
| { | |
| using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) | |
| { | |
| using (StreamReader srDecrypt = new StreamReader(csDecrypt)) | |
| { | |
| decryptedId = srDecrypt.ReadToEnd(); | |
| } | |
| } | |
| } | |
| } | |
| } | |
| catch | |
| { | |
| //do nothing | |
| } | |
| return decryptedId; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment