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/cbb6107e7de6c83b620960a19266055e to your computer and use it in GitHub Desktop.
Save jeremyckahn/cbb6107e7de6c83b620960a19266055e to your computer and use it in GitHub Desktop.
// 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