I wanted to create an AES encryption service which will use a custom key/iv.
I want 2 methods: dycrypt/encrypt byte[]
The code works as expected, any remarks/issues?
public class AesGenericEncryptionService
{
private readonly byte[] m_Key;
private readonly byte[] m_IV;
public AesGenericEncryptionService(byte[] key, byte[] iv)
{
if (key == null || key.Length <= 0)
throw new ArgumentNullException(nameof(key));
if (iv == null || iv.Length <= 0)
throw new ArgumentNullException(nameof(iv));
m_Key = key;
m_IV = iv;
}
public byte[] Encrypt(byte[] data)
{
byte[] encrypted;
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Mode = CipherMode.CBC;
rijAlg.KeySize = m_Key.Length * 8;
rijAlg.Key = m_Key;
rijAlg.BlockSize = m_IV.Length * 8;
rijAlg.IV = m_IV;
using (ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV))
{
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
csEncrypt.Write(data, 0, data.Length);
csEncrypt.FlushFinalBlock();
encrypted = msEncrypt.ToArray();
}
}
}
}
return encrypted;
}
public byte[] Decrypt(byte[] cipher)
{
// Check arguments.
if (cipher == null || cipher.Length <= 0)
throw new ArgumentNullException(nameof(cipher));
byte[] dycrypted = null;
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Mode = CipherMode.CBC;
rijAlg.KeySize = m_Key.Length * 8;
rijAlg.Key = m_Key;
rijAlg.BlockSize = m_IV.Length * 8;
rijAlg.IV = m_IV;
using (ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV))
{
using (MemoryStream ms = new MemoryStream(cipher))
{
using (var cryptoStream = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
dycrypted = new byte[cipher.Length];
var bytesRead = cryptoStream.Read(dycrypted, 0, cipher.Length);
dycrypted = dycrypted.Take(bytesRead).ToArray();
}
}
}
}
return dycrypted;
}
}