Calculating a MD5, SHA1, SHA256, SHA384, SHA512 Hash in C#

Following up on my Creating a Hash in Java post, here I am giving another implementation through a simple function for calculating a Hash in C#.

Here’s the code:

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

public String computeHash(String message, String algo) {
	byte[] sourceBytes = Encoding.Default.GetBytes(message);
	byte[] hashBytes = null;
	Console.WriteLine(algo);
	switch(algo.Trim().ToUpper()) {
		case "MD5":
			hashBytes = MD5CryptoServiceProvider.Create().ComputeHash(sourceBytes);
			break;
		case "SHA1":
			hashBytes = SHA1Managed.Create().ComputeHash(sourceBytes);
			break;
		case "SHA256":
			hashBytes = SHA256Managed.Create().ComputeHash(sourceBytes);
			break;
		case "SHA384":
			hashBytes = SHA384Managed.Create().ComputeHash(sourceBytes);
			break;
		case "SHA512":
			hashBytes = SHA512Managed.Create().ComputeHash(sourceBytes);
			break;
		default:
			break;
	}
	StringBuilder sb = new StringBuilder();
	for(int i = 0 ; hashBytes != null && i < hashBytes.Length ; i++) {
		sb.AppendFormat("{0:x2}", hashBytes[i]);
	}
	return sb.ToString();
}
comments powered by Disqus