Encrypt and Decrypt Streams in C# with AES

The class below encrypts any Stream with AES and a password, and decrypts it again. Because it works on streams, it handles a 10 GB file as easily as a short string: data flows through a CryptoStream in chunks and is never loaded into memory all at once.

AES is the only symmetric algorithm you should pick for new code. The original version of this post also offered TripleDES and used RijndaelManaged; both are obsolete in current .NET, and a section at the end explains what was wrong with the old design.

Usage

Encrypt a file and decrypt it again:

string password = "correct horse battery staple";

await using (FileStream input = File.OpenRead("report.pdf"))
await using (FileStream output = File.Create("report.pdf.enc"))
{
    await StreamCrypto.EncryptAsync(input, output, password);
}

await using (FileStream input = File.OpenRead("report.pdf.enc"))
await using (FileStream output = File.Create("report-decrypted.pdf"))
{
    await StreamCrypto.DecryptAsync(input, output, password);
}

For a string, wrap the bytes in a MemoryStream:

using System.Text;

using var plain = new MemoryStream(Encoding.UTF8.GetBytes("This is a plain text."));
using var encrypted = new MemoryStream();
await StreamCrypto.EncryptAsync(plain, encrypted, password);

encrypted.Position = 0;
using var decrypted = new MemoryStream();
await StreamCrypto.DecryptAsync(encrypted, decrypted, password);

Console.WriteLine(Encoding.UTF8.GetString(decrypted.ToArray()));
// This is a plain text.

The implementation

using System.Security.Cryptography;

public static class StreamCrypto
{
    private const int SaltSize = 16;          // bytes
    private const int IvSize = 16;            // AES block size
    private const int KeySize = 32;           // 256-bit key
    private const int Iterations = 600_000;   // PBKDF2 work factor

    public static async Task EncryptAsync(
        Stream input, Stream output, string password, CancellationToken ct = default)
    {
        byte[] salt = RandomNumberGenerator.GetBytes(SaltSize);

        using Aes aes = Aes.Create();
        aes.Key = DeriveKey(password, salt);
        aes.GenerateIV();

        // The salt and IV are not secret. Store them in front of the
        // ciphertext so decryption can read them back.
        await output.WriteAsync(salt, ct);
        await output.WriteAsync(aes.IV, ct);

        using ICryptoTransform encryptor = aes.CreateEncryptor();
        await using var cryptoStream = new CryptoStream(
            output, encryptor, CryptoStreamMode.Write, leaveOpen: true);

        await input.CopyToAsync(cryptoStream, ct);
        await cryptoStream.FlushFinalBlockAsync(ct);
    }

    public static async Task DecryptAsync(
        Stream input, Stream output, string password, CancellationToken ct = default)
    {
        byte[] salt = new byte[SaltSize];
        byte[] iv = new byte[IvSize];
        await input.ReadExactlyAsync(salt, ct);
        await input.ReadExactlyAsync(iv, ct);

        using Aes aes = Aes.Create();
        aes.Key = DeriveKey(password, salt);
        aes.IV = iv;

        using ICryptoTransform decryptor = aes.CreateDecryptor();
        await using var cryptoStream = new CryptoStream(
            input, decryptor, CryptoStreamMode.Read, leaveOpen: true);

        await cryptoStream.CopyToAsync(output, ct);
    }

    private static byte[] DeriveKey(string password, byte[] salt) =>
        Rfc2898DeriveBytes.Pbkdf2(password, salt, Iterations, HashAlgorithmName.SHA256, KeySize);
}

ReadExactlyAsync needs .NET 7 or later; everything else works from .NET 6.

Why it is built this way

A password is not a key. AES needs exactly 16, 24 or 32 random-looking bytes. PBKDF2 (Rfc2898DeriveBytes.Pbkdf2) stretches a password into a key and makes each guess expensive for an attacker. 600,000 iterations of SHA-256 is the current OWASP recommendation; it costs a fraction of a second once per file. If you already have a random 32-byte key, for example from a key vault, skip the derivation and use it directly.

A fresh salt and IV every time. The random salt means the same password produces a different key for every file. The random IV means the same file encrypted twice produces different ciphertext, so an observer cannot tell that two files are identical. Neither value is secret; they just must never be reused, which is why they are generated per call and stored at the start of the output.

FlushFinalBlockAsync. AES in the default CBC mode works on 16-byte blocks, and the last block is padded. The padding is only written when the final block is flushed. Disposing the CryptoStream would flush it too, but doing it explicitly makes the intent clear and surfaces errors before the method returns.

leaveOpen: true. Without it, disposing the CryptoStream also disposes the underlying stream. In the string example above, that would close encrypted before you could rewind and read it.

Authenticated encryption with AesGcm

The code above keeps data confidential, but it does not detect tampering. A wrong password usually ends in a CryptographicException (“Padding is invalid”), but not always: about one time in 256 the padding happens to look valid and you get garbage back without an error. Worse, if an attacker can modify ciphertext and watch how your application reacts, CBC without an integrity check is open to padding-oracle attacks.

Authenticated encryption fixes both by adding a tag that decryption verifies. In .NET that is AesGcm:

using System.Security.Cryptography;

static byte[] EncryptGcm(byte[] plaintext, byte[] key)
{
    byte[] nonce = RandomNumberGenerator.GetBytes(12);
    byte[] tag = new byte[16];
    byte[] ciphertext = new byte[plaintext.Length];

    using var aes = new AesGcm(key, tag.Length);
    aes.Encrypt(nonce, plaintext, ciphertext, tag);

    return [.. nonce, .. tag, .. ciphertext];
}

static byte[] DecryptGcm(byte[] data, byte[] key)
{
    ReadOnlySpan<byte> nonce = data.AsSpan(0, 12);
    ReadOnlySpan<byte> tag = data.AsSpan(12, 16);
    ReadOnlySpan<byte> ciphertext = data.AsSpan(28);
    byte[] plaintext = new byte[ciphertext.Length];

    using var aes = new AesGcm(key, tag.Length);
    aes.Decrypt(nonce, ciphertext, tag, plaintext); // throws if anything was changed

    return plaintext;
}

key is 16, 24 or 32 bytes, for example the output of DeriveKey above. The AesGcm(key, tagSize) constructor exists from .NET 8. AesGcm is the better choice for messages, tokens and database fields. Its limitation is that it is not a streaming API: the whole plaintext and ciphertext must fit in memory. For large files, either encrypt in fixed-size chunks with a separate nonce per chunk, or keep the CBC stream above and add an HMAC-SHA256 over the salt, IV and ciphertext (encrypt-then-MAC), verifying it before you decrypt.

Maintaining the old code

The original class used RijndaelManaged and TripleDESCryptoServiceProvider. Both are marked obsolete (SYSLIB0022 and SYSLIB0021); Aes.Create() and TripleDES.Create() replace them. TripleDES itself should only be used to decrypt old data. The bigger flaw was that the IV was derived from the password with a fixed salt, so the same input and password always produced the same output, and 100 PBKDF2 iterations made password guessing cheap. Data encrypted that way can still be decrypted with the old settings; re-encrypt it with the code above when you can.

Related examples

2 thoughts on “Encrypt and Decrypt Streams in C# with AES”

  1. You indicate to the user you are using streaming, but you actually create a buffer the size of the full plaintext or ciphertext. Also note that a password is not a key, and a key is not a password.

    Reply

Leave a Comment