-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathIStringHasher.cs
34 lines (27 loc) · 1.05 KB
/
IStringHasher.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
using System.Diagnostics.CodeAnalysis;
using System.Security.Cryptography;
using System.Text;
namespace Digdir.Domain.Dialogporten.Application.Common;
internal interface IStringHasher
{
[return: NotNullIfNotNull(nameof(personIdentifier))]
string? Hash(string? personIdentifier);
}
internal class PersistantRandomSaltStringHasher : IStringHasher
{
private const int SaltSize = 16;
private readonly Lazy<byte[]> _lazySalt = new(() => RandomNumberGenerator.GetBytes(SaltSize));
public string? Hash(string? personIdentifier)
{
if (string.IsNullOrWhiteSpace(personIdentifier))
{
return null;
}
var identifierBytes = Encoding.UTF8.GetBytes(personIdentifier);
Span<byte> buffer = stackalloc byte[identifierBytes.Length + _lazySalt.Value.Length];
identifierBytes.CopyTo(buffer);
_lazySalt.Value.CopyTo(buffer[identifierBytes.Length..]);
var hashBytes = SHA256.HashData(buffer);
return BitConverter.ToString(hashBytes, 0, 5).Replace("-", "").ToLowerInvariant();
}
}