How to get a hashed string

M

Marc Gravell

I'm assuming by "hashed" you mean for storage purposes - i.e. not
simply .GetHashCode(); anyway, picking the simplest option (MD5),
something like:

using System;
using System.Security.Cryptography;
using System.Text;
using System.Xml;
static class Program
{
static void Main()
{
string text = "abcdefghijklmnopqrstuvwxyz";
MD5CryptoServiceProvider crypt = new
MD5CryptoServiceProvider();
byte[] inputBuffer = Encoding.UTF8.GetBytes(text);
byte[] hashBuffer = crypt.ComputeHash(inputBuffer);

// result as base-64 (easy & shorter result)
string hashBase64 = Convert.ToBase64String(hashBuffer);

// result as hex-string (more common)
StringBuilder sb = new StringBuilder(hashBuffer.Length * 2);
foreach (byte b in hashBuffer)
{
sb.Append(b.ToString("x2"));
}
string hashHex = sb.ToString();
}
}

Note, however, that MD5 is not very sucure; there are databases
dedicated to known MD5 values, so it shouldn't be used to hash
passwords or credit-card numbers, etc. For secure applications, you'd
want to look at a keyed algorithm - such as any of the HMACSHA[n]
implementations:

http://msdn2.microsoft.com/en-us/library/system.security.cryptography.hmacsha1.aspx

Marc
 
A

Arne Vajhøj

ad said:
I want to hash a givien string to a hashed string.
How can I do witth c#?

private static readonly Encoding utf8 = new UTF8Encoding();
private static readonly MD5 md5 = new MD5CryptoServiceProvider();
private static string MD5Calc(string s)
{
byte[] binres = md5.ComputeHash(utf8.GetBytes(s));
StringBuilder res = new StringBuilder("");
for(int i = 0; i < binres.Length; i++)
{
res.Append(String.Format("{0:x2}", binres));
}
return res.ToString();
}

eller

private static readonly Encoding utf8 = new UTF8Encoding();
private static readonly MD5 md5 = new MD5CryptoServiceProvider();
private static string MD5Calc(string s)
{
byte[] binres = md5.ComputeHash(utf8.GetBytes(s));
return Convert.ToBase64String(binres);
}

depending on whether you want Hex or Base64 encoding.

Note that MD5 is not particular secure any more and for
some purposes SHA-256 should be used instead.

Arne
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top