Take the 2-minute tour ×

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();
    csEncrypt.Write(input, 0, input.Length);

    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?

share|improve this question
It's because this stream does not support seeking. Why do you want to avoid it? As long as you don't use Seek, everything should be fine. –  liggett78 Oct 26 '09 at 16:31

3 Answers 3

up vote 7 down vote accepted

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.

share|improve this answer
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 Oct 26 '09 at 16:38
Yup, that's exactly it. –  Jon Skeet Oct 26 '09 at 17:37

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

share|improve this answer
What byte array could I push through this constructor that would still work? –  4501 Oct 26 '09 at 16:22
I believe MD5 hashes to 16 bytes. –  popester Oct 26 '09 at 16:25

To avoid this problem, its much easier to use:

    using (var reader = new StreamReader(csEncrypt))
        return reader.ReadToEnd();
share|improve this answer
Throws CryptographicException : Padding is invalid and cannot be removed. –  MangeshGhotage Dec 5 at 9:20

Your Answer


