-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
pkcs8.js
53 lines (47 loc) · 1.53 KB
/
pkcs8.js
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
(() => {
/*
Convert an ArrayBuffer into a string
from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String
*/
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
/*
Export the given key and write it into the "exported-key" space.
*/
async function exportCryptoKey(key) {
const exported = await window.crypto.subtle.exportKey(
"pkcs8",
key
);
const exportedAsString = ab2str(exported);
const exportedAsBase64 = window.btoa(exportedAsString);
const pemExported = `-----BEGIN PRIVATE KEY-----\n${exportedAsBase64}\n-----END PRIVATE KEY-----`;
const exportKeyOutput = document.querySelector(".exported-key");
exportKeyOutput.classList.add("fade-in");
exportKeyOutput.addEventListener("animationend", () => {
exportKeyOutput.classList.remove("fade-in");
}, { once: true });
exportKeyOutput.textContent = pemExported;
}
/*
Generate a sign/verify key pair,
then set up an event listener on the "Export" button.
*/
window.crypto.subtle.generateKey(
{
name: "RSA-PSS",
// Consider using a 4096-bit key for systems that require long-term security
modulusLength: 2048,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256",
},
true,
["sign", "verify"]
).then((keyPair) => {
const exportButton = document.querySelector(".pkcs8");
exportButton.addEventListener("click", () => {
exportCryptoKey(keyPair.privateKey);
});
});
})();