首页 > 解决方案 > 如何加快 C# 中的文件加密?

问题描述

我正在创建一个程序,该程序将使用System.Security.Cryptography. 为简单起见,我只是从下面的加密方法中给出一个片段。该进程以 768MB 块读取文件 ( const int CHUNK_SIZE = 768 * 1024 * 1024) 但加密超过 2GB 的文件大约需要 50 秒。

有没有办法将此过程分解为多个线程以更快地加密文件数据?也许每个线程在哪里读取文件的下一部分?

CipherModeCBC和 Padding 是PKCS7.

using (var rStream = new FileStream(path, FileMode.Open, FileAccess.Read))
{
    using (var wStream = new FileStream(path + DEFAULT_FILE_EXTENSION, FileMode.CreateNew, FileAccess.Write))
    {
        using (var cStream = new CryptoStream(wStream, transformEncrypt, CryptoStreamMode.Write))
        {
            var buffer = new byte[CHUNK_SIZE];
            rStream.Seek(0, SeekOrigin.Begin);
            int bytesRead = rStream.Read(buffer, 0, CHUNK_SIZE);
            while (bytesRead > 0)
            {
                cStream.Write(buffer, 0, bytesRead);
                bytesRead = rStream.Read(buffer, 0, bytesRead);
            }
        }
    }
}

标签: c#cryptographyfilestream

解决方案


推荐阅读