AES 256文件加密c#

本文关键字:加密 文件 AES | 更新日期: 2023-09-27 18:22:07

我似乎找不到一个使用AES 256加密来加密c#中文件的干净例子

有人有一些示例代码吗?

AES 256文件加密c#

这是上面问题的答案

 UnicodeEncoding ue = new UnicodeEncoding();
                byte[] key = ue.GetBytes(password);
                string cryptFile = outputFile;
                using (FileStream fileCrypt = new FileStream(cryptFile, FileMode.Create))
                {
                    using (AesManaged encrypt = new AesManaged())
                    {
                        using (CryptoStream cs = new CryptoStream(fileCrypt, encrypt.CreateEncryptor(key, key), CryptoStreamMode.Write))
                        {
                            using (FileStream fileInput = new FileStream(inputFile, FileMode.Open))
                            {
                                encrypt.KeySize = 256;
                                encrypt.BlockSize = 128;
                                int data;
                                while ((data = fileInput.ReadByte()) != -1)
                                    cs.WriteByte((byte)data);
                            }
                        }
                    }
                }

我不是安全专家,除了小文件外,我还没有测试过这一点,但这是我使用.NET 6:进行的AES-256文件加密的现代化完整版本

using System.Security.Cryptography;
using System.Text;
namespace Core.Encryption;
/// <summary>
/// Encrypts and decrypts files using AES-256.
/// String keys are encoded using UTF8.
/// </summary>
public static class FileEncryptor
{
    private const int AesKeySize = 256;
    private const int AesBlockSize = 128;
    public const int KeySizeInBytes = AesKeySize / 8;
    /// <summary>
    /// Encrypts a file using a 32 character key.
    /// </summary>
    public static Task EncryptAsync(string inputFilePath, string outputFilePath, string key, CancellationToken token = default)
    {
        if (string.IsNullOrWhiteSpace(key))
        {
            throw new ArgumentException("Key cannot be empty!", nameof(key));
        }
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        return EncryptAsync(inputFilePath, outputFilePath, keyBytes, token);
    }
    public static async Task EncryptAsync(string inputFilePath, string outputFilePath, byte[] keyBytes, CancellationToken token = default)
    {
        if (!File.Exists(inputFilePath))
        {
            throw new ArgumentException("Input file does not exist!", nameof(inputFilePath));
        }
        if (keyBytes.Length != KeySizeInBytes)
        {
            throw new ArgumentException("Key must be 32 bytes (256 bits) in length!", nameof(keyBytes));
        }
        using var aes = Aes.Create();
        aes.BlockSize = AesBlockSize;
        aes.KeySize = AesKeySize;
        aes.Key = keyBytes;
        await using FileStream outFileStream = new(outputFilePath, FileMode.Create);
        // Write initialization vector to beginning of file
        await outFileStream.WriteAsync(aes.IV.AsMemory(0, aes.IV.Length), token);
        ICryptoTransform encryptor = aes.CreateEncryptor();
        await using CryptoStream cryptoStream = new(
            outFileStream,
            encryptor,
            CryptoStreamMode.Write);
        await using var inputFileStream = new FileStream(inputFilePath, FileMode.Open);
        await inputFileStream.CopyToAsync(cryptoStream, token);
    }
    /// <summary>
    /// Decrypts a file using a 32 character key.
    /// </summary>
    public static Task DecryptAsync(string inputFilePath, string outputFilePath, string key, CancellationToken token = default)
    {
        if (string.IsNullOrWhiteSpace(key))
        {
            throw new ArgumentException("Key cannot be empty!", nameof(key));
        }
        byte[] keyBytes = Encoding.UTF8.GetBytes(key);
        return DecryptAsync(inputFilePath, outputFilePath, keyBytes, token);
    }
    public static async Task DecryptAsync(string inputFilePath, string outputFilePath, byte[] keyBytes, CancellationToken token = default)
    {
        if (!File.Exists(inputFilePath))
        {
            throw new ArgumentException("Input file does not exist!", nameof(inputFilePath));
        }
        if (keyBytes.Length != KeySizeInBytes)
        {
            throw new ArgumentException("Key must be 32 bytes (256 bits) in length!", nameof(keyBytes));
        }
        await using var inputFileStream = new FileStream(inputFilePath, FileMode.Open);
        // Read IV from beginning of file
        const int blockSizeInBytes = AesBlockSize / 8;
        var initializationVector = new byte[blockSizeInBytes];
        int ivBytesRead = await inputFileStream.ReadAsync(initializationVector.AsMemory(0, blockSizeInBytes), token);
        if (ivBytesRead != initializationVector.Length)
        {
            throw new ArgumentException("Failed to read initialization vector from input file!", nameof(inputFilePath));
        }
        using var aes = Aes.Create();
        aes.BlockSize = AesBlockSize;
        aes.IV = initializationVector;
        aes.KeySize = AesKeySize;
        aes.Key = keyBytes;
        ICryptoTransform decryptor = aes.CreateDecryptor();
        await using CryptoStream cryptoStream = new(
            inputFileStream,
            decryptor,
            CryptoStreamMode.Read);
        await using FileStream outFileStream = new(outputFilePath, FileMode.Create);
        await cryptoStream.CopyToAsync(outFileStream, token);
    }
}

我也没有测试过取消,但我不明白为什么它不起作用。不用说,你应该自己做测试:-)

用法:

var inputFile = @"C:'tmp'test.txt";
var outputFile = @"C:'tmp'test.encrypted";
var password = "abcde-fghij-klmno-pqrst-uvwxy-z0"; // must be 32 chars (256 / 8 = 32 bytes)
await FileEncryptor.EncryptAsync(inputFile, outputFile, password);
await FileEncryptor.DecryptAsync(outputFile, @"C:'tmp'decrypted.txt", password);

为了支持多个密钥大小,我想我们可以像IV一样将其写入文件的开头,但对于我的需求来说,这已经足够了。