Skip to content

Instantly share code, notes, and snippets.

@gimenete
Last active July 11, 2022 09:51
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 gimenete/61d0569f29f76f7b9fe9a74f5fe8b1c0 to your computer and use it in GitHub Desktop.
Save gimenete/61d0569f29f76f7b9fe9a74f5fe8b1c0 to your computer and use it in GitHub Desktop.
Interoperability between webcrypto and crypto modules in Node.js
const crypto = require('node:crypto')
const {webcrypto} = crypto
const {subtle} = webcrypto
async function generateKeys() {
const {
publicKey,
privateKey
} = await subtle.generateKey({
name: 'RSA-OAEP',
modulusLength: 1024,
publicExponent: new Uint8Array([1, 0, 1]),
length: 256,
hash: 'SHA-1',
}, true, ['encrypt', 'decrypt']);
return {publicKey, privateKey}
}
async function aesDecrypt(ciphertext, key) {
const dec = new TextDecoder();
const plaintext = await subtle.decrypt({
name: 'RSA-OAEP',
}, key, ciphertext);
return dec.decode(plaintext);
}
async function run() {
const plaintext = 'hello world'
const {publicKey, privateKey} = await generateKeys()
const pem = '-----BEGIN PUBLIC KEY-----\n'+Buffer.from(await subtle.exportKey('spki', publicKey)).toString('base64')+'\n-----END PUBLIC KEY-----'
const pk = crypto.createPublicKey(pem)
const encrypted = crypto.publicEncrypt({key: pk}, Buffer.from(plaintext));
console.log(await aesDecrypt(encrypted, privateKey))
}
run().catch(console.error)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment