CryptoStream: Why CryptoStreamMode.Write to encrypt and CryptoStreamMode.Read to decrypt?

Ben picture Ben · May 5, 2017 · Viewed 9.2k times · Source

Let e = 'password' and I am transforming it to 'as9kio0736' in a CryptoStream.

Let d = 'as9kio0736' and I am transforming it to 'password in a CryptoStream.

When I am transforming d back to 'password' why is it not considered writing in a CryptoStream?

using (MemoryStream msEncrypt = new MemoryStream()) {
    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) {
        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) {
            swEncrypt.Write(plainText);
        }
    }
}

using (MemoryStream msDecrypt = new MemoryStream(cipherText)) {
    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) {
        using (StreamReader srDecrypt = new StreamReader(csDecrypt)) {
            plaintext = srDecrypt.ReadToEnd();
        }
    }
}

Answer

bartonjs picture bartonjs · May 5, 2017

You can use CryptoStream in either direction for either operation; it's just where your data is and what you want to do with it.

If the data to process is already in a Stream (and you're okay with the stream getting drained and disposed), use CryptoStream in read mode and read the data out (including by using cryptoStream.CopyTo(someOtherStream)). If the data is in a byte[] and you want to write it to a Stream, use CryptoStream.Write.

In the .NET Core tests you can find examples both ways.

Heck, those are even in the same files. It's all just a matter of preference.