gego.info

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);
}

:, ,

2 Comments for this entry

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...