gpt4 book ai didi

c# - 如何散列文件的前 N ​​个字节?

转载 作者:行者123 更新时间:2023-11-30 13:34:18 25 4
gpt4 key购买 nike

使用 .net,我希望能够散列可能大文件的前 N ​​个字节,但我似乎找不到这样做的方法。

ComputeHash 函数(我使用的是 SHA1)采用字节数组或流,但流似乎是执行此操作的最佳方式,因为我不希望将可能很大的文件加载到内存中。

明确:如果可以的话,我不想将可能很大的数据加载到内存中。如果文件是 2GB,而我想对前 1GB 进行哈希处理,那将占用大量 RAM!

最佳答案

您可以使用 CryptoStream 对大量数据进行哈希处理 - 像这样的方法应该可行:

var sha1 = SHA1Managed.Create();

FileStream fs = \\whatever
using (var cs = new CryptoStream(fs, sha1, CryptoStreamMode.Read))
{
byte[] buf = new byte[16];
int bytesRead = cs.Read(buf, 0, buf.Length);
long totalBytesRead = bytesRead;

while (bytesRead > 0 && totalBytesRead <= maxBytesToHash)
{
bytesRead = cs.Read(buf, 0, buf.Length);
totalBytesRead += bytesRead;
}
}

byte[] hash = sha1.Hash;

关于c# - 如何散列文件的前 N ​​个字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3441338/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com