Replacement function for FormsAuthentication. HashPasswordForStoringInConfigFile

From .Net 4.5 version Microsoft deprecates the
System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile function which is used to create the hash of a string generally for password. Following is the extension method which gives the same output as FormsAuthentication.HashPasswordForStoringInConfigFile.
/// <summary>
/// Returns the hash of the given string. 
/// </summary>
/// <param name="stringToHash" />string for which the hash should be generated
/// <param name="hashAlgorithm" />Hash algorithm. Ex: MD5, SHA1, SHA256, SHA384, SHA512
/// <returns></returns>
public static string GetHash(this string stringToHash, string hashAlgorithm)
{
   var algorithm = System.Security.Cryptography.HashAlgorithm.Create(hashAlgorithm);
   byte[] hash = algorithm.ComputeHash(System.Text.Encoding.UTF8.GetBytes(stringToHash));

   // ToString("x2")  converts byte in hexadecimal value
   string encryptedVal = string.Concat(hash.Select(b => b.ToString("x2"))).ToUpperInvariant();
   return encryptedVal;
}
Happy Coding 😊!!

Gopikrishna

    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment