要解密的数据长度无效
本文关键字:无效 数据 解密 | 更新日期: 2023-09-27 18:29:37
我一直在研究在尝试使用Rijndael C#库进行解密时遇到的一个问题。我已经尝试了几个发布在这里的解决方案,但似乎都不起作用或适用。
问题是:我试图解密一个从硬件发送的HTTP请求。然而,我没有将HTTP请求转换为与我的解密方法匹配的正确字节数(我认为这是问题所在?)。
这是我的代码:
System.Text.Encoding enc = System.Text.Encoding.ASCII;
System.Text.Encoding req = System.Text.Encoding.ASCII;
if (curContext != null)
{
string decrypted = "";
int totalBytes = curContext.Request.TotalBytes;
StreamReader sr = new StreamReader(curContext.Request.InputStream);
string request = sr.ReadToEnd();
if (!String.IsNullOrEmpty(request))
{
using (RijndaelManaged myRijndael = new RijndaelManaged())
{
myRijndael.Mode = CipherMode.ECB;
myRijndael.Padding = PaddingMode.None;
byte[] key = enc.GetBytes(WebConfigurationManager.AppSettings["32B"].ToString());
myRijndael.KeySize = 256;
myRijndael.Key = key;
decrypted = DecryptStringFromBytes(req.GetBytes(request), myRijndael.Key);
}
}
}
以及解密方法:
static string DecryptStringFromBytes(byte[] cipherText, byte[] Key)
{
using (RijndaelManaged rijAlg = new RijndaelManaged())
{
rijAlg.Key = Key;
rijAlg.Mode = CipherMode.ECB;
rijAlg.Padding = PaddingMode.None;
// Create a decrytor to perform the stream transform.
ICryptoTransform decryptor = rijAlg.CreateDecryptor();
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
// and place them in a string.
plaintext = srDecrypt.ReadToEnd();
}
}
}
}
}
在srDecrypt.ReadToEnd()上,我得到标题中所述的错误消息。
我对这件事还很陌生,所以我不确定哪里出了问题。如有任何建议,我们将不胜感激。谢谢~!
"流到字符串到字节"的转换顺序感觉非常错误。确保您确实需要这样做,而不是简单地从响应中读取字节。
在解密方法的底部尝试这个方法:
int plainByteCount = int.MinValue;
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
plainBytes = new byte[cipherText.Length];
plainByteCount = cryptoStream.Read(plainBytes, 0, plainBytes.Length);
}
}
string plainText = Encoding.UTF8.GetString(plainBytes, 0, plainByteCount);
return plainText;
我想我可能发现了你的问题。根据StreamReader
的构造函数,默认编码为UTF8Encoding
。尝试使用其他构造函数重载并传入ASCII编码:
StreamReader sr = new StreamReader(
curContext.Request.InputStream, Encoding.ASCII);
string request = sr.ReadToEnd();