| | | 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 DeriveKeyMemLimit = 1 << 16; // 64 MiB |
| | | 10 | | private const ulong DeriveKeyOpsLimit = 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.PrivkeyLen) |
| | 0 | 22 | | throw new ArgumentException($"Key must be {CryptoConstants.PrivkeyLen} bytes long", nameof(key)); |
| | | 23 | | |
| | 0 | 24 | | var ret = _cryptoProvider |
| | 0 | 25 | | .DeriveKeyFromPasswordUsingArgon2I(key, password, salt, DeriveKeyOpsLimit, DeriveKeyMemLimit); |
| | | 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 | | } |