You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET 7下如何用ChaCha20Poly1305流式加密大文件(无外部库)

流式处理ChaCha20Poly1305大文件加密解密(.NET 7)

.NET 7中ChaCha20Poly1305虽无直接的流重载,但可通过CreateEncryptor/CreateDecryptor获取ICryptoTransform,结合CryptoStream实现流式分块处理,完全无需加载整个文件到内存。以下是具体实现:

加密实现

using System.Security.Cryptography;

public static void EncryptFile(string inputFilePath, string outputFilePath, byte[] key)
{
    // 生成12字节随机nonce(ChaCha20Poly1305标准要求长度)
    byte[] nonce = new byte[12];
    RandomNumberGenerator.Fill(nonce);

    using (var inputStream = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read))
    using (var outputStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write))
    using (var chacha = new ChaCha20Poly1305(key))
    {
        // 将nonce写入输出文件开头,解密时需读取该值
        outputStream.Write(nonce, 0, nonce.Length);

        // 创建加密器并绑定密钥、nonce
        using (var encryptor = chacha.CreateEncryptor(key, nonce))
        using (var cryptoStream = new CryptoStream(outputStream, encryptor, CryptoStreamMode.Write))
        {
            // 流式复制输入数据到加密流,自动分块处理
            inputStream.CopyTo(cryptoStream);
        }
        // CryptoStream销毁时会自动追加Poly1305验证标签到输出流末尾
    }
}

解密实现

using System.Security.Cryptography;

public static void DecryptFile(string inputFilePath, string outputFilePath, byte[] key)
{
    using (var inputStream = new FileStream(inputFilePath, FileMode.Open, FileAccess.Read))
    using (var outputStream = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write))
    {
        // 读取文件开头的12字节nonce
        byte[] nonce = new byte[12];
        int bytesRead = inputStream.Read(nonce, 0, nonce.Length);
        if (bytesRead != nonce.Length)
        {
            throw new InvalidDataException("无效加密文件:nonce读取失败");
        }

        using (var chacha = new ChaCha20Poly1305(key))
        // 创建解密器并绑定密钥、nonce
        using (var decryptor = chacha.CreateDecryptor(key, nonce))
        using (var cryptoStream = new CryptoStream(inputStream, decryptor, CryptoStreamMode.Read))
        {
            // 流式复制加密流数据到输出流,自动验证标签并解密
            cryptoStream.CopyTo(outputStream);
        }
        // CryptoStream销毁时自动验证Poly1305标签,验证失败抛出CryptographicException
    }
}

使用示例

// 生成256位(32字节)随机密钥(实际应用需妥善存储,不可丢失)
byte[] key = new byte[32];
RandomNumberGenerator.Fill(key);

// 加密大文件
EncryptFile(@"D:\large-file.raw", @"D:\large-file.encrypted", key);

// 解密文件
DecryptFile(@"D:\large-file.encrypted", @"D:\large-file-decrypted.raw", key);

关键注意事项

  • 密钥安全:256位密钥需通过加密配置文件、密钥管理服务等方式妥善存储,绝对不能硬编码到代码中。
  • Nonce唯一性:每次加密必须生成新的12字节随机nonce,禁止重复使用同一密钥+nonce组合,否则会完全破坏加密安全性。
  • 性能优化:CopyTo默认缓冲区为81920字节,可根据实际需求调整(如设为128KB)提升大文件处理速度:inputStream.CopyTo(cryptoStream, 1024 * 128);

内容的提问来源于stack exchange,提问作者Bird2

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 14:12:59