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

时间:2010-01-03 03:45:10

标签: c# .net sha1 checksum

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

4 个答案:

答案 0 :(得分:73)

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包含SHA-1哈希的字符串表示形式。此外,通过使用FileStream而不是字节缓冲区,ComputeHash计算块中的散列,因此您不必一次加载整个文件,这对大文件很有帮助。 / p>

答案 1 :(得分:60)

使用ComputeHash方法。见这里:

ComputeHash

示例摘录:

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

    //do something with hash
}

缓冲区是文件的内容。

答案 2 :(得分:5)

如果您已经将文件作为流读取,则以下技术会在您阅读时计算哈希值。唯一需要注意的是,你需要消耗整个流。

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));
        }
    }

答案 3 :(得分:2)

你也可以尝试:

IEnumerable