61 lines
1.9 KiB
JavaScript

/*
Convert an ArrayBuffer into a string
from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String
*/
export function ab2str(buf) {
return String.fromCharCode.apply(null, new Uint8Array(buf));
}
/*
Convert a string into an ArrayBuffer
from https://developers.google.com/web/updates/2012/06/How-to-convert-ArrayBuffer-to-and-from-String
*/
export function str2ab(str) {
const buf = new ArrayBuffer(str.length);
const bufView = new Uint8Array(buf);
for (let i = 0, strLen = str.length; i < strLen; i++) {
bufView[i] = str.charCodeAt(i);
}
return buf;
}
export function exportedKeyToPem(key, type) {
let exportedAsString = ab2str(key);
let exportedAsBase64 = window.btoa(exportedAsString);
return `-----BEGIN ${type.toUpperCase()} KEY-----\n${exportedAsBase64}\n-----END ${type.toUpperCase()} KEY-----`;
}
export function pemToKey(pemKey, type) {
const base64 = pemKey.replace(`-----BEGIN ${type.toUpperCase()} KEY-----`, '').replace(`-----END ${type.toUpperCase()} KEY-----`, '').trim();
const binaryDerString = window.atob(base64);
const binaryDer = str2ab(binaryDerString);
return window.crypto.subtle.importKey(
"pkcs8",
binaryDer,
{
name: "Ed25519",
},
true,
["sign"],
);
}
export async function genKey() {
// Generate keys
const { publicKey, privateKey } = await crypto.subtle.generateKey(
{
name: "Ed25519",
},
true,
["sign", "verify"],
);
const exportedPubkey = await crypto.subtle.exportKey("spki", publicKey);
const exportedPrivkey = await crypto.subtle.exportKey("pkcs8", privateKey);
// const privkey = await crypto.subtle.wrapKey("pkcs8", privateKey, wrapkey, { name: "AES-KW" });
const key = {
privateKey: exportedPrivkey,
publicKey: exportedPubkey
}
return key;
}