2009/04/13

AES String Encryption/Decryption

public string AESforString(string rawString, string key, string IV, bool toEncrypt)
{
  try
  {
    RijndaelManaged oAES = new RijndaelManaged();
    Rfc2898DeriveBytes oRfc2898DeriveBytes = new Rfc2898DeriveBytes(key, Encoding.UTF8.GetBytes(IV));

    oAES.Padding = PaddingMode.PKCS7;
    oAES.Mode = CipherMode.CBC;
    oAES.KeySize = 256;
    oAES.Key = oRfc2898DeriveBytes.GetBytes(32);
    oAES.BlockSize = 128;
    oAES.IV = oRfc2898DeriveBytes.GetBytes(16);

    byte[] rawData;
    byte[] result;
    if (toEncrypt)
    {
      rawData = Encoding.UTF8.GetBytes(rawString);
      result = oAES.CreateEncryptor().TransformFinalBlock(rawData, 0, rawData.Length);
      oAES.Clear();
      return Convert.ToBase64String(result);
    }
    else
    {
      rawData = Convert.FromBase64String(rawString);
      result = oAES.CreateDecryptor().TransformFinalBlock(rawData, 0, rawData.Length);
      oAES.Clear();
      return Encoding.UTF8.GetString(result);
    }
  }
  catch (CryptographicException cex)
  {
    return cex.Message;
  }
}

No comments:

Post a Comment