从CryptoStream读取会导致填充错误

时间:2013-12-02 02:52:49

标签: c# stream cryptography

我正在编写Aes解密方法,目前,我一直试图读取CryptoStream中的所有内容并将其全部放入byte []。这就是我解密的原因:

    public byte[] GetDecrypted()
    {
        byte[] toReturn;
        using (Aes dec = Aes.Create())
        {
            dec.Key = Key;
            dec.IV = IV;

            ICryptoTransform cryptoTransform = dec.CreateDecryptor(dec.Key, dec.IV);
            using (MemoryStream ms = new MemoryStream(Data))
            {
                using (CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Read))
                {
                    using (MemoryStream decMs = new MemoryStream())
                    {
                        cs.CopyTo(decMs);
                        toReturn = decMs.ToArray();
                    }
                }
            }
        }
        return toReturn;
    }

对于加密,我使用了非常相似的代码;也许这里出了点问题:

    public byte[] GetEncrypted()
    {
        byte[] toReturn;
        using (Aes enc = Aes.Create())
        {
            enc.Key = Key;
            enc.GenerateIV();
            IV = enc.IV;

            ICryptoTransform cryptoTransform = enc.CreateEncryptor(enc.Key, enc.IV);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write))
                {
                    cs.Write(Data, 0, Data.Length);
                    toReturn = ms.ToArray();
                }
            }
        }
        return toReturn;
    }

1 个答案:

答案 0 :(得分:2)

您的问题确实存在于您的加密方面。您必须先关闭加密流以将数据刷新到基础流。这是一个简单的解决方法,只需使用阻止移动.ToArray() CryptoStream以外的地方。

using (MemoryStream ms = new MemoryStream())
{
    using (CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Write))
    {
        cs.Write(Data, 0, Data.Length);
    }

    toReturn = ms.ToArray();
}