CryptoStream.close() 处的 C# 加密 System.Security.Cryptography.CryptographicException

C# Encryption System.Security.Cryptography.CryptographicException at CryptoStream.close()

我正在尝试用 C# 编写 En-/Decrypter。正如标题所示,我在 CryptoStream.close() 处得到了 System.Security.Cryptography.CryptographicException。我还没有找到解决方案。希望有人能帮忙。

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);
    }

MSDN Stream.Close 文档说:

"This method calls Dispose, specifying true to release all resources. You do not have to specifically call the Close method. Instead, ensure that every Stream object is properly disposed. You can declare Stream objects within a using block (or Using block in Visual Basic) to ensure that the stream and all of its resources are disposed, or you can explicitly call the Dispose method."

因此,我建议尝试类似以下的方法来处理您的流:

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);
}

CryptoStreamclass 的 MSDN 上对所有这些以及更多内容进行了详细解释。