Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / security / encryption

C# hash creator (modified version from MSDN)

4.27/5 (6 votes)
2 Aug 2013CPOL 16.8K  
Easier GetHash function in System.Security.Cryptography.

Introduction

A simple modification to make MSDN Hash generator a more generic and easier function. Note: the code originated from MSDN, I only did some inheritance modification to make it easier to use.

Background 

I was about to make a hash generator for fun. However, when I look at the GetHash function on MSDN, I don't want to make a new GetHash function for every type. Therefore, I make this code.

Using the code  

To use the function "GetHash<T>(string input, Encoding encoding)", just call

C#
string str = GetHash<MD5>(text, Encoding.UTF8)
//Or
string str = GetHash<SHA256>(text, Encoding.UTF8)
//Or
string str = GetHash<SHA512>(text, Encoding.UTF8)
C#
using System.Security.Cryptography;
private static string GetHash<T>(string input, Encoding encoding) where T:HashAlgorithm
{
    //create a Hash object
    T hashobj = (T)HashAlgorithm.Create(typeof(T).ToString());
    // Convert the input string to a byte array and compute the hash. 
    byte[] data = hashobj.ComputeHash(encoding.GetBytes(input));
    // Create a new Stringbuilder to collect the bytes
    StringBuilder sBuilder = new StringBuilder();
    // Loop through each byte of the hashed data  
    // and format each one as a hexadecimal string. 
    for (int i = 0; i < data.Length; i++)
        sBuilder.Append(data[i].ToString("x2"));
    // Return the hexadecimal string. 
    return sBuilder.ToString();
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)