简体   繁体   English

如何在C#中执行SHA1文件校验和?

[英]How do I do a SHA1 File Checksum in C#?

如何在文件上使用SHA1CryptoServiceProvider()来创建文件的SHA1校验和?

using (FileStream fs = new FileStream(@"C:\file\location", FileMode.Open))
using (BufferedStream bs = new BufferedStream(fs))
{
    using (SHA1Managed sha1 = new SHA1Managed())
    {
        byte[] hash = sha1.ComputeHash(bs);
        StringBuilder formatted = new StringBuilder(2 * hash.Length);
        foreach (byte b in hash)
        {
            formatted.AppendFormat("{0:X2}", b);
        }
    }
}

formatted contains the string representation of the SHA-1 hash. formatted包含SHA-1哈希的字符串表示形式。 Also, by using a FileStream instead of a byte buffer, ComputeHash computes the hash in chunks, so you don't have to load the entire file in one go, which is helpful for large files. 此外,通过使用FileStream而不是字节缓冲区, ComputeHash以块的ComputeHash计算散列,因此您不必一次性加载整个文件,这对大文件很有用。

With the ComputeHash method. 使用ComputeHash方法。 See here: 看这里:

ComputeHash ComputeHash

Example snippet: 示例代码段:

using(var cryptoProvider = new SHA1CryptoServiceProvider())
{
    string hash = BitConverter
            .ToString(cryptoProvider.ComputeHash(buffer));

    //do something with hash
}

Where buffer is the contents of your file. 缓冲区是文件的内容。

If you are already reading the file as a stream, then the following technique calculates the hash as you read it. 如果您已经将文件作为流读取,则以下技术会在您读取时计算哈希值。 The only caveat is that you need to consume the whole stream. 唯一需要注意的是,你需要消耗整个流。

class Program
    {
        static void Main(string[] args)
        {
            String sourceFileName = "C:\\test.txt";
            Byte[] shaHash;

            //Use Sha1Managed if you really want sha1
            using (var shaForStream = new SHA256Managed())
            using (Stream sourceFileStream = File.Open(sourceFileName, FileMode.Open))
            using (Stream sourceStream = new CryptoStream(sourceFileStream, shaForStream, CryptoStreamMode.Read))
            {
                //Do something with the sourceStream 
                //NOTE You need to read all the bytes, otherwise you'll get an exception ({"Hash must be finalized before the hash value is retrieved."}) 
                while(sourceStream.ReadByte() != -1);                
                shaHash = shaForStream.Hash;
            }

            Console.WriteLine(Convert.ToBase64String(shaHash));
        }
    }

Also you can try: 你也可以尝试:

FileStream fop = File.OpenRead(@"C:\test.bin");
string chksum = BitConverter.ToString(System.Security.Cryptography.SHA1.Create().ComputeHash(fop));

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

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