How do I do a SHA1 File Checksum in C#?

前端 未结 4 1260
鱼传尺愫
鱼传尺愫 2020-11-27 12:45

How do I use the SHA1CryptoServiceProvider() on a file to create a SHA1 Checksum of the file?

4条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-27 13:13

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

提交回复
热议问题