Skip to content

Instantly share code, notes, and snippets.

@waldyrfelix
Created October 17, 2012 21:02
Show Gist options
  • Save waldyrfelix/3908162 to your computer and use it in GitHub Desktop.
Save waldyrfelix/3908162 to your computer and use it in GitHub Desktop.
AES Mode CBC with PKCS7 Padding
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