Created
December 6, 2023 15:30
-
-
Save jeremyckahn/cbb6107e7de6c83b620960a19266055e 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
// Written by ChatGPT: https://chat.openai.com/share/5a3241a3-d4ab-4d85-96c5-9aafdff8e483 | |
// Function to generate a key pair | |
async function generateKeyPair() { | |
const keyPair = await crypto.subtle.generateKey( | |
{ | |
name: 'RSA-OAEP', | |
modulusLength: 2048, | |
publicExponent: new Uint8Array([0x01, 0x00, 0x01]), | |
hash: 'SHA-256', | |
}, | |
true, | |
['encrypt', 'decrypt'] | |
); | |
return keyPair; | |
} | |
// Function to encrypt a string with the public key | |
async function encryptString(publicKey, plaintext) { | |
const encodedText = new TextEncoder().encode(plaintext); | |
const encryptedData = await crypto.subtle.encrypt( | |
{ | |
name: 'RSA-OAEP', | |
}, | |
publicKey, | |
encodedText | |
); | |
return encryptedData; | |
} | |
// Function to decrypt data with the private key | |
async function decryptString(privateKey, encryptedData) { | |
const decryptedArrayBuffer = await crypto.subtle.decrypt( | |
{ | |
name: 'RSA-OAEP', | |
}, | |
privateKey, | |
encryptedData | |
); | |
const decryptedText = new TextDecoder().decode(decryptedArrayBuffer); | |
return decryptedText; | |
} | |
// Example usage | |
(async () => { | |
try { | |
// Generate key pair | |
const keyPair = await generateKeyPair(); | |
// Get public and private keys | |
const publicKey = keyPair.publicKey; | |
const privateKey = keyPair.privateKey; | |
// Text to encrypt | |
const plaintext = 'Hello, Web Crypto API!'; | |
// Encrypt using the public key | |
const encryptedData = await encryptString(publicKey, plaintext); | |
// Decrypt using the private key | |
const decryptedText = await decryptString(privateKey, encryptedData); | |
console.log('Original Text:', plaintext); | |
console.log('Encrypted Data:', new Uint8Array(encryptedData)); | |
console.log('Decrypted Text:', decryptedText); | |
} catch (error) { | |
console.error('Error:', error); | |
} | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment