我創建了一個MemoryStream
,將它傳遞給CryptoStream
進行編寫。我想CryptoStream
加密,並保留我打開MemoryStream
然後讀入其他東西。但一旦CryptoStream
配置,它也配置MemoryStream
。CryptoStream是否可以讓基礎流開放?
可以CryptoStream
離開基地MemoryStream
打開莫名其妙?
using (MemoryStream scratch = new MemoryStream())
{
using (AesManaged aes = new AesManaged())
{
// <snip>
// Set some aes parameters, including Key, IV, etc.
// </snip>
ICryptoTransform encryptor = aes.CreateEncryptor();
using (CryptoStream myCryptoStream = new CryptoStream(scratch, encryptor, CryptoStreamMode.Write))
{
myCryptoStream.Write(someByteArray, 0, someByteArray.Length);
}
}
// Here, I'm still within the MemoryStream block, so I expect
// MemoryStream to still be usable.
scratch.Position = 0; // Throws ObjectDisposedException
byte[] scratchBytes = new byte[scratch.Length];
scratch.Read(scratchBytes,0,scratchBytes.Length);
return Convert.ToBase64String(scratchBytes);
}
爲什麼你首先使用流?只需在輸入字節上調用'encryptor.TransformFinalBlock'即可。數據流主要用於增量加密/解密,但不能在同時提供完整數據時使用。 – CodesInChaos