Wednesday, October 13, 2010

Class File For Hashing Value Using SHA256 Algorithum

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

namespace Hash
{
public class Hash
{
public Hash() { }

public enum HashType : int
{
MD5,
SHA1,
SHA256,
SHA512
}

public static string GetHash(string text, HashType hashType, string key)
{
string hashString;
switch (hashType)
{
case HashType.MD5:
hashString = GetMD5(text);
break;
case HashType.SHA1:
hashString = GetSHA1(text);
break;
case HashType.SHA256:
hashString = GetSHA256(text, key);
break;
case HashType.SHA512:
hashString = GetSHA512(text);
break;
default:
hashString = "Invalid Hash Type";
break;
}
return hashString;
}

public static bool CheckHash(string original, string hashString, HashType hashType, string key)
{
string originalHash = GetHash(original, hashType, key);
return (originalHash == hashString);
}

private static string GetMD5(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);

MD5 hashString = new MD5CryptoServiceProvider();
string hex = "";

hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}

private static string GetSHA1(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);

SHA1Managed hashString = new SHA1Managed();
string hex = "";

hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}

private static string GetSHA256(string text, string key)
{


UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;

byte[] message = UE.GetBytes(text);
byte[] hashkey = UE.GetBytes(key);

HMACSHA256 hashString = new HMACSHA256(hashkey);

//SHA256Managed hashString = new SHA256Managed();
string hex = "";

hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}

private static string GetSHA512(string text)
{
UnicodeEncoding UE = new UnicodeEncoding();
byte[] hashValue;
byte[] message = UE.GetBytes(text);

SHA512Managed hashString = new SHA512Managed();
string hex = "";

hashValue = hashString.ComputeHash(message);
foreach (byte x in hashValue)
{
hex += String.Format("{0:x2}", x);
}
return hex;
}
}
}

No comments: