I've created a class for encrypting and decrypting using AES.
public class AesEncryptionProvider {
#region Fields
// Encryption key
private static readonly byte[] s_key = new byte[32] {
// Omitted...
};
// Initialization vector
private static readonly byte[] s_iv = new byte[16] {
// Omitted...
};
private AesCryptoServiceProvider m_provider;
private ICryptoTransform m_encryptor;
private ICryptoTransform m_decryptor;
#endregion
#region Constructors
private AesEncryptionProvider () {
m_provider = new AesCryptoServiceProvider();
m_encryptor = m_provider.CreateEncryptor(s_key, s_iv);
m_decryptor = m_provider.CreateDecryptor(s_key, s_iv);
}
static AesEncryptionProvider () {
Instance = new AesEncryptionProvider();
}
#endregion
#region Properties
public static AesEncryptionProvider Instance { get; private set; }
#endregion
#region Methods
public string Encrypt (string value) {
if (string.IsNullOrEmpty(value)) {
throw new ArgumentException("Value required.");
}
return Convert.ToBase64String(
Transform(
Encoding.UTF8.GetBytes(value),
m_encryptor));
}
public string Decrypt (string value) {
if (string.IsNullOrEmpty(value)) {
throw new ArgumentException("Value required.");
}
return Encoding.UTF8.GetString(
Transform(
Convert.FromBase64String(value),
m_decryptor));
}
#endregion
#region Private methods
private byte[] Transform (byte[] input, ICryptoTransform transform) {
byte[] output;
using (MemoryStream memory = new MemoryStream()) {
using (CryptoStream crypto = new CryptoStream(
memory,
transform,
CryptoStreamMode.Write
)) {
crypto.Write(input, 0, input.Length);
crypto.FlushFinalBlock();
output = memory.ToArray();
}
}
return output;
}
#endregion
}
As you can see, in both cases I'm writing to a MemoryStream
via a CryptoStream
. If I create a new decryptor via m_provider.CreateDecyptor(s_key, s_iv)
on every call to Decrypt
it works just fine.
What has gone wrong here? Why is the decryptor behaving as if its forgotten the IV? Is there something that the call to StreamReader.ReadToEnd()
is doing that helps m_decryptor
function correctly?
I would like to avoid either of the two "working" approaches I listed here as there is a performance hit on both and this is a very critical path. Thanks in advance.