从CryptoStream读取会导致填充错误



我正在编写一个Aes解密方法,目前,我一直在尝试读取CryptoStream中的所有内容,并将其全部放入一个字节[]中。这就是我要解密的东西:

    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;
    }

您的问题确实在于加密方面。必须关闭加密流才能首先将数据刷新到基础流。这是一个简单的修复方法,只需将.ToArray()移动到CryptoStream的using块之外即可。

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

相关内容

  • 没有找到相关文章

最新更新