0

我目前以这种方式设置 RijndaelManaged(由于服务器如何处理加密,IV 和密钥相同)。服务器也使用 CFB8 作为模式,我设置正确了吗?

    public static RijndaelManaged GenerateAES(byte[] key)
    {
        RijndaelManaged cipher = new RijndaelManaged();
        cipher.Mode = CipherMode.CFB;
        cipher.Padding = PaddingMode.None;
        cipher.KeySize = 128;
        cipher.Key = key;
        cipher.IV = key;

        return cipher;
    }

我通过这样做写入数据: ICryptoTransform e = GenerateAES(key).CreateEncryptor();

        using(CryptoStream stream = new CryptoStream(BaseStream, e, CryptoStreamMode.Write))
        {
            stream.WriteByte(b);
            stream.FlushFinalBlock();
        }

BaseStream 是我打开的 NetworkStream,'b' 是我发送给函数的值。

当我尝试对流进行 0x00 (作为测试)时,出现此错误:

System.Security.Cryptography.CryptographicException: Length of the data to encrypt is invalid.
at System.Security.Cryptography.RijndaelManagedTransform.EncryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at System.Security.Cryptography.CryptoStream.FlushFinalBlock()
at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing)
at System.IO.Stream.Close()

我只测试了这个函数是否可以在不依赖任何外部库的情况下与服务器通信。

4

2 回答 2

6

您已将 设置PaddingMode为 None,并且尝试加密的字节数少于完整的数据块。加密更多数据( 的倍数cipher.BlockSize)或将填充模式设置为 None 以外的其他值,以便自动填充到适当的长度。

编辑:

RijndaelManaged 的​​默认 FeedbackSize 为 128 位,但您想使用 CFB8。如果将 设置cipher.FeedbackSize为 8,您将能够将其用作没有填充的流密码,并且写入 CryptoStream 的每个字节都将被加密并立即写入输出流。您不应每次写入后调用FlushFinalBlock,因为这会终止加密过程。

于 2012-08-02T12:16:16.223 回答
0

在这里提供了一个解决方案: https ://stackoverflow.com/a/29038974/725903

The idea is to wrap ICryptoTransform passed to a CryptoStream ctor that handles TransformFinalBlock adding required bytes before encryption/decryption and removing them on return

于 2015-03-13T18:09:04.720 回答