Last active
December 9, 2023 20:58
-
-
Save jeremyckahn/bee18ad83ab869cf05b91dbfaff640fe to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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 ECDH key pair | |
const keyPair = await crypto.subtle.generateKey( | |
{ | |
name: "ECDH", | |
namedCurve: "P-256", | |
}, | |
true, // Whether the key is extractable (private key) | |
["deriveKey", "deriveBits"] // 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: "ECDH", | |
namedCurve: "P-256", | |
}, | |
false, | |
[] | |
); | |
console.log("Imported Public Key:", importedPublicKey); | |
// Convert the private key string back to CryptoKey | |
const importedPrivateKey = await crypto.subtle.importKey( | |
"pkcs8", | |
base64ToArrayBuffer(privateKeyString), | |
{ | |
name: "ECDH", | |
namedCurve: "P-256", | |
}, | |
false, | |
["deriveKey", "deriveBits"] | |
); | |
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