带有盐的 MD5 哈希值,用于在 C# 中将密码保存在 DB 中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1300890/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 14:53:21  来源:igfitidea点击:

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

c#.netsecurityhashmd5

提问by abatishchev

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

您能否告诉我一些通过 MD5 散列用户密码的简单算法,但使用来提高可靠性。

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

采纳答案by dtb

You can use the HMACMD5class:

您可以使用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 saltand passwordare 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");

回答by Darin Dimitrov

Here's a sample. It handles MD5, SHA1, SHA256, SHA384, and SHA512.

这是一个示例。它处理 MD5、SHA1、SHA256、SHA384 和 SHA512。

回答by Christian Hayter

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.ComputePasswordDigestfunction with Reflector.

微软已经为你完成了这项工作,但需要一些挖掘。安装Web Service Extensions 3.0,看看Microsoft.Web.Services3.Security.Tokens.UsernameToken.ComputePasswordDigestReflector的功能。

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.

我想在此处发布该函数的源代码,但我不确定这样做是否合法。如果有人能让我放心,那么我会这样做。

回答by Juliet

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。