小编Mr.*_*Jr.的帖子

AES加密的C#UTF8编码问题

我正在创建一个基于TCP的聊天客户端。我正在尝试使用AES加密某些数据(以提高安全性)我有一个AES加密类,默认情况下它使用UTF-8作为输出和输入的编码类型。但是由于某种原因,当我通过TCPClient(使用UTF-8)传递信息并从另一端获取信息时,它会抛出错误:

`System.Security.Cryptography.CryptographicException: Length of the data to decrypt is invalid.
   at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
   at System.Security.Cryptography.CryptoStream.FlushFinalBlock()`
Run Code Online (Sandbox Code Playgroud)

因此,我在不使用TCP客户端的情况下重新创建了问题,只是将AES加密的数据放入UTF-8编码系统中,该系统获取字节数组的字符串,然后使用UTF-8重新获取字节数组(基本上是与网络上发生的事情相同(没有字符串))

此方法有效:

        string dataToEncrypt = "Hello World";
        byte[] key = Encryption.AesEncryption.GenerateKey(32);
        byte[] iv = Encryption.AesEncryption.GenerateKey(16);

        byte[] encrypted = Encryption.AesEncryption.EncryptString(dataToEncrypt, key, iv);

        string decrypted = Encryption.AesEncryption.DecryptedBytes(encrypted, key, iv);
Run Code Online (Sandbox Code Playgroud)

该方法不起作用(从上面抛出错误)

        Encoding encoding = Encoding.UTF8;

        string dataToEncrypt = "Hello World";
        byte[] key = Encryption.AesEncryption.GenerateKey(32);
        byte[] iv = Encryption.AesEncryption.GenerateKey(16);

        byte[] encrypted = Encryption.AesEncryption.EncryptString(dataToEncrypt, key, iv);

        string encstring = encoding.GetString(encrypted);

        byte[] utf8encrypted = encoding.GetBytes(encstring);

        string decrypted …
Run Code Online (Sandbox Code Playgroud)

c# encryption encoding aes utf-8

5
推荐指数
1
解决办法
2994
查看次数

标签 统计

aes ×1

c# ×1

encoding ×1

encryption ×1

utf-8 ×1