Created
September 8, 2021 12:53
-
-
Save DennisLoska/6918bb0e02868001108f78bd0104ad95 to your computer and use it in GitHub Desktop.
Asymmetric encryption of JSON in node.js
This file contains hidden or 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 NodeRSA = require('node-rsa'); | |
// generate new public/private key-pair | |
const key = new NodeRSA({ b: 2048 }); | |
const publicKey = key.exportKey('pkcs8-public-pem'); | |
const privateKey = key.exportKey('pkcs8-private-pem'); | |
// print the keys | |
console.log('\nPUBLIC KEY:\n'); | |
console.log(publicKey); | |
console.log('\nPRIVATE KEY:\n'); | |
console.log(privateKey); | |
console.log('\n'); | |
// data to be encrypted | |
const data = { hello: 'world' }; | |
const text = JSON.stringify(data); | |
// server code - encryption using public key | |
const serverKey = new NodeRSA(publicKey); | |
const encrypted = serverKey.encrypt(text, 'base64'); | |
console.log('encrypted: ', encrypted, '\n'); | |
// client code - decryption using private key | |
const clientKey = new NodeRSA(privateKey); | |
const decrypted = clientKey.decrypt(encrypted, 'utf8'); | |
console.log('decrypted: ', JSON.parse(decrypted)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment