// Code taken from https://github.com/mdn/dom-examples/blob/main/web-crypto/export-key/pkcs8.js
function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
async function exportPrivateKey(key) {
const exported = await window.crypto.subtle.exportKey('pkcs8', key)
const exportedAsString = ab2str(exported)
const exportedAsBase64 = window.btoa(exportedAsString)
return `-----BEGIN PRIVATE KEY-----\n${exportedAsBase64}\n-----END PRIVATE KEY-----`
}
async function exportPublicKey(key, format) {
const exported = await window.crypto.subtle.exportKey('spki', key)
const exportedAsString = ab2str(exported)
const exportedAsBase64 = window.btoa(exportedAsString)
return `-----BEGIN PUBLIC KEY-----\n${exportedAsBase64}\n-----END PUBLIC KEY-----`
}
// EDDSA Key
/*
EDDSA support in Web Crypto is experimental and may not be present in all browsers
See: https://nodejs.org/api/webcrypto.html#ed25519ed448x25519x448-key-pairs
*/
const eddsaKey = await window.crypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify'])
const eddsaPublicKey = await exportPublicKey(eddsaKey)
const eddsaPrivateKey = await exportPrivateKey(eddsaKey)
// ECDSA Key
const ecdsaKey = await window.crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, true, ['sign', 'verify'])
const ecdsaPublicKey = await exportPublicKey(ecdsaKey)
const ecdsaPrivateKey = await exportPrivateKey(ecdsaKey)
// RSA Key
const rsaKey = await window.crypto.subtle.generateKey(
{
name: 'RSA-PSS',
modulusLength: 3072,
publicExponent: new Uint8Array([1, 0, 1]),
hash: "SHA-256",
},
true,
['sign', 'verify']
)
const rsaPublicKey = await exportPublicKey(rsaKey)
const rsaPrivateKey = await exportPrivateKey(rsaKey)