Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MD5 hash with salt for keeping password in DB in C#

Could you please advise me some easy algorithm for hashing user password by MD5, but with salt for increasing reliability.

Now I have this one:

private static string GenerateHash(string value)
{
    var data = System.Text.Encoding.ASCII.GetBytes(value);
    data = System.Security.Cryptography.MD5.Create().ComputeHash(data);
    return Convert.ToBase64String(data);
}
like image 354
abatishchev Avatar asked Aug 19 '09 15:08

abatishchev


2 Answers

You can use the HMACMD5 class:

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

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

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

Both salt and password are expected as byte arrays.

If you have strings you'll 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");
like image 96
dtb Avatar answered Oct 21 '22 13:10

dtb


In addition to the HMACSHA1 class mentioned above, if you just need a quick salted hash, then 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 real trick is storing the salt in a secure location, such as your machine.config.

like image 31
Juliet Avatar answered Oct 21 '22 11:10

Juliet