【发布时间】:2017-06-03 17:01:57
【问题描述】:
我是加密新手,正在使用以下方法加密文件:
private static void encryptFile(string filePath, byte[] password, byte[] salt)
{
Rfc2898DeriveBytes rdb = new Rfc2898DeriveBytes(password, salt, 1000);
AesManaged algorithm = new AesManaged();
byte[] rgbKey = rdb.GetBytes(algorithm.KeySize / 8);
byte[] rgbIV = rdb.GetBytes(algorithm.BlockSize / 8);
GCHandle keyHandle = GCHandle.Alloc(rgbKey, GCHandleType.Pinned);
GCHandle IVHandle = GCHandle.Alloc(rgbIV, GCHandleType.Pinned);
ICryptoTransform cryptoAlgorithm = algorithm.CreateEncryptor(rgbKey, rgbIV);
using (FileStream readStream = File.Open(filePath, FileMode.Open))
{
using (FileStream writeStream = new FileStream(filePath + ".enc", FileMode.Create, FileAccess.Write))
{
using (CryptoStream cryptoStream = new CryptoStream(writeStream, cryptoAlgorithm, CryptoStreamMode.Write))
{
while (readStream.Position < readStream.Length)
{
byte[] buffer = new byte[4096];
int amountRead = readStream.Read(buffer, 0, buffer.Length);
cryptoStream.Write(buffer, 0, amountRead);
}
cryptoStream.Flush();
}
}
}
UtilityMethods.destroyBytes(rgbKey);
UtilityMethods.destroyBytes(rgbIV);
keyHandle.Free();
IVHandle.Free();
}
我想做的是多线程处理以加快加密速度。使用单线程,加密一个约 3GB 的文件需要 5 分钟。如果可能的话,我希望能够在 1 分钟内完成加密(在 30 秒内会很棒,但我想我可能会延长)。
我相信答案是创建多个流(虽然我不确定),为每个流分配一个文件块进行加密,但我不确定如何“将文件分开”以分配一个块到每个流,或在每个部分通过分配给它的流之后“将文件重新组合在一起”。有人能指出我正确的方向吗?
非常感谢!
附:我看过这个(Rijndael algorithm and CryptoStream: is it possible to encrypt / decrypt multithreaded?),但我不明白答案(ECB,CBC?)。如果我的问题的答案就在那里,您能否提供一些示例代码让我朝着正确的方向前进?
再次感谢!
【问题讨论】:
-
并行/多线程加密只能通过 ECB 实现,否则单个块相互依赖。关于 ECB、CBC:请参阅 Encryption operating modes: ECB vs CBC 和 CipherMode Enumeration。另请注意有关 ECB 的评论:“重要提示:不建议使用此模式,因为它为多种安全漏洞打开了大门。”
-
这可能是 I/O 问题而不是 CPU 问题。在不同的物理磁盘或 SSD 上尝试输入和输出相同的代码,您会看到更好的性能。
标签: c# multithreading encryption