AES 256解密错误

本文关键字:错误 解密 AES | 更新日期: 2023-09-27 18:13:53

我试图解密AES256位,但它给了我这个错误"解密的数据长度无效。"在Plain_Text = Stream_Read.ReadToEnd();线上。我的加密方法有效,但解密不起作用。有人能帮帮我吗?谢谢。

 private static string Decrypt(string stringCypher_Text, string stringKey, string stringIV)
    {
        //Hashes, and converts key to bytes
        //hash
        //convert
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        Byte[] Key = encoding.GetBytes(stringKey);
        //converts string IV to bytes
        Byte[] IV = encoding.GetBytes(stringIV);
        //converts cypher string to bytes
        Byte[] Cypher_Text = encoding.GetBytes(stringCypher_Text);
        RijndaelManaged Crypto = null;
        MemoryStream MemStream = null;
        ICryptoTransform Decryptor = null;
        CryptoStream Crypto_Stream = null;
        StreamReader Stream_Read = null;
        string Plain_Text;
        try
        {
            Crypto = new RijndaelManaged();
            Crypto.Key = Key;
            Crypto.IV = IV;
            MemStream = new MemoryStream(Cypher_Text);
            //Create Decryptor make sure if you are decrypting that this is here and you did not copy paste encryptor.
            Decryptor = Crypto.CreateDecryptor(Crypto.Key, Crypto.IV);
            //This is different from the encryption look at the mode make sure you are reading from the stream.
            Crypto_Stream = new CryptoStream(MemStream, Decryptor, CryptoStreamMode.Read);
            //I used the stream reader here because the ReadToEnd method is easy and because it return a string, also easy.
            Stream_Read = new StreamReader(Crypto_Stream);
            Plain_Text = Stream_Read.ReadToEnd();
        }
        finally
        {
            if (Crypto != null)
                Crypto.Clear();
            MemStream.Flush();
            MemStream.Close();
        }
        return Plain_Text;
    }

AES 256解密错误

问题在您的加密方法中,或者更确切地说在加密和解密之间的交互中。您确实不想对二进制数据使用UTF8Encoding或ANY编码。文本编码用于将文本转换为二进制数据并再转换回来。加密文本实际上是纯二进制数据。我建议使用base64string。

在你的Encrypt方法中,你很可能有一个MemoryStream,你要从中返回编码字符。相反,返回一个Base64String,如下所示:

string cipherText = Convert.ToBase64String(memoryStream.ToArray());
return cipherText;

然后在你的解密你把密文,并把它变成一个字节[]像这样…

Byte[] Cypher_Text = Convert.FromBase64String(stringCypher_Text);

你也应该传递你的键和初始化向量作为base64string以及之后,你的代码应该很好去。

尝试将Plain_Text = Steam_Read.ReadToEnd();更改为

  byte[] plainText = new byte[Plain_Text.Length];
  int dByte = Stream_Read.Read(plainText, 0, plainText.Length);
  string decryptedText = Encoding.UTF8.GetString(plainText, 0, dByte);
  return descryptedText;