| | 1 | | using System.Diagnostics; |
| | 2 | |
|
| | 3 | | namespace NLightning.Infrastructure.Crypto.Hashes; |
| | 4 | |
|
| | 5 | | using Domain.Crypto.Constants; |
| | 6 | | using Factories; |
| | 7 | | using Interfaces; |
| | 8 | |
|
| | 9 | | /// <summary> |
| | 10 | | /// SHA-256 from <see href="https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf">FIPS 180-4</see>. |
| | 11 | | /// </summary> |
| | 12 | | public sealed class Sha256 : IDisposable |
| | 13 | | { |
| | 14 | | private readonly ICryptoProvider _cryptoProvider; |
| | 15 | | private readonly IntPtr _state; |
| | 16 | |
|
| 6328 | 17 | | public Sha256() |
| | 18 | | { |
| 6328 | 19 | | _cryptoProvider = CryptoFactory.GetCryptoProvider(); |
| 6328 | 20 | | _state = _cryptoProvider.MemoryAlloc(CryptoConstants.LIBSODIUM_SHA256_STATE_LEN); |
| 6328 | 21 | | Reset(); |
| 6328 | 22 | | } |
| | 23 | |
|
| | 24 | | /// <summary> |
| | 25 | | /// Appends the specified data to the data already processed in the hash. |
| | 26 | | /// </summary> |
| | 27 | | public void AppendData(ReadOnlySpan<byte> data) |
| | 28 | | { |
| 84588 | 29 | | if (!data.IsEmpty) |
| | 30 | | { |
| 84092 | 31 | | _cryptoProvider.Sha256Update(_state, data); |
| | 32 | | } |
| 84588 | 33 | | } |
| | 34 | |
|
| | 35 | | /// <summary> |
| | 36 | | /// Retrieves the hash for the accumulated data into the hash parameter, |
| | 37 | | /// and resets the object to its initial state. |
| | 38 | | /// </summary> |
| | 39 | | public void GetHashAndReset(Span<byte> hash) |
| | 40 | | { |
| | 41 | | Debug.Assert(hash.Length == CryptoConstants.SHA256_HASH_LEN); |
| | 42 | |
|
| 81672 | 43 | | _cryptoProvider.Sha256Final(_state, hash); |
| | 44 | |
|
| 81672 | 45 | | Reset(); |
| 81672 | 46 | | } |
| | 47 | |
|
| | 48 | | private void Reset() |
| | 49 | | { |
| 88000 | 50 | | _cryptoProvider.Sha256Init(_state); |
| 88000 | 51 | | } |
| | 52 | |
|
| | 53 | | #region Dispose Pattern |
| | 54 | | private void ReleaseUnmanagedResources() |
| | 55 | | { |
| 6280 | 56 | | _cryptoProvider.MemoryZero(_state, CryptoConstants.SHA256_HASH_LEN); |
| 6280 | 57 | | _cryptoProvider.MemoryFree(_state); |
| 6280 | 58 | | } |
| | 59 | |
|
| | 60 | | private void Dispose(bool disposing) |
| | 61 | | { |
| 6280 | 62 | | ReleaseUnmanagedResources(); |
| 6280 | 63 | | if (disposing) |
| | 64 | | { |
| 6280 | 65 | | _cryptoProvider.Dispose(); |
| | 66 | | } |
| 6280 | 67 | | } |
| | 68 | |
|
| | 69 | | public void Dispose() |
| | 70 | | { |
| 6280 | 71 | | Dispose(true); |
| 6280 | 72 | | GC.SuppressFinalize(this); |
| 6280 | 73 | | } |
| | 74 | |
|
| | 75 | | ~Sha256() |
| | 76 | | { |
| 0 | 77 | | Dispose(false); |
| 0 | 78 | | } |
| | 79 | | #endregion |
| | 80 | | } |