I\'m having some trouble with the code below. I have a file in a temporary location which is in need of encryption, this function encrypts that data which is then stored at
The KeySize must be specified first. This looks like a bug e.g. this works
using (var aes = new AesManaged())
{
aes.KeySize = 256;
aes.Mode = CipherMode.CBC;
aes.IV = iv;
aes.Key = passwordHash;
aes.Padding = PaddingMode.PKCS7;
but this doesn't
using (var aes = new AesManaged())
{
aes.Mode = CipherMode.CBC;
aes.IV = iv;
aes.Key = passwordHash;
aes.Padding = PaddingMode.PKCS7;
aes.KeySize = 256;
Well, there are several things going wrong here.
1. Your setting the size of the IV too large. If you have a key size of 256, the IV for Rijndael is 16 bytes. If you try to set the key with more bytes than that you will get an exception. IV size should be set to Block size / 8 see MSDN so the IV size you have is correct.
I am posting some sample code using memory streams to show the encrypting and decrypting.
var tempData = "This is the text to encrypt. It's not much, but it's all there is.";
using (var rijCrypto = new RijndaelManaged())
{
byte[] encryptedData;
rijCrypto.Padding = System.Security.Cryptography.PaddingMode.ISO10126;
rijCrypto.KeySize = 256;
using (var input = new MemoryStream(Encoding.Unicode.GetBytes(tempData)))
using (var output = new MemoryStream())
{
var encryptor = rijCrypto.CreateEncryptor();
using (var cryptStream = new CryptoStream(output, encryptor, CryptoStreamMode.Write))
{
var buffer = new byte[1024];
var read = input.Read(buffer, 0, buffer.Length);
while (read > 0)
{
cryptStream.Write(buffer, 0, read);
read = input.Read(buffer, 0, buffer.Length);
}
cryptStream.FlushFinalBlock();
encryptedData = output.ToArray();
}
}
using (var input = new MemoryStream(encryptedData))
using (var output = new MemoryStream())
{
var decryptor = rijCrypto.CreateDecryptor();
using (var cryptStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read))
{
var buffer = new byte[1024];
var read = cryptStream.Read(buffer, 0, buffer.Length);
while (read > 0)
{
output.Write(buffer, 0, read);
read = cryptStream.Read(buffer, 0, buffer.Length);
}
cryptStream.Flush();
var result = Encoding.Unicode.GetString(output.ToArray());
}
}
}
Another way to read CryptoStream is to using CopyTo methord:
...
using (var output = new MemoryStream())
{
cryptStream.CopyTo(output);
return output.ToArray();
}
...