Skip to content

Instantly share code, notes, and snippets.

@victor141516
Created July 23, 2025 07:49
Show Gist options
  • Save victor141516/184f321edd4ca4c3b230a2a9c3e59464 to your computer and use it in GitHub Desktop.
Save victor141516/184f321edd4ca4c3b230a2a9c3e59464 to your computer and use it in GitHub Desktop.
async function generateKeysAndId() {
const keyPair = await crypto.subtle.generateKey(
{
name: "RSASSA-PKCS1-v1_5",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: "SHA-256",
},
true,
["sign", "verify"]
);
const [pubBuf, privBuf] = await Promise.all([
crypto.subtle.exportKey("spki", keyPair.publicKey),
crypto.subtle.exportKey("pkcs8", keyPair.privateKey),
]);
const hash = new Uint8Array(await crypto.subtle.digest("SHA-256", pubBuf));
const id = [...hash.slice(0, 16)]
.flatMap((b) => [b >> 4, b & 0x0f])
.map((n) => String.fromCharCode(97 + n))
.join("");
const toPem = (buf, type) => {
const b64 = btoa(String.fromCharCode(...new Uint8Array(buf)));
const lines = b64.match(/.{1,64}/g).join("\n");
return `-----BEGIN ${type}-----\n${lines}\n-----END ${type}-----`;
};
const privKey = toPem(privBuf, "PRIVATE KEY");
const pubKey = btoa(String.fromCharCode(...new Uint8Array(pubBuf)));
return { id, privKey, pubKey };
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment