C# code blocks: getting the SHA1 hash from a string easily

Posted: (EET/GMT+2)

 

In case you need a quick was to get the SHA1 hash from a string, here's a nice way to do it:

using System.Security.Cryptography;
using System.Text;
...

private string GetSha1Hash(string input)
{
  SHA1CryptoServiceProvider sha1 = new SHA1CryptoServiceProvider();
  byte[] inputBytes = Encoding.ASCII.GetBytes(input);
  byte[] hash = sha1.ComputeHash(inputBytes);
  StringBuilder results = new StringBuilder();
  foreach (byte singleByte in hash)
  {
    results.Append(singleByte.ToString("x2"));
  }
  return results.ToString();
}

Calling this method is also super-simple, as you need to only pass in your input data. Note that above, the ASCII encoding is used, this is good for U.S. based regular text. But if you wanted to chance this to UTF-8 for instance, you could change the encoding class used on the second line of the method. For instance:

byte[] inputBytes = Encoding.UTF8.GetBytes(input);

What kind of string does this method return? Here are two examples:

GetSha1Hash(""):  da39a3ee5e6b4b0d3255bfef95601890afd80709
GetSha1Hash("A"): 6dcd4ce23d88e2ee9568ba546c007c63d9131c1b

The hash has always the length of 40 characters.

Good luck. Remember your salt! :-)