| | 1 | | namespace NLightning.Infrastructure.Crypto.Hashes; |
| | 2 | |
|
| | 3 | | using Domain.Crypto.Constants; |
| | 4 | | using Factories; |
| | 5 | | using Interfaces; |
| | 6 | |
|
| | 7 | | public sealed class Argon2Id : IDisposable |
| | 8 | | { |
| | 9 | | private const ulong DERIVE_KEY_MEM_LIMIT = 1 << 16; // 64 MiB |
| | 10 | | private const ulong DERIVE_KEY_OPS_LIMIT = 3; |
| | 11 | |
|
| | 12 | | private readonly ICryptoProvider _cryptoProvider; |
| | 13 | |
|
| 0 | 14 | | public Argon2Id() |
| | 15 | | { |
| 0 | 16 | | _cryptoProvider = CryptoFactory.GetCryptoProvider(); |
| 0 | 17 | | } |
| | 18 | |
|
| | 19 | | public void DeriveKeyFromPasswordAndSalt(string password, ReadOnlySpan<byte> salt, Span<byte> key) |
| | 20 | | { |
| 0 | 21 | | if (key.Length != CryptoConstants.PRIVKEY_LEN) |
| 0 | 22 | | throw new ArgumentException($"Key must be {CryptoConstants.PRIVKEY_LEN} bytes long", nameof(key)); |
| | 23 | |
|
| 0 | 24 | | var ret = _cryptoProvider |
| 0 | 25 | | .DeriveKeyFromPasswordUsingArgon2I(key, password, salt, DERIVE_KEY_OPS_LIMIT, DERIVE_KEY_MEM_LIMIT); |
| | 26 | |
|
| 0 | 27 | | if (ret != 0) |
| 0 | 28 | | throw new Exception("Argon2ID key derivation failed"); |
| 0 | 29 | | } |
| | 30 | |
|
| | 31 | | public void Dispose() |
| | 32 | | { |
| 0 | 33 | | _cryptoProvider.Dispose(); |
| 0 | 34 | | } |
| | 35 | | } |