Compute String Hash : C# Extension method

Hashing is the technique of transforming a string of characters into a shorter fixed-length value or key that represents the original string. Hashing is a one-way conversion. You cannot convert the hash value back to original string. So it is good to store sensitive data like passwords as hash value. MD5, SHA1, SHA256, SHA384, and SHA512 are the commonly used hashing algorithms.

.NET framework provides the classes to create the hash values in System.Security.Cryptography namespace. Following is the extension method to compute the hash value of a string using MD5, SHA1, SHA256, SHA384, and SHA512 algorithms
using System;
using System.Text;
using System.Security.Cryptography;
public static class Extensions
{
 public static string ComputeHash(this string data, string hashAlogorithm)
 {
  byte[] bytes = null;
  switch (hashAlogorithm.ToLower())
  {
   case "md5":
    using (MD5 md5Hash = MD5.Create())
    {
     bytes = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(data));
    }
    break;
   case "sha1":
    using (SHA1 sha1Hash = SHA1.Create())
    {
     bytes = sha1Hash.ComputeHash(Encoding.UTF8.GetBytes(data));
    }
    break;
   case "sha256":
    using (SHA256 sha256Hash = SHA256.Create())
    {
     bytes = sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(data));
    }
    break;
   case "sha384":
    using (SHA384 sha384Hash = SHA384.Create())
    {
     bytes = sha384Hash.ComputeHash(Encoding.UTF8.GetBytes(data));
    }
    break;
   case "sha512":
    using (SHA512 sha512Hash = SHA512.Create())
    {
     bytes = sha512Hash.ComputeHash(Encoding.UTF8.GetBytes(data));
    }
    break;
  }
  
  if (bytes.Length > 0)
  {
   // Convert byte array to a string   
   StringBuilder builder = new StringBuilder();
   for (int i = 0; i < bytes.Length; i++)
   {
    builder.Append(bytes[i].ToString("x2"));
   }
   return builder.ToString();
  }
  else return null;
 }
}
Reference: https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography?view=netframework-4.8

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment