如果您知道您真正想要读取多少数据(即长度 - 28 字节),那么当您计算哈希时,只输入那么多数据。您还没有确切说明您是如何计算哈希的,但您通常可以重复地将更多数据“写入”到哈希计算中 - 只要您需要,就这样做,直到您到达最后 28 个字节。
样本:
public byte[] Sha1ExceptEnd(Stream input, int bytesToOmit)
{
long bytesToRead = input.Length - bytesToOmit;
byte[] buffer = new byte[16 * 1024]; // Hash up to 16K at a time
using (SHA1 sha1 = SHA1.Create())
{
while (bytesToRead > 0)
{
int thisPass = (int) Math.Min(buffer.Length, bytesToRead);
int bytesReadThisPass = input.Read(buffer, 0, thisPass);
if (bytesReadThisPass <= 0)
{
throw new IOException("Unexpected end of data");
}
sha1.TransformBlock(buffer, 0, bytesReadThisPass, buffer, 0);
bytesToRead -= bytesReadThisPass;
}
// Flush the hash
sha1.TransformFinalBlock(buffer, 0, 0);
return sha1.Hash;
}
}