Reputation: 1021
I am trying to generate a MD5 hash in C#, but I cannot retrieve the string that I am expecting.
Using an MD5 Hash Generator, the string Hello World!
returns a hash of ed076287532e86365e841e92bfc50d8c
.
Using this code:
string hash;
using (MD5 md5 = MD5.Create())
{
hash = Encoding.UTF8.GetString(md5.ComputeHash(Encoding.Default.GetBytes("Hello World!")));
}
returns �\ab�S.�6^����\r�
which is problematic.
I suspect this is an issue to do with my encoding of the string. How can I retrieve the expected value?
Edit: As you can see, I do not have much (any) experience with using the MD5 hash - the aim of this question is to educate myself, rather than use the code to secure information.
Upvotes: 2
Views: 2690
Reputation: 2806
The ComputeHash()
returns a byte array. You have to convert that byte array into a string in hex notation.
public string CalculateMD5Hash(string input)
{
// step 1, calculate MD5 hash from input
using(MD5 md5 = System.Security.Cryptography.MD5.Create())
{
byte[] inputBytes = System.Text.Encoding.UTF8.GetBytes(input);
byte[] hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
StringBuilder sb = new StringBuilder(2 * hash.Length);
for (int i = 0; i < hash.Length; i++)
{
// use "x2" for all lower case.
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
}
Upvotes: 2
Reputation: 186728
If you want string
represenatation of the hash, you have to encode its byte[]
representation:
using System.Security.Cryptography;
...
public string MD5Hash(String input) {
using (MD5 md5 = MD5.Create()) {
return String.Concat(md5
.ComputeHash(Encoding.UTF8.GetBytes(input))
.Select(item => item.ToString("x2")));
}
}
...
// hash == "ed076287532e86365e841e92bfc50d8c"
String hash = MD5Hash("Hello World!");
Upvotes: 1
Reputation: 49719
ComputeHash()
returns a byte array. Use a method to convert it to your desired hex format, e.g. BitConverter.ToString
and some string manipulatino to get rid of the hyphens:
string hash;
using (MD5 md5 = MD5.Create())
{
hash = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes("Hello World!")));
}
hash = hash.Replace("-", "");
Output: ED076287532E86365E841E92BFC50D8C
Upvotes: 2