Skip to content

Instantly share code, notes, and snippets.

@jeremyckahn
Created December 4, 2023 03:13
Show Gist options
  • Save jeremyckahn/66d54e4960bf42e3256f48004aab7ce6 to your computer and use it in GitHub Desktop.
Save jeremyckahn/66d54e4960bf42e3256f48004aab7ce6 to your computer and use it in GitHub Desktop.
Use Web Crypto API to create public and private key pairs and convert them to strings
// Generated by ChatGPT: https://chat.openai.com/share/eef660d9-eaf2-494e-8175-54290254c73f
// Function to generate a key pair
async function generateKeyPair() {
try {
const keyPair = await window.crypto.subtle.generateKey(
{
name: 'RSA-OAEP',
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: 'SHA-256',
},
true,
['encrypt', 'decrypt']
);
return keyPair;
} catch (error) {
console.error('Key generation error:', error);
}
}
// Function to export key as a PEM string
async function exportKeyAsPEM(key, type) {
try {
const exportedKey = await window.crypto.subtle.exportKey(type === 'PUBLIC' ? 'spki' : 'pkcs8', type === 'PUBLIC' ? key.publicKey : key.privateKey);
const exportedAsString = arrayBufferToBase64(exportedKey);
const pemString = `-----BEGIN ${type} KEY-----\n${exportedAsString}\n-----END ${type} KEY-----\n`;
return pemString;
} catch (error) {
console.error('Key export error:', error);
}
}
// Function to convert ArrayBuffer to Base64
function arrayBufferToBase64(buffer) {
const binary = String.fromCharCode.apply(null, new Uint8Array(buffer));
return btoa(binary);
}
// Example usage
(async () => {
const keyPair = await generateKeyPair();
const publicKeyPEM = await exportKeyAsPEM(keyPair, 'PUBLIC');
const privateKeyPEM = await exportKeyAsPEM(keyPair, 'PRIVATE');
console.log('Public Key (PEM):', publicKeyPEM);
console.log('Private Key (PEM):', privateKeyPEM);
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment