我刚刚浏览了 DavidHayden 的一篇文章对用户密码进行哈希处理.
真的,我无法得到他想要达到的目标。
这是他的代码:
private static string CreateSalt(int size)
{
//Generate a cryptographic random number.
RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
byte[] buff = new byte[size];
rng.GetBytes(buff);
// Return a Base64 string representation of the random number.
return Convert.ToBase64String(buff);
}
private static string CreatePasswordHash(string pwd, string salt)
{
string saltAndPwd = String.Concat(pwd, salt);
string hashedPwd =
FormsAuthentication.HashPasswordForStoringInConfigFile(
saltAndPwd, "sha1");
return hashedPwd;
}
是否还有其他 C# 方法可以对密码进行哈希处理并向其添加盐?
Update:如果您使用的是 .NET 6 或更高版本,请使用这个解决方案.
实际上,这有点奇怪,因为成员资格提供者将字符串转换放入配置文件中。哈希和盐是二进制 blob,不需要将它们转换为字符串,除非您想将它们放入文本文件中。
在我的书中,开始 ASP.NET 安全,(哦最后,一个给这本书拉皮条的借口)我做了以下事情
static byte[] GenerateSaltedHash(byte[] plainText, byte[] salt)
{
HashAlgorithm algorithm = new SHA256Managed();
byte[] plainTextWithSaltBytes =
new byte[plainText.Length + salt.Length];
for (int i = 0; i < plainText.Length; i++)
{
plainTextWithSaltBytes[i] = plainText[i];
}
for (int i = 0; i < salt.Length; i++)
{
plainTextWithSaltBytes[plainText.Length + i] = salt[i];
}
return algorithm.ComputeHash(plainTextWithSaltBytes);
}
盐的生成正如问题中的例子。您可以使用将文本转换为字节数组Encoding.UTF8.GetBytes(string)
。如果您必须将哈希转换为其字符串表示形式,您可以使用Convert.ToBase64String
and Convert.FromBase64String
将其转换回来。
您应该注意,您不能在字节数组上使用相等运算符,它会检查引用,因此您应该简单地遍历两个数组来检查每个字节,从而
public static bool CompareByteArrays(byte[] array1, byte[] array2)
{
if (array1.Length != array2.Length)
{
return false;
}
for (int i = 0; i < array1.Length; i++)
{
if (array1[i] != array2[i])
{
return false;
}
}
return true;
}
Always每个密码使用新的盐。盐不必保密,可以与哈希本身一起存储。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)