Open in a new tab

Generate a signing key pair, sign and verify a message (a changed message fails), and let two parties compute the same X25519 shared secret from each other's public keys.

Uses @awacloud/fw (Apache-2.0). This example's code is Apache-2.0.

When to use it

Proving who wrote something (releases, messages, tokens) and deriving a key between two parties without sending it: the two Curve25519 primitives most protocols are built on, in pure JavaScript, with public test vectors.

Copy-paste steps

  1. npm install @awacloud/fw
  2. Serve node_modules/@awacloud/fw/src/ at /vendor/fw/ (node serve.js from the examples root does this; any static server works).
  3. Copy index.html and main.js next to each other and open index.html through that server. The ../../_style/examples.css link is optional: copy that file along, or delete the link.
  4. Feed the X25519 shared secret to HKDF (fw/crypto-hash) before using it as a key; never use it raw.

What it shows

  • ed25519.keyPair(seed) (32 random bytes from random.bytes), sign(privateKey, message) and verify(publicKey, signature, message).
  • x25519.scalarMultBase(secret) for a public key, scalarMult(secret, theirPublicKey) for the shared secret, and isLowOrderPoint to refuse a malicious public key.
  • Checked against the RFC 8032 and RFC 7748 known answers.

Code

main.js

javascriptApache-2.074 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { ed25519 } from '@awacloud/fw/crypto/pkc/ed25519.js';
import { x25519 } from '@awacloud/fw/crypto/pkc/x25519.js';
import { random } from '@awacloud/fw/crypto/utils/random.js';
import { hex } from '@awacloud/fw/io/codec/hex.js';

fw.runtime.registerAllDeep([ed25519, x25519, random, hex]);
const ED25519 = fw.runtime.resolve('ed25519');
const X25519 = fw.runtime.resolve('x25519');
const RANDOM = fw.runtime.resolve('random');

const encoder = new TextEncoder();
export const HEX = fw.runtime.resolve('hex');

/**
 * An Ed25519 identity: keep `privateKey` secret, publish `publicKey`.
 * @param {Uint8Array} [seed] 32 random bytes; generated when omitted
 */
export function signingKeys(seed = /** @type {Uint8Array} */ (RANDOM.bytes(32))) {
    const pair = ED25519.keyPair(seed);
    if (!pair) throw new Error('Ed25519 key generation failed');
    return pair;
}

/** @param {Uint8Array} privateKey @param {string} message */
export function sign(privateKey, message) {
    const signature = ED25519.sign(privateKey, encoder.encode(message));
    if (!signature) throw new Error('Ed25519 signing failed');
    return signature;
}

/** @param {Uint8Array} publicKey @param {Uint8Array} signature @param {string} message */
export const verify = (publicKey, signature, message) => ED25519.verify(publicKey, signature, encoder.encode(message));

/**
 * X25519: each party derives a public key from a random scalar; both
 * compute the same secret from the other's public key.
 * @param {Uint8Array} [secret] 32 random bytes; generated when omitted
 */
export function agreementKeys(secret = /** @type {Uint8Array} */ (RANDOM.bytes(32))) {
    const publicKey = X25519.scalarMultBase(secret);
    if (!publicKey) throw new Error('X25519 key generation failed');
    return { secret, publicKey };
}

/** @param {Uint8Array} mySecret @param {Uint8Array} theirPublicKey @returns {Uint8Array} */
export function sharedSecret(mySecret, theirPublicKey) {
    if (X25519.isLowOrderPoint(theirPublicKey)) throw new Error('refusing a low-order public key');
    return /** @type {Uint8Array} */ (X25519.scalarMult(mySecret, theirPublicKey));
}

/** @param {string} id @param {string} value */
const show = (id, value) => { /** @type {HTMLElement} */ (document.getElementById(id)).textContent = value; };
const message = /** @type {HTMLInputElement} */ (document.getElementById('message'));
const signer = signingKeys();

function update() {
    const signature = sign(signer.privateKey, message.value);
    show('public-key', HEX.fromBytes(signer.publicKey));
    show('signature', HEX.fromBytes(signature));
    show('verifies', String(verify(signer.publicKey, signature, message.value)));
    show('verifies-changed', String(verify(signer.publicKey, signature, `${message.value}!`)));
}

const alice = agreementKeys();
const bob = agreementKeys();
show('alice', HEX.fromBytes(alice.publicKey));
show('bob', HEX.fromBytes(bob.publicKey));
const [ab, ba] = [sharedSecret(alice.secret, bob.publicKey), sharedSecret(bob.secret, alice.publicKey)];
show('agree', String(HEX.fromBytes(ab) === HEX.fromBytes(ba)));

message.addEventListener('input', update);
update();

index.html

htmlApache-2.035 lines

<!doctype html>
<!-- SPDX-License-Identifier: Apache-2.0 -->
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>fw · Sign with Ed25519, agree on a secret with X25519</title>
  <link rel="stylesheet" href="../../_style/examples.css">
  <script type="importmap">
  { "imports": {
    "@awacloud/fw": "/vendor/fw/main.js", "@awacloud/fw/": "/vendor/fw/" } }
  </script>
  <script type="module" src="./main.js"></script>
</head>
<body>
  <main>
    <h1>Sign with Ed25519, agree on a secret with X25519</h1>
    <h2>Signature</h2>
    <label for="message">Message</label>
    <input id="message" type="text" value="release 1.4.0" autocomplete="off">
    <dl>
      <dt>Public key</dt><dd><code id="public-key"></code></dd>
      <dt>Signature</dt><dd><code id="signature"></code></dd>
      <dt>Verifies</dt><dd><output id="verifies"></output></dd>
      <dt>Verifies with the message changed</dt><dd><output id="verifies-changed"></output></dd>
    </dl>
    <h2>Key agreement</h2>
    <dl>
      <dt>Alice's public key</dt><dd><code id="alice"></code></dd>
      <dt>Bob's public key</dt><dd><code id="bob"></code></dd>
      <dt>Shared secrets match</dt><dd><output id="agree"></output></dd>
    </dl>
  </main>
</body>
</html>