2013-05-15 139 views
1

我试图解密一个AES256位,但它给了我这个错误“解密数据的长度是无效的。”在线Plain_Text = Stream_Read.ReadToEnd();。我的加密方法有效,但解密不能。有人能帮助我吗?谢谢。AES 256解密错误

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

您可以发布您的加密方法,以便更容易排除故障吗? – Kevin

回答

1

的问题是在你的加密方法或更准确的加密和解密之间的相互作用。 你真的不想对二进制数据使用UTF8Encoding或ANY编码。文本编码用于将文本转换为二进制数据并再次返回。加密文本实际上是纯粹的二进制数据。我会建议使用Base64Strings。

在你的Encrypt方法中,你很可能有一个MemoryStream,你正在返回编码字符。相反,返回这样的Base64String ...

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

然后在你解密你采取的密文,并把它放回一个byte []像这样...

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

你也应该通过你的关键和初始化向量作为Base64Strings以及之后,你的代码应该很好去。

+0

它转换回一个字节时,抛出一个异常如何解决这个问题的任何想法?由于AES在使用转换为base64字符串时给了我一些非base64字符。 “输入不是有效的Base-64字符串,因为它包含非基本64字符,多于两个填充字符或填充字符中的非法字符。” – user2138160

+0

如果你用一个完整的例子(加密和解密)更新你的问题,我敢打赌,我可以很快看到有什么问题。 – Kevin

+0

我的假设是,您正在尝试执行Convert.FromBase64String的字符串与从Convert.ToBase64String返回的字符串不同。但是没有看到代码,我真的不知道更多。 – Kevin

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; 
+0

“Stream_Read.Read(plainText,0,plainText.Length);” “给System.IO.TextReader.Read(char [],int,int)的最佳重载方法匹配”有一些无效参数“AND”参数1:无法从'byte []'转换为' char []' “ – user2138160