AESManaged File Encryption and Decryption和prepending初始化向量

时间:2013-03-01 16:27:46

标签: c# byte aes encryption-symmetric

我正在尝试加密/解密字节 - 我已经在System.Security.Cryptography中使用AESManaged类对AES算法的Key和IV进行了大量阅读。我阅读了James Johnson对以下问题http://www.techques.com/question/1-7025135/My-Length-of-the-data-to-decrypt-is-invalid-error的回答,他建议您在加密例程中使用随机IV并将IV添加到加密消息中。解密功能从加密消息的开头剥离随机IV以初始化解密类,然后解密剩余的字节。我试图在以下代码中执行此操作。但我一直得到“要解密的数据长度无效”。加密后尝试解密时出现错误消息。有人可能会对可能出错的事情有所了解。

       USAGE: (streamToEncrypt/streamToDecrypt are System.IO.Stream)

       using (var cryptoHelper = new AESHelper())
        {
            var encryptedBytes = cryptoHelper.Encrypt(AESHelper.StreamToByteArray(streamToEncrypt));

        }


using (var cryptoHelper = new AESHelper())
        {
            var decryptedBytes = cryptoHelper.Decrypt(AESHelper.StreamToByteArray(streamToDecrypt));                             
        }

 public class AESHelper : IDisposable
 {       
    public AesManaged AESManaged;
    internal ICryptoTransform Encryptor { get; set; }
    internal ICryptoTransform Decryptor { get; set; }
    private const string KEY = "2428GD19569F9B2C2341839416C8E87G";
    private static readonly byte[] Salt = Encoding.ASCII.GetBytes("?pt1$8f]l4g80");
    private const Int32 ITERATIONS = 1042;


    internal AESHelper()
    {
        AESManaged = new AesManaged();
        AESManaged.BlockSize = AESManaged.LegalBlockSizes[0].MaxSize;
        AESManaged.KeySize = AESManaged.LegalKeySizes[0].MaxSize;                    
        AESManaged.Mode= CipherMode.CBC;
    }
   public void KeyGenerator()
    {
        var key = new Rfc2898DeriveBytes(KEY, Salt, ITERATIONS);
        AESManaged.Key = key.GetBytes(AESManaged.KeySize / 8);           
    }
    public byte[] Encrypt(byte[] input)
    {
        KeyGenerator();
        var ms = new MemoryStream();
        //Random IV 
        Encryptor = AESManaged.CreateEncryptor(AESManaged.Key, AESManaged.IV);
        //Add the IV to the beginning of the memory stream
        ms.Write(BitConverter.GetBytes(AESManaged.IV.Length), 0, sizeof(int));
        ms.Write(AESManaged.IV, 0, AESManaged.IV.Length);
        var cs = new CryptoStream(ms,
          Encryptor, CryptoStreamMode.Write);
        cs.Write(input, 0, input.Length);
        cs.Close();
        return ms.ToArray();
    }
    public byte[] Decrypt(byte[] input)
    {
        KeyGenerator();

        // Get the initialization vector from the encrypted stream
        var ms = new MemoryStream(input);
        AESManaged.IV = ReadByteArray(ms);
        Decryptor = AESManaged.CreateDecryptor(AESManaged.Key, AESManaged.IV);
        var cs = new CryptoStream(ms,
         Decryptor, CryptoStreamMode.Write);
        cs.Write(input, 0, input.Length);
        cs.Close();//Error occurs here
        return ms.ToArray();
    }

    internal static byte[] ReadByteArray(Stream s)
    {
        var rawLength = new byte[sizeof(int)];
        if (s.Read(rawLength, 0, rawLength.Length) != rawLength.Length)
        {
            throw new SystemException("Stream did not contain properly formatted byte array");
        }
        var buffer = new byte[16];
        if (s.Read(buffer, 0, buffer.Length) != buffer.Length)
        {
            throw new SystemException("Did not read byte array properly");
        }

        return buffer;
    }
     internal static byte[] StreamToByteArray(Stream inputStream)
    {
        if (!inputStream.CanRead)
        {
            throw new ArgumentException();
        }

        // This is optional
        if (inputStream.CanSeek)
        {
            inputStream.Seek(0, SeekOrigin.Begin);
        }

        var output = new byte[inputStream.Length];
        var bytesRead = inputStream.Read(output, 0, output.Length);
        Debug.Assert(bytesRead == output.Length, "Bytes read from stream matches stream length");
        return output;
    }
  public void Dispose()
    {
        if (AESManaged != null)
            ((IDisposable) AESManaged).Dispose();

    }}

非常感谢提前

1 个答案:

答案 0 :(得分:3)

可能你已经解决了这个问题,但我会把答案给那些面临类似问题的人。

由于input数组中存在其他信息而发生错误。在public byte[] Encrypt(byte[] input)方法中,您在写入加密数据之前写入IV长度和IV。行:

ms.Write(BitConverter.GetBytes(AESManaged.IV.Length), 0, sizeof(int));
ms.Write(AESManaged.IV, 0, AESManaged.IV.Length);

public byte[] Decrypt(byte[] input)方法中,您正在阅读此信息并使用read IV作为AES算法的初始化向量。一切都很好。然后,您正在使用CryptoStream构建CryptoStreamMode.Write并传递MemoryStream对象ms以获取解密数据。但是,传递的input数组不仅包含加密消息,还包含您在加密过程中编写的IV。这就是它无法解密的原因。

要解决此问题,您需要从input数组中仅提取密码数据并将其传递给:cs.Write(cipherData, 0, cipherData.Length);或将模式更改为CryptoStreamMode.Read并使用cs.Read(outputBuff, 0, outputBuff.Length); }。

也不要使用相同的MemoryStream对象进行读写,因为在CryptoStream写入后会有一些垃圾。