简体   繁体   English

带有salt的MD5哈希,用于在C#中保存密码

[英]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. 你可以告诉我一些简单的算法,用于通过MD5散列用户密码,但是使用salt来提高可靠性。

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);
}

You can use the HMACMD5 class: 您可以使用HMACMD5类:

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

Works with SHA-1, SHA256, SHA384, SHA512 and RIPEMD160 as well: 适用于SHA-1,SHA256,SHA384,SHA512和RIPEMD160:

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

Both salt and password are expected as byte arrays. saltpassword都是字节数组。

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");

Here's a sample . 这是一个样本 It handles MD5, SHA1, SHA256, SHA384, and SHA512. 它处理MD5,SHA1,SHA256,SHA384和SHA512。

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: 除了上面提到的HMACSHA1类之外,如果你只需要一个快速盐渍哈希,那么你已经95%的方式:

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. 真正的诀窍是将盐存储在安全的位置,例如machine.config。

Microsoft have done this work for you, but it takes a bit of digging. 微软已经为你完成了这项工作,但它需要一些挖掘。 Install Web Service Extensions 3.0, and have a look at the Microsoft.Web.Services3.Security.Tokens.UsernameToken.ComputePasswordDigest function with Reflector. 安装Web Service Extensions 3.0,并查看带有Reflector的Microsoft.Web.Services3.Security.Tokens.UsernameToken.ComputePasswordDigest函数。

I would like to post the source code to that function here, but I'm not sure if it's legal to do that. 我想在这里将源代码发布到该函数,但我不确定这样做是否合法。 If anyone can reassure me then I will do so. 如果有人能安慰我,那么我会这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM