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

如何在文件上使用SHA1CryptoServiceProvider()来创build文件的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包含SHA-1散列的string表示forms。 此外,通过使用FileStream而不是字节缓冲区, ComputeHash以块为ComputeHash计算散列,因此您不必一次加载整个文件,这对于大文件很有帮助。

用ComputeHash方法。 看这里:

ComputeHash

示例代码片段:

 using(var cryptoProvider = new SHA1CryptoServiceProvider()) { string hash = BitConverter .ToString(cryptoProvider.ComputeHash(buffer)); //do something with hash } 

哪里缓冲区是您的文件的内容。

如果您已经以stream的forms读取文件,那么以下技术会在读取散列时进行计算。 唯一的警告是你需要消耗整个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)); } } 

你也可以尝试:

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