Last active
July 11, 2022 09:51
-
-
Save gimenete/61d0569f29f76f7b9fe9a74f5fe8b1c0 to your computer and use it in GitHub Desktop.
Interoperability between webcrypto and crypto modules in Node.js
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
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