Digital Signature — JavaScript source
Sign messages with Ed25519 or ECDSA and verify signatures. Prove authorship without revealing your private key.
This is the JavaScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
/**
* digital-signature — Ed25519 / ECDSA P-256 message signing & verification.
*
* Language: JavaScript (ES module; runs in browsers, Node >= 19, Bun, Deno).
* CosmoDev polyglot showcase port of the `digital-signature` tool, ported from
* src/lib/digital-signature.ts.
*
* Why this file exists: the TypeScript lib is a thin, careful wrapper over the
* Web Crypto API — so the JavaScript port is the same wrapper, minus the types.
* 100% client-side: keys, messages and signatures never leave the runtime. One
* substitution to note: unlike the other ports here, nothing is re-implemented
* — WebCrypto itself performs every key generation, signature and verify, and
* it already emits exactly the byte layout the tool promises (64-byte raw
* signatures, IEEE P1363 r||s for ECDSA — NOT ASN.1 DER). Ed25519 needs a
* runtime whose WebCrypto implements it; the error below says so and points at
* the ECDSA P-256 fallback, mirroring the original.
*
* display source — part of CosmoDev's polyglot tool pages.
*/
const HEX = /^(?:[0-9a-fA-F]{2})+$/;
/** The WebCrypto SubtleCrypto handle, or a descriptive throw in its absence. */
function subtle() {
const c = globalThis.crypto;
if (!c?.subtle) {
throw new Error('Web Crypto is not available in this browser context.');
}
return c.subtle;
}
function assertAlgorithm(algorithm) {
if (algorithm !== 'ed25519' && algorithm !== 'ecdsa-p256') {
throw new Error('Unknown algorithm. Use "ed25519" or "ecdsa-p256".');
}
}
function label(algorithm) {
return algorithm === 'ed25519' ? 'Ed25519' : 'ECDSA P-256';
}
/** KeyGen params object for the requested algorithm (Web Crypto shape). */
function keyGenParams(algorithm) {
return algorithm === 'ed25519'
? { name: 'Ed25519' }
: { name: 'ECDSA', namedCurve: 'P-256' };
}
/** Sign/verify params object (ECDSA must pin the hash it signs with). */
function signParams(algorithm) {
return algorithm === 'ed25519'
? { name: 'Ed25519' }
: { name: 'ECDSA', hash: 'SHA-256' };
}
function hexToBytes(hex, what) {
if (!hex || !HEX.test(hex)) {
throw new Error(`${what} must be a non-empty hex string (pairs of 0-9 / a-f digits).`);
}
const out = new Uint8Array(hex.length / 2);
for (let i = 0; i < out.length; i++) {
out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16);
}
return out;
}
function toHex(bytes) {
return Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('');
}
/**
* Generate a fresh signing key pair, exported as hex SPKI / PKCS8 keys.
* The public half is safe to share; the private half IS the identity.
*/
export async function generateKeyPair(algorithm) {
assertAlgorithm(algorithm);
let pair;
try {
pair = await subtle().generateKey(keyGenParams(algorithm), true, ['sign', 'verify']);
} catch {
throw new Error(
algorithm === 'ed25519'
? 'Ed25519 is not supported by this browser. Switch to ECDSA P-256 or update your browser.'
: 'ECDSA P-256 key generation failed.'
);
}
const spki = new Uint8Array(await subtle().exportKey('spki', pair.publicKey));
const pkcs8 = new Uint8Array(await subtle().exportKey('pkcs8', pair.privateKey));
return { publicKey: toHex(spki), privateKey: toHex(pkcs8) };
}
async function importPrivateKey(privateKeyHex, algorithm) {
const bytes = hexToBytes(privateKeyHex, 'Private key');
try {
return await subtle().importKey('pkcs8', bytes, keyGenParams(algorithm), false, ['sign']);
} catch {
throw new Error(`Invalid private key for ${label(algorithm)} (expected hex PKCS8).`);
}
}
async function importPublicKey(publicKeyHex, algorithm) {
const bytes = hexToBytes(publicKeyHex, 'Public key');
try {
return await subtle().importKey('spki', bytes, keyGenParams(algorithm), false, ['verify']);
} catch {
throw new Error(`Invalid public key for ${label(algorithm)} (expected hex SPKI).`);
}
}
/** Sign `message` with a hex PKCS8 private key. Returns the hex signature. */
export async function signMessage(message, privateKeyHex, algorithm) {
assertAlgorithm(algorithm);
if (message === '') {
throw new Error('Message must not be empty.');
}
const key = await importPrivateKey(privateKeyHex, algorithm);
const signature = await subtle().sign(
signParams(algorithm),
key,
new TextEncoder().encode(message)
);
return toHex(new Uint8Array(signature));
}
/**
* Verify `signatureHex` against `message` with a hex SPKI public key.
* Returns false when the signature, message or key simply do not match;
* throws only for malformed input (non-hex / wrong key type).
*/
export async function verifySignature(message, signatureHex, publicKeyHex, algorithm) {
assertAlgorithm(algorithm);
const signature = hexToBytes(signatureHex, 'Signature');
const key = await importPublicKey(publicKeyHex, algorithm);
return subtle().verify(
signParams(algorithm),
key,
signature,
new TextEncoder().encode(message)
);
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →