Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jeremyckahn/c49ca17a849ecf35c5f957ffde956cf4 to your computer and use it in GitHub Desktop.
Save jeremyckahn/c49ca17a849ecf35c5f957ffde956cf4 to your computer and use it in GitHub Desktop.
// Generated by ChatGPT: https://chat.openai.com/share/6c78c3f4-213d-48e6-9f79-b85ef3a7adc7
// Helper functions for converting between ArrayBuffer and base64
function arrayBufferToBase64(buffer) {
const bytes = new Uint8Array(buffer);
return btoa(String.fromCharCode.apply(null, bytes));
}
function base64ToArrayBuffer(base64) {
const binaryString = atob(base64);
const bytes = new Uint8Array(binaryString.length);
for (let i = 0; i < binaryString.length; i++) {
bytes[i] = binaryString.charCodeAt(i);
}
return bytes.buffer;
}
async function generateAndImportKeys() {
try {
// Generate an RSA-OAEP key pair
const keyPair = await crypto.subtle.generateKey({
name: "RSA-OAEP",
modulusLength: 2048,
publicExponent: new Uint8Array([0x01, 0x00, 0x01]),
hash: {
name: "SHA-256"
},
},
true, // Whether the key is extractable (private key)
["encrypt", "decrypt"] // Key usages
);
// Convert public key to string
const publicKeyBuffer = await crypto.subtle.exportKey("spki", keyPair.publicKey);
const publicKeyString = arrayBufferToBase64(publicKeyBuffer);
console.log("Public Key String:", publicKeyString);
// Convert private key to string
const privateKeyBuffer = await crypto.subtle.exportKey("pkcs8", keyPair.privateKey);
const privateKeyString = arrayBufferToBase64(privateKeyBuffer);
console.log("Private Key String:", privateKeyString);
// Convert the public key string back to CryptoKey
const importedPublicKey = await crypto.subtle.importKey(
"spki",
base64ToArrayBuffer(publicKeyString), {
name: "RSA-OAEP",
hash: {
name: "SHA-256"
},
},
false,
["encrypt"]
);
console.log("Imported Public Key:", importedPublicKey);
// Convert the private key string back to CryptoKey
const importedPrivateKey = await crypto.subtle.importKey(
"pkcs8",
base64ToArrayBuffer(privateKeyString), {
name: "RSA-OAEP",
hash: {
name: "SHA-256"
},
},
false,
["decrypt"]
);
console.log("Imported Private Key:", importedPrivateKey);
} catch (error) {
console.error("Error generating or importing keys:", error);
}
}
// Call the async function
generateAndImportKeys();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment