Problem
How to use hash data (e.g. passwords) in ASP.NET Core.
Solution
The new Data Protection API in .NET Core includes functionality to create hashes using PBKDF2algorithm. ASP.NET Core uses this behind the scenes functionality in PasswordHasher class, which is used in ASP.NET Core Identity.
Create a class library and add the following NuGet package -
Microsoft.AspNetCore.Cryptography.KeyDerivation
Add a class to encapsulate the hashing logic.
- public class Hash
- {
- public static string Create(string value, string salt)
- {
- var valueBytes = KeyDerivation.Pbkdf2(
- password: value,
- salt: Encoding.UTF8.GetBytes(salt),
- prf: KeyDerivationPrf.HMACSHA512,
- iterationCount: 10000,
- numBytesRequested: 256 / 8);
- return Convert.ToBase64String(valueBytes);
- }
- public static bool Validate(string value, string salt, string hash)
- => Create(value, salt) == hash;
- }
Add a class to encapsulate the logic for creating a random salt.
- public class Salt
- {
- public static string Create()
- {
- byte[] randomBytes = new byte[128 / 8];
- using (var generator = RandomNumberGenerator.Create())
- {
- generator.GetBytes(randomBytes);
- return Convert.ToBase64String(randomBytes);
- }
- }
- }
VISHNU SURENDRANPosted Sep 4, 2020, 1:28 PM
The salt need to store into the database for login verification?
Tridip BhattacharjeePosted Mar 14, 2018, 4:28 AM
If we use random salt then it will hard to match two hash. suppose first time random salt will be used to generate hash and second time it will generate different hash....am i right?