Created
October 17, 2012 21:02
-
-
Save waldyrfelix/3908162 to your computer and use it in GitHub Desktop.
AES Mode CBC with PKCS7 Padding
This file contains 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
private static readonly byte[] iv = // array de 16 bytes | |
private static string decrypt(string message, string key) | |
{ | |
var encryptedBytes = Convert.FromBase64String(message); | |
var aesAlg = makeAesCryptoServiceProvider(key); | |
var decryptor = aesAlg.CreateDecryptor(); | |
using (var memory = new MemoryStream(encryptedBytes)) | |
{ | |
using (var crypto = new CryptoStream(memory, decryptor, CryptoStreamMode.Read)) | |
{ | |
using (var stream = new StreamReader(crypto)) | |
{ | |
return stream.ReadToEnd(); | |
} | |
} | |
} | |
} | |
private static string encrypt(string message, string key) | |
{ | |
var aes = makeAesCryptoServiceProvider(key); | |
var encryptor = aes.CreateEncryptor(); | |
using (var memory = new MemoryStream()) | |
{ | |
using (var crypto = new CryptoStream(memory, encryptor, CryptoStreamMode.Write)) | |
{ | |
using (var stream = new StreamWriter(crypto)) | |
{ | |
stream.Write(message); | |
} | |
} | |
return Convert.ToBase64String(memory.ToArray()); | |
} | |
} | |
private static AesCryptoServiceProvider makeAesCryptoServiceProvider(string key) | |
{ | |
return new AesCryptoServiceProvider | |
{ | |
Mode = CipherMode.CBC, | |
Padding = PaddingMode.PKCS7, | |
Key = Encoding.UTF8.GetBytes(key), | |
IV = iv | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment