CSharp – Rijndael/AES symetric Encryption and Decryption
by gernot on Feb.02, 2006, under Coding
A short tutorial how to encrypt, respectivelly decrypt a string in C# with Rijndael/AES.
NOTE: The Keygeneration is done in the encryption and decryption methods. For usage in a ‘real’ application this should be outsourced.
Encryption
using System.Security.Cryptography;
// Input Values:
// pwdHash = “MD5″ / “SHA1″
// iv = “16 ASCII Characters”
// keySize = 128 / 192 / 256
public string Encrypt(string text, string pwdPhrase, string pwdSalt, string pwdHash,
int pwdIterations, string iv, int keySize)
{
byte[] ivBytes = Encoding.ASCII.GetBytes(iv);
byte[] pwdSaltBytes = Encoding.ASCII.GetBytes(pwdSalt);
byte[] textBytes = Encoding.UTF8.GetBytes(text);
PasswordDeriveBytes pwd
= new PasswordDeriveBytes (pwdPhrase, pwdSaltBytes, pwdHash, pwdIterations);
byte[] keyBytes = pwd.GetBytes( keySize / 8 );
RijndaelManaged symmKey = new RijndaelManaged ();
symmKey.Mode = CipherMode.CBC;
ICryptoTransform enc
= symmKey.CreateEncryptor(keyBytes, ivBytes);
MemoryStream mem = new MemoryStream ();
CryptoStream cry
= new CryptoStream (mem, enc, CryptoStreamMode.Write);
cry.Write(textBytes, 0, textBytes.Length);
cry.FlushFinalBlock();
byte[] cipBytes = mem.ToArray();
mem.Close();
cry.Close();
return Convert.ToBase64String(cipBytes);
}
Decryption
using System.Security.Cryptography;
// Input Values:
// pwdHash = “MD5″ / “SHA1″
// iv = “16 ASCII Characters”
// keySize = 128 / 192 / 256
public string Decrypt(string cip, string pwdPhrase, string pwdSalt, string pwdHash,
int pwdIterations, string iv, int keySize)
{
byte[] ivBytes = Encoding.ASCII.GetBytes(iv);
byte[] pwdSaltBytes = Encoding.ASCII.GetBytes(pwdSalt);
byte[]cipTextBytes = Convert.FromBase64String(cip);
PasswordDeriveBytes pwd
= new PasswordDeriveBytes (pwdPhrase, pwdSaltBytes, pwdHash, pwdIterations);
byte[] keyBytes = pwd.GetBytes( keySize / 8 );
RijndaelManaged symmKey = new RijndaelManaged ();
symmKey.Mode = CipherMode.CBC;
ICryptoTransform dec
= symmKey.CreateDecryptor(keyBytes, ivBytes);
MemoryStream mem = new MemoryStream (cipTextBytes);
CryptoStream cry
= new CryptoStream (mem, dec, CryptoStreamMode.Read);
byte[] textBytes = new byte[cipTextBytes.Length];
int decByteCount
= cry.Read(textBytes, 0, textBytes.Length);
mem.Close();
cry.Close();
return Encoding.UTF8.GetString(textBytes, 0, decByteCount);
}
July 16th, 2008 on 06:19
Very helpful. But you could in all the method use only bytes[] without conversion, and outside the methods to convert everything. It is cleaner so
July 16th, 2008 on 06:31
By the way: The code is difficult to understand because is bad formatted.