| | 1 | | using NBitcoin; |
| | 2 | |
|
| | 3 | | namespace NLightning.Infrastructure.Bitcoin.Crypto.Functions; |
| | 4 | |
|
| | 5 | | using Domain.Crypto.Constants; |
| | 6 | | using Domain.Crypto.ValueObjects; |
| | 7 | | using Infrastructure.Crypto.Hashes; |
| | 8 | | using Infrastructure.Crypto.Interfaces; |
| | 9 | |
|
| | 10 | | /// <summary> |
| | 11 | | /// The SecP256k1 DH function implementation. |
| | 12 | | /// </summary> |
| | 13 | | /// <see href="https://github.com/lightning/bolts/blob/master/08-transport.md#handshake-state"/> |
| | 14 | | internal sealed class Ecdh : IEcdh |
| | 15 | | { |
| | 16 | | /// <inheritdoc/> |
| | 17 | | /// <param name="k">Private Key</param> |
| | 18 | | /// <param name="rk">Remote Static PubKey</param> |
| | 19 | | /// <param name="sharedKey"></param> |
| | 20 | | public void SecP256K1Dh(PrivKey k, ReadOnlySpan<byte> rk, Span<byte> sharedKey) |
| | 21 | | { |
| 200 | 22 | | PubKey pubKey = new(rk); |
| 188 | 23 | | using Key key = new(k); |
| | 24 | |
|
| | 25 | | // ECDH operation |
| 188 | 26 | | var sharedPubKey = pubKey.GetSharedPubkey(key); |
| | 27 | |
|
| | 28 | | // Shared public key's Compressed format's SHA256 |
| 188 | 29 | | using var sha256 = new Sha256(); |
| 188 | 30 | | sha256.AppendData(sharedPubKey.Compress().ToBytes()); |
| 188 | 31 | | sha256.GetHashAndReset(sharedKey); |
| 376 | 32 | | } |
| | 33 | |
|
| | 34 | | /// <inheritdoc/> |
| | 35 | | public CryptoKeyPair GenerateKeyPair() |
| | 36 | | { |
| 0 | 37 | | using var key = new Key(); |
| 0 | 38 | | return new CryptoKeyPair(key.ToBytes(), key.PubKey.ToBytes()); |
| 0 | 39 | | } |
| | 40 | |
|
| | 41 | | /// <inheritdoc/> |
| | 42 | | public CryptoKeyPair GenerateKeyPair(ReadOnlySpan<byte> privateKey) |
| | 43 | | { |
| 188 | 44 | | if (privateKey.Length != CryptoConstants.PrivkeyLen) |
| | 45 | | { |
| 4 | 46 | | throw new ArgumentException("Invalid private key length"); |
| | 47 | | } |
| | 48 | |
|
| 184 | 49 | | using var key = new Key(privateKey.ToArray()); |
| 184 | 50 | | return new CryptoKeyPair(key.ToBytes(), key.PubKey.ToBytes()); |
| 184 | 51 | | } |
| | 52 | | } |