Open in a new tab

Generate an Ed25519 key pair with the browser's WebCrypto, export it in the three standard formats, import it back, and rebuild the same key in pure JavaScript from its PKCS#8 bytes.

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

When to use it

When a key has to cross a boundary: a public key published as a JWK for a web API or as SPKI PEM for a server or a command-line tool, or a private key moved from WebCrypto to code that has no WebCrypto (a worker of another runtime, an older browser) through the pure-JS ed25519 module.

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). WebCrypto needs https or localhost.
  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. Never show or send a private key in a real page: this one prints the PKCS#8 text only to make the format visible.

What it shows

  • webcryptoEd25519.generateKey(true): an extractable key pair, so exportKey('pkcs8' | 'spki' | 'jwk', key) can read it out. pkcs8 and spki give DER bytes, which pem.encode(bytes, label) wraps as text; jwk gives an object (kty: 'OKP', crv: 'Ed25519', x).
  • The JWK text, parsed and passed to importKey('jwk', …, ['verify']), verifies the WebCrypto signature: the round trip loses nothing.
  • keyformat.decodePkcs8Edwards(der) returns the algorithm OID and the 32-byte seed; ed25519.keyPair(seed) rebuilds the key in pure JS, and its signature is byte for byte the WebCrypto one, because Ed25519 signing is deterministic.
  • The paste box takes a JWK or an SPKI PEM block. pem.decode(text, 'PUBLIC KEY') and keyformat.decodeSpkiEdwards check the label and the OID before WebCrypto sees the bytes; malformed text, an X25519 key or a private JWK each get a message, and a key that did not sign gets "Not valid".
  • Argument order differs: webcryptoEd25519.verify(key, signature, message), but ed25519.verify(publicKey, message, signature).
  • Ed25519 is recent in WebCrypto (Chrome 113, Firefox 130, Safari 17). The wrapper never throws: generateKey resolves false when the browser lacks it, and the page says so instead of failing later.

Code

main.js

javascriptApache-2.080 lines

// SPDX-License-Identifier: Apache-2.0
import fw from '@awacloud/fw';
import { webcryptoEd25519 } from '@awacloud/fw/crypto/webcrypto/ed25519.js';
import { keyformat } from '@awacloud/fw/crypto/utils/keyformat.js';
import { pem } from '@awacloud/fw/crypto/utils/pem.js';
import { ed25519 } from '@awacloud/fw/crypto/pkc/ed25519.js';

fw.runtime.registerAllDeep([webcryptoEd25519, keyformat, pem, ed25519]);
const WEB = fw.runtime.resolve('webcryptoEd25519');
const KEYFORMAT = fw.runtime.resolve('keyformat');
const PEM = fw.runtime.resolve('pem');
const ED25519 = fw.runtime.resolve('ed25519');
const B64 = fw.runtime.resolve('b64'); // registered as a pem dependency

export const MALFORMED = 'Not a public key: paste a JWK (JSON) or a PUBLIC KEY PEM block.';
export const NOT_ED25519 = 'Not an Ed25519 public key.';
export const VALID = 'Valid: this public key verifies the signature over the message.';
export const INVALID = 'Not valid: this key did not sign this message.';

/** A pasted JWK (JSON) or SPKI PEM to a key; never throws, a refusal is a string. @param {string} text */
export async function importPublic(text) {
    if (text.trim().startsWith('{')) {
        let jwk;
        try { jwk = JSON.parse(text); } catch { return MALFORMED; }
        return (await WEB.importKey('jwk', jwk, ['verify'])) || NOT_ED25519;
    }
    const block = PEM.decode(text, 'PUBLIC KEY');
    if (!block) return MALFORMED;
    const spki = KEYFORMAT.decodeSpkiEdwards(block.bytes); // the algorithm OID, before WebCrypto sees it
    if (!spki || spki.oid !== KEYFORMAT.OID.ED25519) return NOT_ED25519;
    return (await WEB.importKey('spki', block.bytes, ['verify'])) || NOT_ED25519;
}

/**
 * PKCS#8 holds the 32-byte seed: pure JS rebuilds the same key from it, and Ed25519 signing is deterministic.
 * @param {Uint8Array} pkcs8 DER @param {Uint8Array} message @returns {Uint8Array | false}
 */
export function pureSign(pkcs8, message) {
    const decoded = KEYFORMAT.decodePkcs8Edwards(pkcs8);
    const pair = decoded && decoded.oid === KEYFORMAT.OID.ED25519 && ED25519.keyPair(decoded.seed);
    return pair ? ED25519.sign(pair.privateKey, message) : false;
}

const el = (/** @type {string} */ id) => /** @type {HTMLTextAreaElement} */ (document.getElementById(id));
/** @param {Uint8Array} a @param {Uint8Array} b */
const same = (a, b) => a.length === b.length && a.every((x, i) => x === b[i]);
/** @type {{ message: Uint8Array, signature: Uint8Array } | null} */
let signed = null;

el('generate').addEventListener('click', async () => {
    const keys = /** @type {CryptoKeyPair | false} */ (await WEB.generateKey(true)); // extractable, to export it
    if (!keys) { // the wrapper resolves false when crypto.subtle is missing or rejects 'Ed25519'
        el('status').textContent = WEB.isAvailable()
            ? 'Unsupported: this browser\'s WebCrypto has no Ed25519 (Chrome 113, Firefox 130, Safari 17 have it).'
            : 'Unsupported: no WebCrypto here, it needs https or localhost.';
        return;
    }
    const message = new TextEncoder().encode(el('message').value);
    const pkcs8 = /** @type {Uint8Array} */ (await WEB.exportKey('pkcs8', keys.privateKey));
    const signature = /** @type {Uint8Array} */ (await WEB.sign(keys.privateKey, message));
    signed = { message, signature };
    el('pkcs8').value = PEM.encode(pkcs8, 'PRIVATE KEY');
    el('jwk').value = JSON.stringify(await WEB.exportKey('jwk', keys.publicKey), null, 1);
    el('spki').value = PEM.encode(await WEB.exportKey('spki', keys.publicKey), 'PUBLIC KEY');
    el('signature').textContent = B64.fromBytes(signature);
    const back = await importPublic(el('jwk').value); // the JWK text, as a receiver would get it
    const ok = typeof back !== 'string' && await WEB.verify(back, signature, message);
    el('jwk-verifies').textContent = ok ? 'yes' : 'no';
    const pure = pureSign(pkcs8, message);
    el('pure-signature').textContent = pure ? B64.fromBytes(pure) : '';
    el('identical').textContent = pure && same(pure, signature) ? 'yes, byte for byte' : 'no';
    el('status').textContent = 'Signed. Paste a public key below to check the signature.';
});

el('verify').addEventListener('click', async () => {
    if (!signed) return;
    const key = await importPublic(el('paste').value);
    const valid = typeof key !== 'string' && await WEB.verify(key, signed.signature, signed.message);
    el('verdict').textContent = typeof key === 'string' ? key : valid ? VALID : INVALID;
});

index.html

htmlApache-2.043 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 · Move keys between JWK, PKCS#8 and SPKI</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>Move keys between JWK, PKCS#8 and SPKI</h1>
    <label for="message">Message to sign</label>
    <textarea id="message" rows="2">Invoice 2026-118, total 420.00 EUR</textarea>
    <p><button id="generate" type="button">Generate an Ed25519 key and sign</button></p>
    <p id="status" role="status"></p>
    <h2>The key, exported</h2>
    <label for="pkcs8">Private key (PKCS#8 PEM; shown here for the demo only)</label>
    <textarea id="pkcs8" rows="3" spellcheck="false" readonly></textarea>
    <label for="jwk">Public key (JWK)</label>
    <textarea id="jwk" rows="7" spellcheck="false" readonly></textarea>
    <label for="spki">Public key (SPKI PEM)</label>
    <textarea id="spki" rows="3" spellcheck="false" readonly></textarea>
    <p>Signature (WebCrypto, base64): <code id="signature"></code></p>
    <h2>The key, re-imported</h2>
    <dl>
      <dt>The JWK, imported back, verifies the signature</dt><dd><output id="jwk-verifies"></output></dd>
      <dt>Signature from the PKCS#8 seed, in pure JS (base64)</dt><dd><code id="pure-signature"></code></dd>
      <dt>Same as the WebCrypto signature</dt><dd><output id="identical"></output></dd>
    </dl>
    <h2>Verify with a pasted public key</h2>
    <label for="paste">Public key (JWK JSON or SPKI PEM)</label>
    <textarea id="paste" rows="7" spellcheck="false"></textarea>
    <p><button id="verify" type="button">Verify the signature</button></p>
    <p><output id="verdict"></output></p>
  </main>
</body>
</html>