views:

293

answers:

3

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 RC2 = 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?

A: 

Can you use one of the constructors on the MemoryStream where you pass 'true' to the writable parameter?

popester
What byte array could I push through this constructor that would still work?
4501
I believe MD5 hashes to 16 bytes.
popester
+7  A: 

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.

Jon Skeet
So is the exception occurring simply because attempting to view the Position property is invalid on the stream, so it is just affirming to me that I cannot view that?
4501
Yup, that's exactly it.
Jon Skeet
A: 

Check this, it might help ;)

http://admincraft.net/arts/2WRCS.html

AdminCraft