public byte[] EncryptAES(byte[] clearPayload, CryptoLevel keysize = CryptoLevel.AES256)
{
// if the key strength requested is different from the instance
if (KeySize != KeySize)
{
KeySize = keysize;
// re-calculate the encryption hash using the encryption level requested
SetEncryptionLevel(KeySize);
}
// Check arguments.
if (clearPayload == null || clearPayload.Length <= 0)
{
throw new ArgumentNullException("clearPayload");
}
if (key_array == null || key_array.Length <= 0)
{
throw new ArgumentNullException("Key");
}
if (iv_array == null || iv_array.Length <= 0)
{
throw new ArgumentNullException("Key");
}
// declare the output object.
byte[] encrypted;
// Create an Aes object
// with the specified key and IV.
using (Aes aes = Aes.Create())
{
aes.Key = key_array;
aes.IV = iv_array;
aes.Mode = CipherMode.CBC;
aes.Padding = PaddingMode.PKCS7;
// Create a decrytor to perform the stream transform.
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
csEncrypt.Write(clearPayload, 0, clearPayload.Length);
csEncrypt.FlushFinalBlock();
encrypted = msEncrypt.ToArray();
}
msEncrypt.Close();
}
}
// Return the encrypted bytes from the memory stream.
return encrypted;
}