ASP.NET Core 中的雜湊密碼

本文說明如何呼叫 KeyDerivation.Pbkdf2 方法,以使用 PBKDF2 演算法雜湊密碼。

警告

KeyDerivation.Pbkdf2 API 是低階密碼編譯基本類型,旨在用來將應用程式整合到現有的通訊協定或密碼編譯系統。 KeyDerivation.Pbkdf2 不應用於支援密碼型登入的新應用程式中,而且需要在資料存放區中儲存雜湊密碼。 新的應用程式應該使用 PasswordHasher。 如需 PasswordHasher 的詳細資訊,請參閱探索 ASP.NET Core Identity PasswordHasher

資料保護程式碼基礎映像包含 NuGet 套件 Microsoft.AspNetCore.Cryptography.KeyDerivation,其中包含密碼編譯金鑰衍生函數 (KDF)。 此套件是獨立元件,與資料保護系統的其餘部分沒有相依性。 它可以單獨使用。 來源與資料保護程式碼基礎映像並存,以方便起見。

警告

下列程式碼示範如何使用 KeyDerivation.Pbkdf2 來產生共用秘密金鑰。 它不應該用來雜湊資料存放區中儲存體的密碼。

using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using System.Security.Cryptography;

Console.Write("Enter a password: ");
string? password = Console.ReadLine();

// Generate a 128-bit salt using a sequence of
// cryptographically strong random bytes.
byte[] salt = RandomNumberGenerator.GetBytes(128 / 8); // divide by 8 to convert bits to bytes
Console.WriteLine($"Salt: {Convert.ToBase64String(salt)}");

// derive a 256-bit subkey (use HMACSHA256 with 100,000 iterations)
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
    password: password!,
    salt: salt,
    prf: KeyDerivationPrf.HMACSHA256,
    iterationCount: 100000,
    numBytesRequested: 256 / 8));

Console.WriteLine($"Hashed: {hashed}");

/*
 * SAMPLE OUTPUT
 *
 * Enter a password: Xtw9NMgx
 * Salt: CGYzqeN4plZekNC88Umm1Q==
 * Hashed: Gt9Yc4AiIvmsC1QQbe2RZsCIqvoYlst2xbz0Fs8aHnw=
 */
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();

        // generate a 128-bit salt using a cryptographically strong random sequence of nonzero values
        byte[] salt = new byte[128 / 8];
        using (var rngCsp = new RNGCryptoServiceProvider())
        {
            rngCsp.GetNonZeroBytes(salt);
        }
        Console.WriteLine($"Salt: {Convert.ToBase64String(salt)}");

        // derive a 256-bit subkey (use HMACSHA256 with 100,000 iterations)
        string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
            password: password,
            salt: salt,
            prf: KeyDerivationPrf.HMACSHA256,
            iterationCount: 100000,
            numBytesRequested: 256 / 8));
        Console.WriteLine($"Hashed: {hashed}");
    }
}

/*
 * SAMPLE OUTPUT
 *
 * Enter a password: Xtw9NMgx
 * Salt: CGYzqeN4plZekNC88Umm1Q==
 * Hashed: Gt9Yc4AiIvmsC1QQbe2RZsCIqvoYlst2xbz0Fs8aHnw=
 */
 

如需真實世界使用案例,請參閱 ASP.NET Core Identity 的 PasswordHasher 類型的原始程式碼

注意

.NET 參考來源的文件連結通常會載入存放庫的預設分支,這表示下一版 .NET 的目前開發。 若要選取特定版本的標籤,請使用 [切換分支或標籤] 下拉式清單。 如需詳細資訊,請參閱如何選取 ASP.NET Core 原始程式碼 (dotnet/AspNetCore.Docs #26205) 的版本標籤