Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MD5 Hash From String

Tags:

.net

md5

Need to get MD5 hash from string.
Get an error MD5 is null.
I am tying to get a 32 character MD5 hash from a string.

using (System.Security.Cryptography.MD5 md5 =         System.Security.Cryptography.MD5.Create("TextToHash")) {     byte[] retVal = md5.Hash;     StringBuilder sb = new StringBuilder();     for (int i = 0; i < retVal.Length; i++)     {         sb.Append(retVal[i].ToString("x2"));     } } 
like image 561
paparazzo Avatar asked Oct 19 '12 17:10

paparazzo


People also ask

How do you generate the MD5 hash of a string?

Call MessageDigest. getInstance("MD5") to get a MD5 instance of MessageDigest you can use. The compute the hash by doing one of: Feed the entire input as a byte[] and calculate the hash in one operation with md.

What is the MD5 hash of a string?

What is an MD5 hash? An MD5 hash is created by taking a string of an any length and encoding it into a 128-bit fingerprint. Encoding the same string using the MD5 algorithm will always result in the same 128-bit hash output.

How is MD5 hash calculated?

Each MD5 hash looks like 32 numbers and letters, but each digit is in hexadecimal and represents four bits. Since a single character represents eight bits (to form a byte), the total bit count of an MD5 hash is 128 bits. Two hexadecimal characters form a byte, so 32 hexadecimal characters equal 16 bytes.

Can we convert MD5 to string?

You cannot reverse the MD5 function, so your only option is to generate a new password and send that to the user (preferably over some secure channel).


1 Answers

Need to get MD5 hash from string.

Then first you need to convert your string to binary data in some form. How you do that will depend on your requirements, but it'll probably be Encoding.GetBytes for some encoding... you need to work out which encoding though. Does this hash need to match the hash created somewhere else, for example?

Get an error MD5 is null.

That's because you're using MD5.Create incorrectly. The argument is an algorithm name. You should almost certainly just use the parameterless overload instead.

I suspect you want something like:

byte[] hash; using (MD5 md5 = MD5.Create()) {     hash = md5.ComputeHash(Encoding.UTF8.GetBytes(text)); } // Now convert the binary hash into text if you must... 
like image 167
Jon Skeet Avatar answered Sep 21 '22 18:09

Jon Skeet