| | 1 | | namespace NLightning.Infrastructure.Crypto.Primitives; |
| | 2 | |
|
| | 3 | | using Factories; |
| | 4 | | using Interfaces; |
| | 5 | |
|
| | 6 | | public sealed unsafe class SecureMemory : IDisposable |
| | 7 | | { |
| | 8 | | private readonly ICryptoProvider _cryptoProvider; |
| | 9 | | private readonly void* _pointer; |
| | 10 | |
|
| 18848 | 11 | | public int Length { get; } |
| | 12 | |
|
| 452 | 13 | | public SecureMemory(int size) |
| | 14 | | { |
| 452 | 15 | | _cryptoProvider = CryptoFactory.GetCryptoProvider(); |
| 452 | 16 | | Length = size; |
| 452 | 17 | | _pointer = _cryptoProvider.MemoryAlloc((ulong)size).ToPointer(); |
| | 18 | |
|
| 452 | 19 | | _cryptoProvider.MemoryLock(new IntPtr(_pointer), (ulong)Length); |
| 452 | 20 | | } |
| | 21 | |
|
| | 22 | | #region Implicit Conversions |
| 900 | 23 | | public static implicit operator Span<byte>(SecureMemory secureMemory) => new(secureMemory._pointer, secureMemory.Len |
| 16780 | 24 | | public static implicit operator ReadOnlySpan<byte>(SecureMemory secureMemory) => new(secureMemory._pointer, secureMe |
| | 25 | | #endregion |
| | 26 | |
|
| | 27 | | public override bool Equals(object? obj) |
| | 28 | | { |
| 0 | 29 | | if (obj is not SecureMemory castObj) return false; |
| | 30 | |
|
| 0 | 31 | | return castObj.Length == Length && castObj._pointer == _pointer; |
| | 32 | | } |
| | 33 | | public override int GetHashCode() |
| | 34 | | { |
| 0 | 35 | | return Length ^ (int)new IntPtr(_pointer); |
| | 36 | | } |
| | 37 | |
|
| | 38 | | #region Dispose Pattern |
| | 39 | | private void ReleaseUnmanagedResources() |
| | 40 | | { |
| 356 | 41 | | var pointerInt = new IntPtr(_pointer); |
| 356 | 42 | | _cryptoProvider.MemoryZero(pointerInt, (ulong)Length); |
| 356 | 43 | | _cryptoProvider.MemoryUnlock(pointerInt, (ulong)Length); |
| 356 | 44 | | _cryptoProvider.MemoryFree(pointerInt); |
| 356 | 45 | | } |
| | 46 | |
|
| | 47 | | private void Dispose(bool disposing) |
| | 48 | | { |
| 356 | 49 | | ReleaseUnmanagedResources(); |
| 356 | 50 | | if (disposing) |
| | 51 | | { |
| 352 | 52 | | _cryptoProvider.Dispose(); |
| | 53 | | } |
| 356 | 54 | | } |
| | 55 | |
|
| | 56 | | public void Dispose() |
| | 57 | | { |
| 352 | 58 | | Dispose(true); |
| 352 | 59 | | GC.SuppressFinalize(this); |
| 352 | 60 | | } |
| | 61 | |
|
| | 62 | | ~SecureMemory() |
| | 63 | | { |
| 4 | 64 | | Dispose(false); |
| 8 | 65 | | } |
| | 66 | | #endregion |
| | 67 | | } |