| | | 1 | | using System.Security.Cryptography; |
| | | 2 | | using System.Text; |
| | | 3 | | using Elsa.Identity.Contracts; |
| | | 4 | | using Elsa.Identity.Models; |
| | | 5 | | |
| | | 6 | | namespace Elsa.Identity.Services; |
| | | 7 | | |
| | | 8 | | /// <inheritdoc /> |
| | | 9 | | public class DefaultSecretHasher : ISecretHasher |
| | | 10 | | { |
| | | 11 | | /// <inheritdoc /> |
| | | 12 | | public HashedSecret HashSecret(string secret) |
| | | 13 | | { |
| | 0 | 14 | | var saltBytes = GenerateSalt(); |
| | 0 | 15 | | return HashSecret(secret, saltBytes); |
| | | 16 | | } |
| | | 17 | | |
| | | 18 | | /// <inheritdoc /> |
| | | 19 | | public HashedSecret HashSecret(string secret, byte[] salt) |
| | | 20 | | { |
| | 0 | 21 | | var passwordBytes = Encoding.UTF8.GetBytes(secret); |
| | 0 | 22 | | var hashedPassword = HashSecret(passwordBytes, salt); |
| | 0 | 23 | | return HashedSecret.FromBytes(hashedPassword, salt); |
| | | 24 | | } |
| | | 25 | | |
| | | 26 | | /// <inheritdoc /> |
| | | 27 | | public bool VerifySecret(string clearTextSecret, string secret, string salt) |
| | | 28 | | { |
| | 0 | 29 | | var hashedPassword = HashedSecret.FromString(secret, salt); |
| | 0 | 30 | | return VerifySecret(clearTextSecret, hashedPassword); |
| | | 31 | | } |
| | | 32 | | |
| | | 33 | | /// <inheritdoc /> |
| | | 34 | | public bool VerifySecret(string clearTextSecret, HashedSecret hashedSecret) |
| | | 35 | | { |
| | 0 | 36 | | var password = hashedSecret.Secret; |
| | 0 | 37 | | var salt = hashedSecret.Salt; |
| | 0 | 38 | | var providedHashedPassword = HashSecret(clearTextSecret, salt); |
| | 0 | 39 | | return providedHashedPassword.Secret.SequenceEqual(password); |
| | | 40 | | } |
| | | 41 | | |
| | | 42 | | /// <inheritdoc /> |
| | | 43 | | public byte[] HashSecret(byte[] secret, byte[] salt) |
| | | 44 | | { |
| | 0 | 45 | | using var sha256 = SHA256.Create(); |
| | 0 | 46 | | var passwordAndSalt = secret.Concat(salt).ToArray(); |
| | 0 | 47 | | return sha256.ComputeHash(passwordAndSalt); |
| | 0 | 48 | | } |
| | | 49 | | |
| | | 50 | | /// <inheritdoc /> |
| | 0 | 51 | | public byte[] GenerateSalt(int saltSize = 32) => RandomNumberGenerator.GetBytes(saltSize); |
| | | 52 | | } |