1

Is there any change in the code needed between if we use CryptoStream with CryptoStreamMode.Read or with CryptoStreamMode.Write ?

(Besides reading from it and writing to an outStream or reading from an inStream and writing to the CryptoStream, of course.)

.

.

If you absolutely need to see code, here's some (See end of 3rd line):

using (Aes aes = Aes.Create())
using (ICryptoTransform encryptorTransform = aes.CreateEncryptor())
using (CryptoStream outAesStream = new CryptoStream(outStream, encryptorTransform, CryptoStreamMode.Write))
{
   //...
}
ispiro
  • 26,556
  • 38
  • 136
  • 291
  • 1
    There is a breaking change in `CryptoStream.Read` in .net 6 if you are looking for that - https://learn.microsoft.com/en-us/dotnet/core/compatibility/core-libraries/6.0/partial-byte-reads-in-streams – YK1 May 26 '22 at 19:07
  • Don't think so. Generally I'd use `CryptoStream.Write` for encryption and `CryptoStream.Read` for decryption. You're not likely to perform any non-streaming ops on the ciphertext after all. Beware of plaintext oracle attacks though, you might want to perform an integrity / authenticity check before decrypting and/or handling message (see e.g. padding & plaintext oracle attacks). – Maarten Bodewes May 29 '22 at 02:10
  • @MaartenBodewes I've actually found a difference - it seems like we need `FlushFinalBlock ` only when using Write, not when using Read. Probably to let the `CryptoStream` pad the data. To let it know we don't have any more data to be written to it. – ispiro May 29 '22 at 16:41
  • As for additional operations on the Stream - I'm trying to incorporate writing and reading the salt through the Stream overriding its `Read` method. – ispiro May 29 '22 at 16:43
  • @ispiro I guess you could bring the flushing down to generic issues with write and read. For read you never need to flush anyway. But yeah, there is some asymmetry there. – Maarten Bodewes May 29 '22 at 17:23
  • @MaartenBodewes Thanks. I guess the bottom line is as you said, that there is no qualitative difference between Read and Write. You can transform your comment(s) into an answer. – ispiro May 29 '22 at 19:35

0 Answers0