Possible to calculate MD5 (or other) hash with buffered reads?

后端 未结 5 1697
长情又很酷
长情又很酷 2020-11-27 03:37

I need to calculate checksums of quite large files (gigabytes). This can be accomplished using the following method:

    private byte[] calcHash(string file         


        
5条回答
  •  天命终不由人
    2020-11-27 04:14

    I like the answer above but for the sake of completeness, and being a more general solution, refer to the CryptoStream class. If you are already handling streams, it is easy to wrap your stream in a CryptoStream, passing a HashAlgorithm as the ICryptoTransform parameter.

    var file = new FileStream("foo.txt", FileMode.Open, FileAccess.Write);
    var md5 = MD5.Create();
    var cs = new CryptoStream(file, md5, CryptoStreamMode.Write);
    while (notDoneYet)
    {
        buffer = Get32MB();
        cs.Write(buffer, 0, buffer.Length);
    }
    System.Console.WriteLine(BitConverter.ToString(md5.Hash));
    

    You might have to close the stream before getting the hash (so the HashAlgorithm knows it's done).

提交回复
热议问题