|
| 1 | +(() => { |
| 2 | + /* |
| 3 | + Store the calculated signature here, so we can verify it later. |
| 4 | + */ |
| 5 | + let signature; |
| 6 | + |
| 7 | + /* |
| 8 | + Fetch the contents of the "message" textbox, and encode it |
| 9 | + in a form we can use for sign operation. |
| 10 | + */ |
| 11 | + function getMessageEncoding() { |
| 12 | + const messageBox = document.querySelector("#ed25519-message"); |
| 13 | + let message = messageBox.value; |
| 14 | + let enc = new TextEncoder(); |
| 15 | + return enc.encode(message); |
| 16 | + } |
| 17 | + |
| 18 | + /* |
| 19 | + Get the encoded message-to-sign, sign it and display a representation |
| 20 | + of the first part of it in the "signature" element. |
| 21 | + */ |
| 22 | + async function signMessage(privateKey) { |
| 23 | + const signatureValue = document.querySelector(".ed25519 .signature-value"); |
| 24 | + signatureValue.classList.remove("valid", "invalid"); |
| 25 | + |
| 26 | + let encoded = getMessageEncoding(); |
| 27 | + signature = await window.crypto.subtle.sign("Ed25519", privateKey, encoded); |
| 28 | + |
| 29 | + signatureValue.classList.add("fade-in"); |
| 30 | + signatureValue.addEventListener("animationend", () => { |
| 31 | + signatureValue.classList.remove("fade-in"); |
| 32 | + }); |
| 33 | + let buffer = new Uint8Array(signature, 0, 5); |
| 34 | + signatureValue.textContent = `${buffer}...[${signature.byteLength} bytes total]`; |
| 35 | + } |
| 36 | + |
| 37 | + /* |
| 38 | + Fetch the encoded message-to-sign and verify it against the stored signature. |
| 39 | + * If it checks out, set the "valid" class on the signature. |
| 40 | + * Otherwise set the "invalid" class. |
| 41 | + */ |
| 42 | + async function verifyMessage(publicKey) { |
| 43 | + const signatureValue = document.querySelector(".ed25519 .signature-value"); |
| 44 | + signatureValue.classList.remove("valid", "invalid"); |
| 45 | + |
| 46 | + let encoded = getMessageEncoding(); |
| 47 | + let result = await window.crypto.subtle.verify( |
| 48 | + "Ed25519", |
| 49 | + publicKey, |
| 50 | + signature, |
| 51 | + encoded |
| 52 | + ); |
| 53 | + |
| 54 | + signatureValue.classList.add(result ? "valid" : "invalid"); |
| 55 | + } |
| 56 | + |
| 57 | + /* |
| 58 | + Generate a sign/verify key, then set up event listeners |
| 59 | + on the "Sign" and "Verify" buttons. |
| 60 | + */ |
| 61 | + window.crypto.subtle |
| 62 | + .generateKey("Ed25519", true, ["sign", "verify"]) |
| 63 | + .then((keyPair) => { |
| 64 | + const signButton = document.querySelector(".ed25519 .sign-button"); |
| 65 | + signButton.addEventListener("click", () => { |
| 66 | + signMessage(keyPair.privateKey); |
| 67 | + }); |
| 68 | + |
| 69 | + const verifyButton = document.querySelector(".ed25519 .verify-button"); |
| 70 | + verifyButton.addEventListener("click", () => { |
| 71 | + verifyMessage(keyPair.publicKey); |
| 72 | + }); |
| 73 | + }); |
| 74 | +})(); |
0 commit comments