encrypt a file in csharp

Here's an example code for encrypting a file with the AES encryption algorithm in C#:

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

public static void EncryptFile(string inputFile, string outputFile, byte[] key, byte[] IV)
{
    using (FileStream fsIn = new FileStream(inputFile, FileMode.Open, FileAccess.Read))
    {
        using (FileStream fsOut = new FileStream(outputFile, FileMode.Create, FileAccess.Write))
        {
            using (Aes aes = Aes.Create())
            {
                aes.Key = key;
                aes.IV = IV;
                aes.Mode = CipherMode.CBC;

                using (CryptoStream cs = new CryptoStream(fsOut, aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    byte[] buffer = new byte[4096];
                    int bytesRead;

                    while ((bytesRead = fsIn.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        cs.Write(buffer, 0, bytesRead);
                    }
                }
            }
        }
    }
}
974 chars
31 lines

To use this method, simply provide the file paths of the input and output files, as well as a 256-bit key and a 128-bit IV (initialization vector) for the AES algorithm. Note that the same key and IV should be used for encryption and decryption.

main.cs
byte[] key = new byte[32]; // 256-bit key
byte[] IV = new byte[16]; // 128-bit IV

// Generate random key and IV
using (Aes aes = Aes.Create())
{
    aes.GenerateKey();
    aes.GenerateIV();
    key = aes.Key;
    IV = aes.IV;
}

EncryptFile("input.txt", "output.enc", key, IV);
279 chars
14 lines

gistlibby LogSnag