3

我正在尝试加密/解密字节 - 我已经使用 System.Security.Cryptography 中的 AESManaged 类对 AES 算法的密钥和 IV 进行了大量阅读。我读了詹姆斯约翰逊对以下问题的回答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();

    }}

提前谢谢了

4

1 回答 1

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 算法的初始化向量。一切都好。然后,您正在构建CryptoStreamCryptoStreamMode.Write传递获取解密数据的MemoryStream对象。ms但是,传递的input数组不仅包含加密的消息,还包含您在加密过程中编写的 IV。这就是它无法解密的原因。

要克服这个问题,您需要做的是仅从input数组中提取密码数据并将其传递给:cs.Write(cipherData, 0, cipherData.Length);或​​将模式更改为CryptoStreamMode.Read并使用cs.Read(outputBuff, 0, outputBuff.Length);.

也不要使用同一个MemoryStream对象来读写,因为在CryptoStream写入之后你会有一些垃圾。

于 2013-05-29T14:51:12.487 回答