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