如何向现有哈希添加值?

时间:2011-09-19 20:19:09

标签: c# hash

例如,我使用:

执行“hashable”的MD5
        protected string hexHashMD5(byte[] filePart) {
        // Now that we have a byte array we can ask the CSP to hash it
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] result = md5.ComputeHash(filePart);

        // Build the final string by converting each byte
        // into hex and appending it to a StringBuilder
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < result.Length; i++) {
            sb.Append(result[i].ToString("X2"));
        }

        // And return it
        return sb.ToString();
    }

并将其输出存储到程序中的字符串变量中。如何使用Hash并添加另一个byte []来创建新哈希?

我被告知你可以使用文件流,一次自动流式传输,并制作完整的哈希值,但是当我需要将两个单独的文件一起哈希时会发生什么?

1 个答案:

答案 0 :(得分:1)

您可以创建一个自定义Stream类,按顺序读取两个流,然后将其传递给ComputeHash

或者,您可以一次读取一个块的两个流,并将每个块传递给TransformBlock

byte[] buffer = new byte[4096];
while (true) {
    int read = stream1.Read(buffer, 0, buffer.Length);
    if (read == 0) break;
    hash.TransformBlock(buffer, 0, read, null, 0);
}

while (true) {
    int read = stream2.Read(buffer, 0, buffer.Length);
    if (read == 0) break;
    hash.TransformBlock(buffer, 0, read, null, 0);
}

hash.TransformFinalBlock(new byte[0], 0, 0);
var hashCode = hash.Hash;