Last active
January 25, 2017 12:08
-
-
Save shammelburg/f16ceec5cce92cddab9c to your computer and use it in GitHub Desktop.
c#-aes-encryption-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
public static string Encrypt(string clearText) | |
{ | |
string EncryptionKey = "my-secret-key"; | |
byte[] clearBytes = Encoding.Unicode.GetBytes(clearText); | |
using (Aes encryptor = Aes.Create()) | |
{ | |
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); | |
encryptor.Key = pdb.GetBytes(32); | |
encryptor.IV = pdb.GetBytes(16); | |
using (MemoryStream ms = new MemoryStream()) | |
{ | |
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) | |
{ | |
cs.Write(clearBytes, 0, clearBytes.Length); | |
cs.Close(); | |
} | |
clearText = Convert.ToBase64String(ms.ToArray()); | |
} | |
} | |
return clearText; | |
} | |
public static string Decrypt(string cipherText) | |
{ | |
string EncryptionKey = "my-secret-key"; | |
byte[] cipherBytes = Convert.FromBase64String(cipherText); | |
using (Aes encryptor = Aes.Create()) | |
{ | |
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); | |
encryptor.Key = pdb.GetBytes(32); | |
encryptor.IV = pdb.GetBytes(16); | |
using (MemoryStream ms = new MemoryStream()) | |
{ | |
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) | |
{ | |
cs.Write(cipherBytes, 0, cipherBytes.Length); | |
cs.Close(); | |
} | |
cipherText = Encoding.Unicode.GetString(ms.ToArray()); | |
} | |
} | |
return cipherText; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment