4

我有一些用 Rijndael 解密密码的代码

public static string DecryptPassword(string encrypted) {
    using (MemoryStream ms = new MemoryStream())
    using (RijndaelManaged rijndaelManaged = new RijndaelManaged())
    using (ICryptoTransform cryptoTransform = rijndaelManaged.CreateDecryptor(mGlobalKey, mGlobalVector))
    using (CryptoStream cs = new CryptoStream(ms, cryptoTransform, CryptoStreamMode.Read)) {
        byte[] encryptedBytes = Convert.FromBase64String(encrypted);
        cs.Write(encryptedBytes, 0, encryptedBytes.Length);
        cs.FlushFinalBlock();
        return Encoding.Unicode.GetString(ms.GetBuffer(), 0, (int)ms.Length);
    }
}

问题是处理加密流会导致异常

System.IndexOutOfRangeException : Index was outside the bounds of the array.
at System.Security.Cryptography.RijndaelManagedTransform.DecryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)  
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)  
at System.Security.Cryptography.CryptoStream.FlushFinalBlock()  
at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing)  
at System.IO.Stream.Close()  
at System.IO.Stream.Dispose()  

我发现了一些类似问题的链接,但没有解决方案。

仅删除加密流的处置是否安全,或者只会导致终结器在以后爆炸?

4

2 回答 2

4

您正在 CryptoStreamMode.Read 模式下创建蒸汽,并尝试对其进行写入。

于 2011-06-20T22:03:01.000 回答
1

虽然我找不到好的解决方案,但我找到了以下两种解决方法: A. 不要将加密/解密函数设为静态 (C#) / 共享 (VB)。(您必须更改代码以实例化 RijndaelSimple 对象,然后调用 Encrypt/Decrypt 函数。可能的原因:不确定,但可能 CryptoStream 没有以线程安全的方式 B 使用内存流。似乎异常是仅当 cipherText 为空字符串时抛出。在 1.1 中,该函数用于在 cipherText 为空字符串时返回空字符串。因此只需将此代码添加为 Decrypt 函数的第一行: if (string.IsNullOrEmpty(cipherText))返回 ””;

我将选项 B 选为 // (这将是一个有效的解决方案,因为它仅在 cipherText="" 时失败 // (高效,因为它仍然是一个静态函数,并且当 cipherText=" 时它不必解密")

于 2012-04-18T14:29:11.857 回答