我正试着用C#写一个En/Decrypter。正如标题所示,我在CryptoStream.close()获得了一个CryptoStream.close()。我还没找到解决办法。希望有人能帮上忙。
public static string viaRijndael(byte[] input, string key, string iV)
{
Rijndael RijCrypt = Rijndael.Create();
RijCrypt.Key = System.Text.Encoding.UTF8.GetBytes(Tools.GetMD5Hash(Tools.GetMD5Hash(key)));
RijCrypt.IV = System.Text.Encoding.UTF8.GetBytes(Tools.GetMD5Hash(Tools.GetMD5Hash(key)).Substring(0, 16));
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, RijCrypt.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(input, 0, input.Length);
cs.Close(); // System.Security.Cryptography.CryptographicException
byte[] DecryptedBytes = ms.ToArray();
return System.Text.Encoding.UTF8.GetString(DecryptedBytes);
}发布于 2016-05-10 16:30:49
MSDN Stream.Close文档说:
“此方法调用Dispose,指定true以释放所有资源。您不必专门调用Close方法。相反,要确保每个Stream对象都被正确地处理。您可以在using块(或在Visual中使用块)中声明Stream对象,以确保流及其所有资源都被释放,或者您可以显式调用Dispose方法。”
因此,我建议尝试下面这样的方法来处理您的流:
public static string viaRijndael(byte[] input, string key, string iV)
{
byte[] decryptedBytes;
using (Rijndael rijCrypt = Rijndael.Create())
{
rijCrypt.Key = System.Text.Encoding.UTF8.GetBytes(Tools.GetMD5Hash(Tools.GetMD5Hash(key)));
rijCrypt.IV = System.Text.Encoding.UTF8.GetBytes(Tools.GetMD5Hash(Tools.GetMD5Hash(key)).Substring(0, 16));
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, rijCrypt.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(input, 0, input.Length);
}
decrpytedBytes = ms.ToArray();
}
}
return System.Text.Encoding.UTF8.GetString(decryptedBytes);
}所有这些以及更多内容将在CryptoStream类的MSDN上详细解释。
https://stackoverflow.com/questions/37137536
复制相似问题