要解密的数据长度无效

时间:2012-03-30 15:51:36

标签: c# encryption rijndaelmanaged

我在尝试使用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()上,我收到标题中声明的错误消息。

我对此很新,所以我不确定我哪里出错了。任何意见,将不胜感激。感谢〜!

3 个答案:

答案 0 :(得分:0)

“Stream to string to bytes”转换序列感觉非常错误。确保你真的需要这样做,而不是简单地从响应中读取字节。

答案 1 :(得分:0)

请在Decrypt方法的底部尝试此操作:

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;

答案 2 :(得分:0)

我想我可能已经找到了你的问题。根据{{​​3}}的构造函数,默认编码为UTF8Encoding。尝试使用其他构造函数重载并传入ASCII编码:

StreamReader sr = new StreamReader(
   curContext.Request.InputStream, Encoding.ASCII);
string request = sr.ReadToEnd();