aes encrypt file in csharp

Here is an example of how to AES encrypt a file in C#:

main.cs
using System;
using System.IO;
using System.Security.Cryptography;

class AesExample
{
    static void Main()
    {
        string inputFile = @"C:\input.txt";
        string outputFile = @"C:\output.bin";
        string password = "super_secret_password";

        using (Aes aes = Aes.Create())
        {
            // Convert the password to a byte array
            byte[] passwordBytes = System.Text.Encoding.UTF8.GetBytes(password);

            // Derive a key and IV from the password
            // These sizes are the minimum recommended for AES
            Rfc2898DeriveBytes derivedBytes = new Rfc2898DeriveBytes(passwordBytes, saltSize: 8, iterations: 1000);
            byte[] key = derivedBytes.GetBytes(32);
            byte[] iv = derivedBytes.GetBytes(16);

            // Open the input and output files
            using (FileStream inputStream = File.OpenRead(inputFile))
            using (FileStream outputStream = File.Create(outputFile))
            {
                // Write the IV to the beginning of the output file
                outputStream.Write(iv, 0, iv.Length);

                // Create the encryptor and encrypt the input file
                using (ICryptoTransform encryptor = aes.CreateEncryptor(key, iv))
                using (CryptoStream cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write))
                {
                    inputStream.CopyTo(cryptoStream);
                }
            }
        }
    }
}
1490 chars
41 lines

In this example, we create a new Aes object and use it to create an encryptor. We derive a key and initialization vector (IV) from a password using the Rfc2898DeriveBytes class. We then open the input and output files, and write the IV to the beginning of the output file. We create a CryptoStream with the encryptor and write the encrypted data to the output file.

Note that this example uses hardcoded paths for the input and output files, but in practice you would typically prompt the user for the filename or use a command line argument.

gistlibby LogSnag