From 2fe9b8387679ad2ca93eb3b56b1f6ccf1c1c6373 Mon Sep 17 00:00:00 2001 From: Sam Hadow Date: Wed, 19 Feb 2025 16:01:20 +0100 Subject: [PATCH] ecdh test --- package.json | 1 + src/public/ecdh.js | 15 +++++++++++++++ tests/ecdh.test.js | 16 ++++++++++++++++ 3 files changed, 32 insertions(+) create mode 100644 tests/ecdh.test.js diff --git a/package.json b/package.json index 59abc63..4cfd64d 100644 --- a/package.json +++ b/package.json @@ -9,6 +9,7 @@ "author": "Sam Hadow", "license": "BSD-3-Clause-Attribution", "dependencies": { + "@noble/curves": "^1.8.1", "bootstrap": "^5.3.3", "connect-sqlite3": "^0.9.15", "cookie-parser": "^1.4.7", diff --git a/src/public/ecdh.js b/src/public/ecdh.js index e69de29..ab0d9b7 100644 --- a/src/public/ecdh.js +++ b/src/public/ecdh.js @@ -0,0 +1,15 @@ +// X25519 aka ECDH on Curve25519 from [RFC7748](https://www.rfc-editor.org/rfc/rfc7748) +import { x25519 } from '@noble/curves/ed25519'; + +export function genKeys() { + const priv = x25519.utils.randomPrivateKey(); + const pub = x25519.getPublicKey(priv); + return { + privkey: priv, + pubkey: pub + }; +} + +export function sharedKey(priv, pub) { + return x25519.getSharedSecret(priv, pub); +} diff --git a/tests/ecdh.test.js b/tests/ecdh.test.js new file mode 100644 index 0000000..50eacdb --- /dev/null +++ b/tests/ecdh.test.js @@ -0,0 +1,16 @@ +import { genKeys, sharedKey } from '../src/public/ecdh.js'; +import { arrayToHex } from '../src/stringutils.js'; + +describe('ecdh.js functions', () => { + + it('key exchange test', () => { + const keysA= genKeys(); + const keysB = genKeys(); + const sharedA = sharedKey(keysA.privkey, keysB.pubkey); + const sharedB = sharedKey(keysB.privkey, keysA.pubkey); + const sharedAhex = arrayToHex(sharedA); + const sharedBhex = arrayToHex(sharedB); + expect(sharedAhex === sharedBhex); + }); + +});