"Stream does not support searching" with CryptoStream object

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 the initialization of my CryptoStream object, it throws the following error:

"Stream does not support search." To clarify, there is no error handling in the above code, so just running this won't "break", hold back. But after going through the code, the CryptoStream object will show this error in its properties after it is initialized.

Why is this? And how can I avoid this?

+2


source to share


3 answers


So the code does work without exception, but the problem is you are looking at the properties in the debugger? If so, then simple - some properties ( Position

for example) rely on the ability to search in a stream. You cannot do this with CryptoStream

- so the property evaluation failed.



You don't have to avoid it - that's great.

+7


source


Can you use one of the constructors in the MemoryStream where you pass "true" to the write parameter?



0


source


To avoid this problem, it is much easier to use:

    using (var reader = new StreamReader(csEncrypt))
    {
        return reader.ReadToEnd();
    }

      

0


source







All Articles