简体   繁体   English

如何为现有哈希添加值?

[英]How do I add a value to an existing hash?

For instance, I do an MD5 of "hashable" using: 例如,我使用以下命令执行“可哈希”的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();
    }

and store it's output into a string variable in my program. 并将其输出存储到程序中的字符串变量中。 How can I take that Hash and add another byte[] to create a new hash? 如何获取该哈希并添加另一个byte []以创建一个新哈希?

I've been told that you can use file stream, to automatically stream in a bit at a time, and make the full hash, but what happens when I need to hash two separate files together? 有人告诉我,您可以使用文件流,一次自动进行一次流传输,并进行完整的散列,但是当我需要将两个单独的文件散列在一起时会发生什么呢?

You can make a custom Stream class that reads the two streams in order, then pass that to ComputeHash . 您可以创建一个自定义Stream类,该类按顺序读取两个流,然后将其传递给ComputeHash

Alternatively, you can read both streams one block at a time and pass each block to TransformBlock : 另外,您可以一次读取两个数据流,并将每个数据块传递给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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM