1

I want to use this encryption method in my project. However, according to the example it reads, encrypts and then writes one byte at a time, which seems inefficient. From looking at the CryptoStream class there are methods to read and write buffers into the stream. What I am asking is whether it is safe/reliable to encrypt/decrypt more than one byte at a time, and if so, what's the max reliable buffer size to do so.

Foxman
  • 189
  • 13

1 Answers1

2

Indeed, that code you linked to is not a good way to do it. It has many other flaws as well such as invalid resource cleanup.

It is safe to use any buffer size at all. You should choose a buffer size that is large enough to minimize per-call overheads. 4096 is plenty to do that. Depending on what IO device you are targeting you might increase that size. 64KB is a good value for disk and network according to my testing.

usr
  • 168,620
  • 35
  • 240
  • 369
  • thanks! You said that this way has other flaws? Should I still use it but change the read/write or should I use another way altogether? – Foxman Mar 13 '16 at 12:02
  • 1
    The key generation looks bad. Also, encrypted data can be edited by attackers without you being able to find out. Look into authenticated encryption such as AES-GCM. Maybe you can find a crypto library for .NET that is a little more authoritative than a 20 line CodeProject snippet from some random dude. – usr Mar 13 '16 at 15:46
  • Okay, looked a bit more and seems Microsoft gives pretty much [the same example](https://msdn.microsoft.com/en-us/library/as0w18af(v=vs.110).aspx). – Foxman Mar 13 '16 at 17:04
  • 2
    Doesn't matter who gives it. It's just as wrong. That sample code is even worse than what you initially linked to. – usr Mar 13 '16 at 17:26