Last active
April 13, 2023 21:38
-
-
Save renatoargh/54b641cdeac2f2bc7bfa38727b64729c to your computer and use it in GitHub Desktop.
RSA 4096 Assymmetric key encrypt/decrypt example
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
import { JWK, JWE } from 'node-jose'; | |
const store = JWK.createKeyStore() | |
const alphaKey = await JWK.createKey("RSA", 4096, { | |
kid: '258df19c-f3bf-4f39-8829-a9adbd97d7d7', | |
alg: 'RSA-OAEP-256', | |
use: 'enc', | |
expires_on: Math.floor(new Date().valueOf() / 1000), | |
}) | |
const betaKey = await JWK.createKey("RSA", 4096, { | |
kid: 'd955c2af-82e3-4e58-ae70-aa1afa8baf63', | |
alg: 'RSA-OAEP-256', | |
use: 'enc', | |
expires_on: Math.floor(new Date().valueOf() / 1000), | |
}) | |
await Promise.all([ | |
store.add(alphaKey), | |
store.add(betaKey), | |
]) | |
const plaintext = 'potato' | |
const format = 'compact' // `compact` meand JWT-like string. `flattened` means an object format. | |
// PUBLIC KEY ONLY | |
const alphaPublic = alphaKey.toJSON(false) // export PUBLIC key only | |
console.log('> Public Key:', JSON.stringify(alphaPublic, null, 2)) | |
const publicEncrypted = await JWE.createEncrypt({ format }, alphaPublic).update(plaintext).final(); | |
console.log(`> public encrypted (${format}):`, publicEncrypted) | |
const publicDecrypted = await JWE.createDecrypt(store).decrypt(publicEncrypted) | |
console.log('> public decrypted:', publicDecrypted.plaintext.toString()) | |
console.log('') | |
// PRIVATE KEY ONLY | |
const alphaPrivateAndPublic = alphaKey.toJSON(true) // export PUBLIC and PRIVATE keys | |
console.log('> Public and Private Key:', JSON.stringify(alphaPrivateAndPublic, null, 2)) | |
const privateEncrypted = await JWE.createEncrypt({ format }, alphaPrivateAndPublic).update(plaintext).final(); | |
console.log(`> private encrypted (${format}):`, privateEncrypted) | |
const privateDecrypted = await JWE.createDecrypt(store).decrypt(privateEncrypted) | |
console.log('> private decrypted:', privateDecrypted.plaintext.toString()) | |
console.log('') | |
// EXPORTING THE STORE AS JWKS | |
console.log('> JWKS:', JSON.stringify(store.toJSON(false), null, 2)) // `false` means only public keys exported |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: