Library code snippets
Create Hashes - MD5, SHA1, SHA256, SHA384, SHA512
Now, in PHP it's as easy as using md5() or sha1(). But in C# it takes a bit more work. This is what we want to simplify.
So we'll create a Hash class to create hashes.
Create a new project and add a class (Hash).
using System;
using System.Security.Cryptography;
using System.Text;
namespace Hash {
public class Hash {
public Hash() { }
} /* Hash */
} /* Hash */
Let's start by adding an enum representing all the hash functions we are going to support.
public enum HashType :int { MD5, SHA1, SHA256, SHA384, SHA512 }
Our class will have 2 public methods, one for creating a hash and one for checking a hash against a given text.
First we'll create the GetHash method:
public static string GetHash(string strPlain, HashType hshType) {
string strRet;
switch (hshType) {
case HashType.MD5: strRet = GetMD5(strPlain); break;
case HashType.SHA1: strRet = GetSHA1(strPlain); break;
case HashType.SHA256: strRet = GetSHA256(strPlain); break;
case HashType.SHA384: strRet = GetSHA384(strPlain); break;
case HashType.SHA512: strRet = GetSHA512(strPlain); break;
default: strRet = "Invalid HashType"; break;
}
return strRet;
} /* GetHash */
And our CheckHash will depend on this so we might as well add it now.
public static bool CheckHash(string strOriginal, string strHash, HashType hshType) {
string strOrigHash = GetHash(strOriginal, hshType);
return (strOrigHash == strHash);
} /* CheckHash */
As you can see, I created 5 seperate methods to create hashes. I'll explain one for this article, the others are the same but use another hashing class. You'll find them in the source at the end of this article.
A hash function works on a byte array, so we will create two arrays, one for our resulting hash and one for the given text.
UnicodeEncoding UE = new UnicodeEncoding();
byte[] HashValue, MessageBytes = UE.GetBytes(strPlain);
Now we create an object that will hash our text:
SHA1Managed SHhash = new SHA1Managed();
And finally we calculate the hash and convert it to a hexadecimal string. Which we can store in a database for example.
string strHex = "";
HashValue = SHhash.ComputeHash(MessageBytes);
foreach(byte b in HashValue) {
strHex += String.Format("{0:x2}", b);
}
return strHex;
This is how we test it:
static void Main(string[] args) {
String hash = Hash.Hash.GetHash("This is a sample text :p", Hash.Hash.HashType.SHA256);
Console.WriteLine(hash);
Console.WriteLine(Hash.Hash.CheckHash("This is a sample text :p", hash, Hash.Hash.HashType.SHA256));
Console.WriteLine(Hash.Hash.CheckHash("This is a wrong text.", hash, Hash.Hash.HashType.SHA256));
} /* Main */
Now we have our sweet and simple methods available as a class, ready to be used in any project.
I've uploaded the sources again, you will see I documented it as well. When you use NDoc on the generated .xml file you get a very sweet MSDN like documentation.
Related articles
Related discussion
-
looking for help on asp
by cladironbeard (2 replies)
-
Socket Programming in C# - Part 1
by graumanoz (23 replies)
-
LINQ in Action
by naser1 (0 replies)
-
Creating a Windows Service in VB.NET
by Templario55 (107 replies)
-
simple vb to c#, help please
by lksath (1 replies)
Related podcasts
-
Object-Oriented Programming in Ruby
In this episode, I talk with Scott Bellware about object-oriented programming in Ruby, and Ruby's object model. This is taken from a private conversation, and the audio quality suffers at times. Much thanks to Scott for allowing this to be released.This episode of the Alt.NET Podcast is bro...
Events coming up
-
Aug
28
St. Louis Day of .NET
St. Charles, United States
Technical conference with be 2 full days of content with over 40 sessions from local and national speakers, with topics such as:•.NET languages: C#, VB.NET•Technologies: WPF, Silverlight, WCF•Development tools: Visual Studio, TFS, Expression Blend
I'm sure you've found the answer by now, but in case anybody else is on the same quest, maybe this will help:
Porting the Equivalent of PHP’s MD5 to .NET platform in C#
Maybe you will find this post adds more light to the issue.
Hi just like jitz I am struggling to realise a result that matches the SHA1 result when using php can anybody help clarify how to get the same result pls
but when I tried generated any others it gave me a diffrent hash every time(SHA256,SHA384 and SHA512)...
Hi,
I'm using SHA1 to hash the some code in vb.net(desktop app). but when i create SHA1 in PHP it doesn't match with the one i created with vb.net.I filtered out all the special chars in hash generated using vb.net (like =,+ etc).The hash thus trimmed out is only 20-22 chars but when i used php itz above 30. Pls help me
Tom
Thanks a lot
Note, the author wrote that the result of a Hash is unique. This is NEVER the case for a hash function. Hashes are consistent. Given a hash function H and a value a, H(a) = H(a) (i.e., hashes aren't random in a way which varies invocation to invocation.
But given a,b with a!=b it is not true that H(a) != H(b). Indeed for any digest hash one can find a,b with a!=b and H(a) = H(b).
BE WARNED. Never hash something that is used as a primary key. E.g., HASH passwords but never hash usernames.
To get the same result as the md5() function in PHP, use ASCIIEncoding!
As in: ASCIIEncoding UE = new ASCIIEncoding();
Another note:
Yes, there is a simpeler way to do md5 and sha1, but if i have a class for SHA256, 384 and 512, I'd like to combine all of them into one
For SHA1 and MD5 you can simply use:
string hashedText = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile("some text", "sha1");
This thread is for discussions of Create Hashes - MD5, SHA1, SHA256, SHA384, SHA512 .