Created
February 22, 2019 16:21
-
-
Save 2garryn/479130707d3623dbf4307ae0c88856c6 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Security.Cryptography; | |
using System; | |
using Microsoft.AspNetCore.Cryptography.KeyDerivation; | |
namespace Atrades.WebAPI.Account | |
{ | |
public class Password | |
{ | |
private Password(string hash, string salt) | |
{ | |
Hash = hash; | |
Salt = salt; | |
} | |
public bool Compare(Password password) | |
{ | |
return string.Equals(password.Hash, Hash); | |
} | |
public bool Compare(string password) | |
{ | |
string hashed = hashPassword(password, Salt); | |
return string.Equals(Hash, hashed);; | |
} | |
public string Hash {get; } | |
public string Salt {get; } | |
public static Password FromHashAndSalt(string hash, string salt) | |
{ | |
return new Password(hash, salt); | |
} | |
public static Password CreateHashedPassword(string pwd) | |
{ | |
var salt = generateSalt(); | |
var hashed = hashPassword(pwd, salt); | |
return new Password(hashed, salt); | |
} | |
private static string generateSalt() | |
{ | |
byte[] salt = new byte[128 / 8]; | |
using (var rng = RandomNumberGenerator.Create()) | |
{ | |
rng.GetBytes(salt); | |
} | |
return Convert.ToBase64String(salt); | |
} | |
private static string hashPassword(string password, string salt) | |
{ | |
return Convert.ToBase64String(KeyDerivation.Pbkdf2( | |
password: password, | |
salt: Convert.FromBase64String(salt), | |
prf: KeyDerivationPrf.HMACSHA1, | |
iterationCount: 10000, | |
numBytesRequested: 256 / 8)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment