I am trying to encrypt some data with the following code:
public static byte[] EncryptString(byte[] input, string password)
{
PasswordDeriveBytes pderiver = new PasswordDeriveBytes(password, null);
byte[] ivZeros = new byte[8];
byte[] pbeKey = pderiver.CryptDeriveKey("RC2", "MD5", 128, ivZeros);
RC2CryptoServiceProvider RC开发者_高级运维2 = new RC2CryptoServiceProvider();
byte[] IV = new byte[8];
ICryptoTransform encryptor = RC2.CreateEncryptor(pbeKey, IV);
MemoryStream msEncrypt = new MemoryStream();
CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);
csEncrypt.Write(input, 0, input.Length);
csEncrypt.FlushFinalBlock();
return msEncrypt.ToArray();
}
However, when it reaches initializing my CryptoStream object, it throws the following error:
"Stream does not support seeking." To clarify, there is no error handling in the above code, so just running this will not "break", persay. But stepping through the code, the CryptoStream object will show this error in its properties once it's been initialized.
Why is this? And how can I avoid it?
So the code actually runs without an exception, but the problem is when you're looking at the properties in the debugger? If so, that's easy - some properties (Position
, for example) rely on being able to seek within the stream. You can't do that with a CryptoStream
- so the property evaluation fails.
You don't need to avoid this - it's perfectly fine.
Can you use one of the constructors on the MemoryStream where you pass 'true' to the writable parameter?
To avoid this problem, its much easier to use:
using (var reader = new StreamReader(csEncrypt))
{
return reader.ReadToEnd();
}
精彩评论