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