AES 256解密错误

时间:2013-05-15 23:46:37

标签: c# encryption aes

我尝试解密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;

    }

2 个答案:

答案 0 :(得分:1)

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

在您的加密方法中,您很可能有一个要从中返回编码字符的MemoryStream。而是像这样返回一个Base64String ......

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

然后在你的解密中,你拿出那个cipherText然后把它变回像这样的Byte [] ......

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

你也应该将你的密钥和初始化向量作为Base64Strings传递,然后你的代码就可以了。

答案 1 :(得分:0)

尝试将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;