我有一些用 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()
我发现了一些类似问题的链接,但没有解决方案。
仅删除加密流的处置是否安全,或者只会导致终结器在以后爆炸?