[ACCEPTED]-MD5 hash with salt for keeping password in DB in C#-md5

Accepted answer
Score: 41

You can use the HMACMD5 class:

var hmacMD5 = new HMACMD5(salt);
var saltedHash = hmacMD5.ComputeHash(password);

Works with SHA-1, SHA256, SHA384, SHA512 3 and RIPEMD160 as well:

var hmacSHA1 = new HMACSHA1(salt);
var saltedHash = hmacSHA1.ComputeHash(password);

Both salt and password are expected 2 as byte arrays.

If you have strings you'll 1 have to convert them to bytes first:

var salt = System.Text.Encoding.UTF8.GetBytes("my salt");
var password = System.Text.Encoding.UTF8.GetBytes("my password");
Score: 4

In addition to the HMACSHA1 class mentioned 4 above, if you just need a quick salted hash, then 3 you're already 95% of the way there:

private static string GenerateHash(string value, string salt)
    byte[] data = System.Text.Encoding.ASCII.GetBytes(salt + value);
    data = System.Security.Cryptography.MD5.Create().ComputeHash(data);
    return Convert.ToBase64String(data);

The 2 real trick is storing the salt in a secure 1 location, such as your machine.config.

Score: 1

Microsoft have done this work for you, but 6 it takes a bit of digging. Install Web Service 5 Extensions 3.0, and have a look at the Microsoft.Web.Services3.Security.Tokens.UsernameToken.ComputePasswordDigest function 4 with Reflector.

I would like to post the 3 source code to that function here, but I'm 2 not sure if it's legal to do that. If anyone 1 can reassure me then I will do so.

More Related questions