Using the code:
The complete code is given below. The enum EncodeStyle is used to determine what encoding should be applied on output hash value. SHA1HashEncode is the main utility function which uses SHA1CryptoServiceProvider class to provide hashing. This function takes two input arguments 1) path of file which need to be hashed and 2) encoding style of outputed hash value. Call this function from your main program.
using System;
using System.IO;
using System.Security.Cryptography;
public enum EncodeStyle
{
Dig,
Hex,
Base64
};
static string ByteArrayToString(byte[] arrInput, EncodeStyle encode)
{
int i;
StringBuilder sOutput = new StringBuilder(arrInput.Length);
if(EncodeStyle.Base64 == encode)
{
return Convert.ToBase64String(arrInput);
}
for (i = 0; i < arrInput.Length; i++)
{
switch(encode)
{
case EncodeStyle.Dig:
sOutput.Append(arrInput[i].ToString("D3"));
break;
case EncodeStyle.Hex:
sOutput.Append(arrInput[i].ToString("X2"));
break;
}
}
return sOutput.ToString();
}
static string SHA1HashEncode(string filePath, EncodeStyle encode)
{
SHA1 a = new SHA1CryptoServiceProvider();
byte[] arr = new byte[60];
string hash = "";
using (StreamReader sr = new StreamReader(filePath))
{
arr = a.ComputeHash(sr.BaseStream);
hash = ByteArrayToString(arr, encode);
}
return hash;
}