HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

The following method returns the MD5 hash for any given string. For instance for a password. It might be of some assistance when you're trying to validate user credentials but you don't want to store the password readable in the database.

For this method, you'll need the following using statements:

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

...

public
string EncodePassword(string originalPassword)
{
  //Declarations
  Byte[] originalBytes;
  Byte[] encodedBytes;
  MD5 md5;

  //Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
  md5 = new
MD5CryptoServiceProvider();
  originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
  encodedBytes = md5.ComputeHash(originalBytes);

  //Convert encoded bytes back to a 'readable' string
  return
BitConverter.ToString(encodedBytes);
}

Hmmm... I seem to write comments when I'm trying to explain something ;)

Published Wed, May 18 2005 2:40 PM by Rick van den Bosch
Filed under: ,

Comments

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Isn't it a lot easier to use the HashPasswordForStoringInConfigFile method of the FormsAuthentication class?

Wednesday, May 18, 2005 4:20 PM by Rick van den Bosch

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

That method does do the same, so it seems...

Friday, May 27, 2005 7:41 AM by Rick van den Bosch

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Thanks, I needed a way to get the byte[] md5 hash of a string password...worked great

Tuesday, August 22, 2006 2:05 PM by joe

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Your site is realy very interesting.

Wednesday, August 23, 2006 5:56 AM by Vlad

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Nice! I'lll use it on my site. -kak http://www.kennedyandkate.com

Friday, October 06, 2006 5:33 PM by kennedy & kate

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

As a side note: if you want to return a string without the dashes in them, replace the last statement with : return Regex.Replace(BitConverter.ToString(encodedBytes), "-", "");

Tuesday, November 07, 2006 3:51 PM by Kenshi

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

I have a problem, the password MD5 in my server OpenLDAP is saved with {MD5}o5c3WBNN50D/iYO5RJxcvw==, but to compare with the password in my aplication ASP.net the string is different, something so : j+ZGDCZGqIQtr/6+ZDxa4w==, somebody would help me in this case ?

Thursday, April 05, 2007 2:55 PM by RICK

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Hi, your code was very useful. however, i would like to enquire something. Is there any way the code your code for MD5 encrpytion be modified to produce an encrypted ouput of this format?

aTXuyYqHUUudx0Km2bsZKlH4/WM=

WEo/tELTiM0dVGGxgsF+5XmDr6s=

koOQgZFIppxqOVFsmWKiOSMJ3RY=

The password i have in my databse are of this format, and i am trying to find out how to insert new passwords as well as decrpyt passwords of this format.

I thank you in advance for your help. Thank you

Saturday, April 21, 2007 7:57 PM by Aaron

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

HI. the source code u provided for MD5 encrption was very useful. however, i would like to enquire if it was possible to make modifications to your coding such that the ouput encrpyted passwords were of this format.

SZCi/864aZZbnCv6hqp+FV/cUPw=

This is so as i am required to encode passwords as well as decode passwords of this format. Thank you very much in advance.

Sunday, April 22, 2007 12:58 AM by mousemee

# re: how to decode a hashed string

Hi, your code showed how to encode a string into a hased string. How do i do the reverse? input a hashed string and the original password is outputted?

Tuesday, April 24, 2007 5:47 AM by mousemee

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

TO: mousemee

You don't too that. You need a hashed-string to string database. There's LOTS of combinations that generate the same hash.

Tuesday, April 24, 2007 8:24 AM by John Doe

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Hi. is anybody familiar with using membership. crete user web service? I need a web service that adds in new users to database which consists of several tables. Thank you

Tuesday, April 24, 2007 10:01 PM by mousemee

# re: HOWTO: Decode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Please tell me, how decode a password using MD5 in c#/

Wednesday, May 16, 2007 2:27 AM by Ly

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

@ly: MD5 hashing only works one way. You can hash an entered string to see if its hash mathes the one in the database (or wherever). It is not possible to recover a password based on its MD5 hash.

Tuesday, May 22, 2007 1:53 PM by Rick van den Bosch

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

It is possible to get a collision for the computed hash with brute force possibly optimized to abandon invalid iteration branches. But that is a whole science and I am not a scientist in that field.

Remember MD5 is not considered safe for storing passwords, or security any more. Use some stronger hash instead (SHA). However it is still good enough to hash file to check if there is no mod.

Check out wikipedia: http://en.wikipedia.org/wiki/MD5

Thursday, May 24, 2007 8:22 AM by Robajz

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

I seriously doubt you can easily decode passwords encoded using MD5 (it is possible, but it may take you 10 million years...)

Why not just encrypt the entered password and then compare it against the record in the database?

Or am I missing something?

Tuesday, August 07, 2007 7:42 PM by Nurchi

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

It is now possible to "decode" passwords that use MD5 (It won't take you 10 million years either).

Computers are powerful enough now that you can use a rainbow table (a table for MD5 hashes for every combination of letters, numbers, and sometimes symbols, up to 14 characters) to check a hash against a rainbow table relatively easily. There's a program (the name escapes me at the moment) that will actually do this to crack windows passwords given their hash.

That is why it is important to salt your passwords before hashing. For example instead of this:

string hashedPass = MD5(password);

you would want to use this:

string hashedPass = MD5(aComplicatedSaltString + password);

Typically, a good salt would be the user's UserName and a programmer defined salt concatenated together.

That makes it harder to decode because then a hacker would have to add the salt when checking every password which would take the 10,000 years mentioned above (probably less than that, but still futile to attempt).

Sunday, September 23, 2007 6:32 PM by Dan

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Hi guys,

I'm using MD5 to encypt my site passwords but I want to implement a "Forget Password" feature.

Is it possible to decrypt the array of bytes to what the user had entered initialy?

Thanks.

Thursday, October 04, 2007 7:26 PM by Mihai

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Hi

Thanks for this help.

Wednesday, January 09, 2008 2:10 PM by Jahedur Rahman

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

If you're asking is it possible to simply reverse a hash the answer is NO.

A hash is a one-way function. It's simply a fixed-length "checksum" of sorts that is created based on the data presented. There is no reverse algorithm. That's the whole point.

The problem with trying to decode an MD5 hash is that it doesn't matter whether the message was three letters long or 500 pages long, the resulting hash it only 128 bits or 32 characters.

The most common way to crack MD5 hashed passwords is to use a program to systematically hash a dictionary or list of words (or random combinations of letters and numbers) until the resultant hash equals the hash you want to crack.

It's called a brute-force attack because you basically forcibly try every combination until you crack it.

If the password you are trying to crack is a simple or single word found in the dictionary, you can crack it in a matter of minutes or even seconds. If the password is long and complex, this method is typically fruitless.

That's why it is important to enforce complex password requirements of at least 8 characters, upper and lower case with at least one symbol (*&^, etc.

Tuesday, January 22, 2008 4:33 PM by Jeremy Ault

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Why doesn't this work in dot.net within a apxs file?  Where do I put the with statements?  In the script tag or within the <%@ tag?

Friday, February 08, 2008 10:48 AM by John Malcolm

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

can u please provide the code for decoding also...

encoding i did but i want to retrieve the encoded string from the database n compare it with the password field when the user logs in again for this i need to decode the string so tht it comes to its original value n then i can compare it with the password tht user enters...

reply asap

thanks

Tuesday, April 22, 2008 3:07 PM by mani

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

For everyone asking for how to decode hashes, YOU CAN'T.  That is the POINT.  You can hash a string and compare it to your already computed hash, that is IT.  Read a wikipedia on computer hashes for gods sake.

Also, to the original poster, Rick van den Bosch... shame on you for using ASCIIEncoding.Default.GetBytes().  You do realize that would seriously restrict the usefulness of your method to working only in languages that ASCII has the character sets for, right?

I suggest you read this article entitled:

The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)

www.joelonsoftware.com/.../Unicode.html

Thursday, May 29, 2008 2:14 AM by Simucal

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

mani, you do not "decode" a hashed password. It's impossible.  Hashing is not encryption.   Once hashed, you cannot restore it to the original password.

To test to see if the user entered the right password, you hash the password the user enters on the login screen, and compare the result to the password-hash stored in the database.

The benefit here is that even someone who can see into the database cannot know what the users password is.

The downside is that if a user looses their password, you cannot look it up to tell them.  You need to have the system generate a temp password and mail it to them.

Tuesday, June 03, 2008 1:07 AM by Chuck

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Thank you man. It work exactly as I needed.

Thursday, June 05, 2008 11:40 PM by sime

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

What is the length of the generated string ?

Is it fixed?

Somebody should know the length (at least the max) to

store this to database.

Tuesday, July 01, 2008 8:12 PM by ScRePt

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Thank u that was helpfull.

Tuesday, July 29, 2008 1:48 PM by MUFMS

# code for c#

i created a c# web form contains 2labels,2textboxes and button(ok).when click on ok in should verify the userid and  password fron sqlserver if the userid is correct the permit to go for next page.

for this i need code for that

Saturday, August 02, 2008 11:32 AM by madhava reddy

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

It was a very much helpfull stuff for me .

Now can you tell me how to decode the encoded password back.

Saturday, August 30, 2008 8:41 AM by Syed Nisar

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Thanks man!!! That was pretty useful.

Sunday, September 14, 2008 6:48 AM by Aman

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Thank you very much. It was very helpful for me.

Saturday, November 15, 2008 2:09 AM by AT

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Three lines, much faster:

       public static string MD5Encrypt(string data)

       {

           MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();

           byte[] result = md5.ComputeHash(Encoding.UTF8.GetBytes(data));

           return Encoding.UTF8.GetString(result);

       }

Saturday, November 15, 2008 7:20 AM by SpikeX

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

it's a contest?   :-D

1 line:

public static string MD5Encrypt(string data)

{

return Encoding.UTF8.GetString((new MD5CryptoServiceProvider()).ComputeHash(Encoding.UTF8.GetBytes(data)));

}

Wednesday, December 10, 2008 4:22 PM by Defkon1

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

who work with radius server encypt user password?

sample don't work :(

string pswrd = "1";

string key = "key";

byte[] keyBytes = Encoding.Default.GetBytes(key);

byte[] authBytes = radius.Authenticator; //byte[16]

byte[] pswrdBytes = new byte[16];

Encoding.Default.GetBytes(pswrd).CopyTo(pswrdBytes, 0);

int b1Len = keyBytes.Length + authBytes.Length;

byte[] b1 = new byte[b1Len];

keyBytes.CopyTo(b1, 0);

authBytes.CopyTo(b1, keyBytes.Length);

byte[] hash = getMd5Hash(b1);

byte[] res = new byte[16];

for (int i = 0; i < 16; i++)

{

  pswrdBytes[i] ^= hash[i];

}

Saturday, December 13, 2008 3:57 PM by sasha001ua

# encriptando o cifrando informacion?

La necesidad de encriptar (ocultar a simple vista) información no es necesidad propia en los sistemas

Friday, December 19, 2008 8:22 AM by SergioTarrillo - RichWeblog

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Hi,

This is very useful...

But I want to how to Decode it..

Hoping a reply..

Tnx...

:)

Monday, December 29, 2008 7:02 PM by DlexP

# Hashing Password &laquo; Team Six Project Blog

Pingback from  Hashing Password « Team Six Project Blog

Friday, January 09, 2009 8:12 AM by Hashing Password « Team Six Project Blog

# re: HOWTO: Decode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

How can decode password which r store by encode form.

Friday, February 20, 2009 2:13 PM by Hitesh Prajapati

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Hi,

this is very useful and simple way..

thanks...

Friday, February 27, 2009 1:05 PM by shardul

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Following post contains code snippet to generate MD5 hash code using C#:

www.etechplanet.com/.../Generate-MD5-Hash-code-from-a-string-using-C.aspx

Monday, May 04, 2009 6:01 PM by Avi

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

omg omg omg people who ask how to decode the hash should &*&%!!!

READ THE COMMENTS BEFORE YOU POST ANYTHING.

You CAN'T decode and you don't need to.

Just encode the entered password at login and compare that to the hash in the database.

Thursday, May 07, 2009 10:53 AM by marcel

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Thats all very nice but how do I decode it?

;)

Thursday, May 28, 2009 6:23 PM by hmmreally

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Thanks.  I need to decode the hash back to a string now, how do I do that?

Just joking :-D  I can't believe people are asking that!

mrpmorris.blogspot.com/.../more-secure-passwords.html

Sunday, May 31, 2009 3:39 PM by Peter Morris

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

lmao .. you guys rock .. lol how to decode it..

Sunday, June 07, 2009 11:21 AM by Thorton

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

how we verify password stored in database with login password? (using hash functions in c#)

Monday, June 15, 2009 11:44 AM by jsj

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Thanks works great.  Glad somebody mentioned salting.

I would say for those who wan't to automate the forgotten password scenario generate a random temporary password for users to use.

It would be nice to find out what others are on about with regards to having databases that store hashed passwords differently.

Somebody requested what the database length would be it is always 32chars I think.

Wednesday, July 01, 2009 1:45 PM by Mark

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

I wouldn't mention the word encoding in this article, it's hashing. Might trigger the large amount of questions by the beginners.

Personally I prefer this:

FormsAuthentication.HashPasswordForStoringInConfigFile(password, System.Web.Configuration.FormsAuthPasswordFormat.MD5.ToString())

Thursday, July 09, 2009 2:45 PM by cj

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Thanks. That was really useful

Tuesday, July 28, 2009 7:54 AM by Sudarsan Srinivasan

# Question

Can you please tell me how to decode a md5 hash?

Thank you

greetings, Carl

Friday, August 07, 2009 1:42 PM by Carl

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

YOU CAN'T! READ THE REST OF THE POSTS!

Tuesday, November 03, 2009 7:04 PM by Joeli

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Thanks a lot!!

It is very much helpfull for me .

Avi

http://www.etechplanet.com

Thursday, December 03, 2009 11:34 PM by Programming Tutorials

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Does any one try to test algorythms post here vs example given in wiki page : en.wikipedia.org/.../MD5

I do, and those algotythms result are all differents.

Reason ? You have to convert the string returns by yours algorythm into a hexadecimal character string.

So i found out solution, comparing with my java-algrythm. Here is my code, witch complain with wiki examples :

// First class : HEX

public class HEX

   {

       private static char[] HexChars = { '0', '1', '2', '3', '4', '5', '6',

'7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };

       public static String ToString(byte[] data)

       {

           StringBuilder sb = new StringBuilder(data.Length * 2);

           foreach (byte b in data)

           {

               sb.Append(HexChars[((b & 0xF0) >> 4)]);

               sb.Append(HexChars[(b & 0x0F)]);

           }

           return sb.ToString();

       }

   }

// Second class : MD5

using System.Text;

using System.Security.Cryptography;

public class MD5

   {

       public static String Encode(String text)

       {

           return HEX.ToString(Encode(Encoding.UTF8.GetBytes(text)));

       }

       public static byte[] Encode(byte[] data)

       {

           return new MD5CryptoServiceProvider().ComputeHash(data);

       }

   }

Friday, January 15, 2010 3:12 PM by clancien

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Oooops, I apologizes, yours algorythms were right !

Mine is only a different one.

Friday, January 15, 2010 3:17 PM by clancien

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

woow your md5 idea is really great , how did you find that name, did you invent c#. wow can you tell me how to hash that md5 so maybe i could decrypt the password and smoke it. i am a programmer i have a web site, can you tell me how i can do it. could you hold my hand while i pee, and maybe make a decrypt password functions for my hash kittys . can you email me your code, can you do it for me, i am a programmer. and i program real programs like "Hello world!", i did it all by myself from the example file. wow

Tuesday, January 26, 2010 8:15 AM by clueless

# HOWTO: Decode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

hi

Thanks for placing code here...

its very helpful n in easy steps..

once again Thanks

Friday, March 26, 2010 2:38 PM by Ashish Saxena

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Thanks so much.  This posting kicks ass.  It helped a lot.

There were some questions on how to make the output look something like this: "aTXuyYqHUUudx0Km2bsZKlH4/WM=".  I had that question too, and I figured it out.

Answer: Convert your Byte Output to a Base64String, instead of a string.  In this example, simply change the last line of your code to:

"return System.Convert.ToBase64String(encodedBytes);"

Your post was super helpful!  Cheers!

Tuesday, April 13, 2010 9:19 PM by Daniel Brown

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

thanks a lot.

Tuesday, May 11, 2010 8:25 AM by zamkinos

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Does the OS have an impact on this at all? i.e. I am running Server 2008 R2 64 bit and it does not match up to a php or javascript created hash.

However I have been looking for help on this issue and I had a reply on another forum that they got the same hash as I was expecting.  What gives?

Thursday, May 20, 2010 4:58 PM by Russ Walters

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

thnx a lot......

it really helped me a lot

and its probbably the simplest code to do d job available online....

thnx 1ce again

Friday, May 20, 2011 8:55 PM by Mayank

# re: HOWTO: decode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

help

Wednesday, May 25, 2011 8:41 AM by yin lin

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

I would like to be able to decode a MD5 hash but it is not really easy to do that. I would have thought you could reverse it but it is specifically designed to make it hard to do that. Some people seem to have cracked it but only to a certain degree.

The reason I need to decode a password is because the place I work for wants to make sure that when someone changes their password that they do not use the same one as before. Not only the same one but they want me to pull out numbers and special characters and then make sure that what is left is not the same as before.

Anyhow that is one reason why someone would want to do that. All that being said there is other ways to encrypt a password with a key and decrypt it the same way using the key.

HD5 is not the way to go for that it seems.  

Thursday, May 26, 2011 10:33 PM by DeathStalker

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

i have md5 code ... So can i get password of facebook

Monday, June 06, 2011 2:45 PM by abhi shingala

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Good call! Thanks!:)

Sunday, June 19, 2011 5:52 PM by Victor

# How to integrate the decryption procedure in the encrypted file? - Programmers Goodies

Pingback from  How to integrate the decryption procedure in the encrypted file?  - Programmers Goodies

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

How to Decode?

Wednesday, March 14, 2012 5:50 AM by Natraj

# re: HOWTO: Encode a password using MD5 in C# (or: howto calculate the MD5 hash for a string)

Great code, its very easy to use and faster.

Thanks

Tuesday, April 17, 2012 6:50 PM by Deepak

Leave a Comment

(required) 
(required) 
(optional)
(required) 
Please add 2 and 6 and type the answer here: