Belajar
← All lessons

How digital signatures work

Sign with the private key, verify with the public key

Maya
Mirror
You

maya.js

// once, on Maya's laptopconst keys = await crypto.subtle.generateKey(  { name: "ECDSA", namedCurve: "P-256" },  false, ["sign", "verify"]);publish(keys.publicKey); const data = new TextEncoder().encode(message);// SHA-256 the data, then sign that hashconst signature = await crypto.subtle.sign(  { name: "ECDSA", hash: "SHA-256" },  keys.privateKey, data);send({ message, signature });

you.js

// on your laptop, with only the public keyconst ok = await crypto.subtle.verify(  { name: "ECDSA", hash: "SHA-256" },  mayaPublicKey, signature,  new TextEncoder().encode(message));if (!ok) throw new Error("bad signature"); // a changed byte or the wrong keyinstall(message);

Change one byte and the signature stops matching

Message
Maya signed

A signature proves who wrote the message and that it didn't change. It doesn't hide it: anyone can read the message

you.js

// on your laptop, with only the public keyconst ok = await crypto.subtle.verify(  { name: "ECDSA", hash: "SHA-256" },  mayaPublicKey, signature,  new TextEncoder().encode(message));if (!ok) throw new Error("bad signature"); // a changed byte or the wrong keyinstall(message);

Topics

Next: How authenticator codes work

Open lesson