Click here to Skip to main content
13,090,418 members (61,804 online)
Click here to Skip to main content
Add your own
alternative version


10 bookmarked
Posted 2 Aug 2013

C# hash creator (modified version from MSDN)

, 2 Aug 2013
Rate this:
Please Sign up or sign in to vote.
Easier GetHash function in System.Security.Cryptography.


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.


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

string str = GetHash<MD5>(text, Encoding.UTF8)
string str = GetHash<SHA256>(text, Encoding.UTF8)
string str = GetHash<SHA512>(text, Encoding.UTF8)
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++)
    // Return the hexadecimal string. 
    return sBuilder.ToString();


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


About the Author

Software Developer
United States United States
No Biography provided

You may also be interested in...

Comments and Discussions

GeneralMy vote of 3 Pin
satish koladiya26-Aug-13 23:41
professionalsatish koladiya26-Aug-13 23:41 
GeneralMy vote of 2 Pin
Joe Gakenheimer )2-Aug-13 2:56
memberJoe Gakenheimer )2-Aug-13 2:56 
GeneralRe: My vote of 2 Pin
steven-_-song2-Aug-13 3:01
membersteven-_-song2-Aug-13 3:01 
GeneralRe: My vote of 2 Pin
Master.Man19802-Aug-13 9:33
memberMaster.Man19802-Aug-13 9:33 
QuestionImprove performance Pin
Petoj872-Aug-13 2:30
memberPetoj872-Aug-13 2:30 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.170813.1 | Last Updated 2 Aug 2013
Article Copyright 2013 by steven-_-song
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid