| 1 | using System;
|
|---|
| 2 | using System.Collections.Generic;
|
|---|
| 3 | using System.Linq;
|
|---|
| 4 | using System.Security.Cryptography;
|
|---|
| 5 | using System.Text;
|
|---|
| 6 | using System.Threading.Tasks;
|
|---|
| 7 |
|
|---|
| 8 | namespace ChapterX.Domain.Shared
|
|---|
| 9 | {
|
|---|
| 10 | public class PasswordHasher
|
|---|
| 11 | {
|
|---|
| 12 | public static string HashPassword(string password)
|
|---|
| 13 | {
|
|---|
| 14 | byte[] salt;
|
|---|
| 15 | new RNGCryptoServiceProvider().GetBytes(salt = new byte[16]);
|
|---|
| 16 |
|
|---|
| 17 | var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000, HashAlgorithmName.SHA256);
|
|---|
| 18 | byte[] hash = pbkdf2.GetBytes(20);
|
|---|
| 19 |
|
|---|
| 20 | byte[] hashBytes = new byte[36];
|
|---|
| 21 | Array.Copy(salt, 0, hashBytes, 0, 16);
|
|---|
| 22 | Array.Copy(hash, 0, hashBytes, 16, 20);
|
|---|
| 23 |
|
|---|
| 24 | return Convert.ToBase64String(hashBytes);
|
|---|
| 25 | }
|
|---|
| 26 |
|
|---|
| 27 | public static bool VerifyPassword(string password, string storedHash)
|
|---|
| 28 | {
|
|---|
| 29 | byte[] hashBytes = Convert.FromBase64String(storedHash);
|
|---|
| 30 | byte[] salt = new byte[16];
|
|---|
| 31 | Array.Copy(hashBytes, 0, salt, 0, 16);
|
|---|
| 32 |
|
|---|
| 33 | var pbkdf2 = new Rfc2898DeriveBytes(password, salt, 10000, HashAlgorithmName.SHA256);
|
|---|
| 34 | byte[] hash = pbkdf2.GetBytes(20);
|
|---|
| 35 |
|
|---|
| 36 | for (int i = 0; i < 20; i++)
|
|---|
| 37 | {
|
|---|
| 38 | if (hashBytes[i + 16] != hash[i])
|
|---|
| 39 | {
|
|---|
| 40 | return false;
|
|---|
| 41 | }
|
|---|
| 42 | }
|
|---|
| 43 | return true;
|
|---|
| 44 | }
|
|---|
| 45 | }
|
|---|
| 46 | }
|
|---|