编辑:正如@MikeT指出的那样,我发布的原始链接和代码已不再被认为是将密码哈希化以存储在数据存储区中的最佳实践。
这篇文章由Scott Brady撰写,介绍了如何使用PasswordHasher,以及如何使用接口开发更强大的哈希实现。
因此,自己应用字节级哈希函数不再是必需的,但如果你想看看它是如何完成的,本文探讨了PasswordHasher<T>
的实现:
探索ASP.NET Core Identity PasswordHasher
该文章中的相关代码片段如下所示:
private static byte[] HashPasswordV2(string password, RandomNumberGenerator rng)
{
const KeyDerivationPrf Pbkdf2Prf = KeyDerivationPrf.HMACSHA1;
const int Pbkdf2IterCount = 1000;
const int Pbkdf2SubkeyLength = 256 / 8;
const int SaltSize = 128 / 8;
byte[] salt = new byte[SaltSize];
rng.GetBytes(salt);
byte[] subkey = KeyDerivation.Pbkdf2(password, salt, Pbkdf2Prf, Pbkdf2IterCount, Pbkdf2SubkeyLength);
var outputBytes = new byte[1 + SaltSize + Pbkdf2SubkeyLength];
outputBytes[0] = 0x00;
Buffer.BlockCopy(salt, 0, outputBytes, 1, SaltSize);
Buffer.BlockCopy(subkey, 0, outputBytes, 1 + SaltSize, Pbkdf2SubkeyLength);
return outputBytes;
}
原始回答:
微软为使用 .Net Core 的任何人提供了一个使用 PBKDF2 的示例代码页面:
在ASP.NET Core中哈希密码
从文章中可以看到:
using System;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
public class Program
{
public static void Main(string[] args)
{
Console.Write("Enter a password: ");
string password = Console.ReadLine();
byte[] salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
Console.WriteLine($"Salt: {Convert.ToBase64String(salt)}");
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 10000,
numBytesRequested: 256 / 8));
Console.WriteLine($"Hashed: {hashed}");
}
}