For some reason my code give m a error for when I try and grab the byte from this section. And I don't know what the problem is.



static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key)
{
byte[] encrypted;
byte[] IV;

using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Key;

aesAlg.GenerateIV();
IV = aesAlg.IV;

aesAlg.Mode = CipherMode.CBC;

var encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

// Create the streams used for encryption.
using (var msEncrypt = new MemoryStream())
{
using (var csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (var swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
encrypted = msEncrypt.ToArray();
}
}
}

var combinedIvCt = new byte[IV.Length + encrypted.Length];
Array.Copy(IV, 0, combinedIvCt, 0, IV.Length);
Array.Copy(encrypted, 0, combinedIvCt, IV.Length, encrypted.Length);

// Return the encrypted bytes from the memory stream.
return combinedIvCt;

Respuesta :

tonb
I ran the code without problems. I added the decrypt routine from the same github site you got it from and was able to encrypt and subsequently decrypt a message.

So how are you invoking this code? Did you allocate a 16 byte buffer for the key?