public byte[] Secp256K1Encrypt(Span <byte> recipientPublicKey, ReadOnlySpan <byte> plaintext) { var ephemeralPrivateKey = GeneratePrivateKey(); var ephemeralPublicKey = new byte[64]; var recipientPublicKeyParsed = new byte[64]; if (!Secp256K1.PublicKeyCreate(ephemeralPublicKey, ephemeralPrivateKey)) { throw new Exception("Corrupted private key"); } if (!Secp256K1.PublicKeyParse(recipientPublicKeyParsed, recipientPublicKey)) { throw new Exception("Corrupted recipient public key"); } var sessionKey = new byte[32]; if (!Secp256K1.Ecdh(sessionKey, recipientPublicKeyParsed, ephemeralPrivateKey)) { throw new Exception("Ecdh failed"); } var ephemeralPublicKeySerialized = new byte[33]; if (!Secp256K1.PublicKeySerialize(ephemeralPublicKeySerialized, ephemeralPublicKey, Flags.SECP256K1_EC_COMPRESSED)) { throw new Exception("Corrupted public key"); } return(ephemeralPublicKeySerialized.Concat(AesGcmEncrypt(sessionKey, plaintext)).ToArray()); }
public static byte[] Ecdh(byte[] privateKey, byte[] publicKey) { try { Lock.AcquireWriterLock(Timeout.Infinite); var usablePublicKey = new byte[Secp256k1.SERIALIZED_UNCOMPRESSED_PUBKEY_LENGTH]; Secp256K1.PublicKeyParse(usablePublicKey, publicKey); var ecdhKey = new byte[Secp256k1.SERIALIZED_COMPRESSED_PUBKEY_LENGTH]; Secp256K1.Ecdh(ecdhKey, usablePublicKey, privateKey); return(ecdhKey); } finally { Lock.ReleaseWriterLock(); } }
public static byte[] Ecdh(byte[] privateKey, byte[] publicKey) { try { Lock.AcquireWriterLock(Timeout.Infinite); var usablePublicKey = new byte[Secp256k1.SERIALIZED_UNCOMPRESSED_PUBKEY_LENGTH]; if (!Secp256K1.PublicKeyParse(usablePublicKey, publicKey)) { throw new PublicKeyOperationException("Parse public key failed."); } var ecdhKey = new byte[Secp256k1.SERIALIZED_COMPRESSED_PUBKEY_LENGTH]; if (!Secp256K1.Ecdh(ecdhKey, usablePublicKey, privateKey)) { throw new EcdhOperationException("Compute EC Diffie- secret failed."); } return(ecdhKey); } finally { Lock.ReleaseWriterLock(); } }