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