Senhas de hash no ASP.NET CoreHash passwords in ASP.NET Core
A base de código de proteção de dados inclui um pacote Microsoft. AspNetCore. Cryptography. Keyderivation que contém funções de derivação de chave de criptografia.The data protection code base includes a package Microsoft.AspNetCore.Cryptography.KeyDerivation which contains cryptographic key derivation functions. Este pacote é um componente autônomo e não tem dependências no restante do sistema de proteção de dados.This package is a standalone component and has no dependencies on the rest of the data protection system. Ele pode ser usado completamente de forma independente.It can be used completely independently. A origem existe junto com a base de código de proteção de dados como uma conveniência.The source exists alongside the data protection code base as a convenience.
Atualmente, o pacote oferece um método KeyDerivation.Pbkdf2
que permite o hash de uma senha usando o algoritmo PBKDF2.The package currently offers a method KeyDerivation.Pbkdf2
which allows hashing a password using the PBKDF2 algorithm. Essa API é muito semelhante ao tipo de Rfc2898DeriveBytesexistente da .NET Framework, mas há três distinções importantes:This API is very similar to the .NET Framework's existing Rfc2898DeriveBytes type, but there are three important distinctions:
O
KeyDerivation.Pbkdf2
método dá suporte ao consumo de vários PRFs (atualmenteHMACSHA1
,HMACSHA256
eHMACSHA512
), enquanto oRfc2898DeriveBytes
tipo só dá suporte aHMACSHA1
.TheKeyDerivation.Pbkdf2
method supports consuming multiple PRFs (currentlyHMACSHA1
,HMACSHA256
, andHMACSHA512
), whereas theRfc2898DeriveBytes
type only supportsHMACSHA1
.O
KeyDerivation.Pbkdf2
método detecta o sistema operacional atual e tenta escolher a implementação mais otimizada da rotina, fornecendo um desempenho muito melhor em determinados casos.TheKeyDerivation.Pbkdf2
method detects the current operating system and attempts to choose the most optimized implementation of the routine, providing much better performance in certain cases. (No Windows 8, ele oferece cerca de 10 vezes a taxa de transferência deRfc2898DeriveBytes
.)(On Windows 8, it offers around 10x the throughput ofRfc2898DeriveBytes
.)O
KeyDerivation.Pbkdf2
método requer que o chamador especifique todos os parâmetros (Salt, PRF e contagem de iteração).TheKeyDerivation.Pbkdf2
method requires the caller to specify all parameters (salt, PRF, and iteration count). ORfc2898DeriveBytes
tipo fornece valores padrão para eles.TheRfc2898DeriveBytes
type provides default values for these.
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 secure PRNG
byte[] salt = new byte[128 / 8];
using (var rng = RandomNumberGenerator.Create())
{
rng.GetBytes(salt);
}
Console.WriteLine($"Salt: {Convert.ToBase64String(salt)}");
// derive a 256-bit subkey (use HMACSHA1 with 10,000 iterations)
string hashed = Convert.ToBase64String(KeyDerivation.Pbkdf2(
password: password,
salt: salt,
prf: KeyDerivationPrf.HMACSHA1,
iterationCount: 10000,
numBytesRequested: 256 / 8));
Console.WriteLine($"Hashed: {hashed}");
}
}
/*
* SAMPLE OUTPUT
*
* Enter a password: Xtw9NMgx
* Salt: NZsP6NnmfBuYeJrrAKNuVQ==
* Hashed: /OOoOer10+tGwTRDTrQSoeCxVTFr6dtYly7d0cPxIak=
*/
Consulte o código-fonte para o ASP.NET Core Identity PasswordHasher
tipo de um caso de uso do mundo real.See the source code for ASP.NET Core Identity's PasswordHasher
type for a real-world use case.