Last active
August 6, 2019 13:46
-
-
Save chetbox/35c100f709d634bc9ec8b8451a1233a7 to your computer and use it in GitHub Desktop.
RSA asymmetric data encrypt and decrypt 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 { generateKeyPairSync, publicEncrypt, privateDecrypt } = require('crypto'); | |
const { publicKey, privateKey } = generateKeyPairSync('rsa', { | |
modulusLength: 4096, | |
publicKeyEncoding: { | |
type: 'spki', | |
format: 'pem', | |
}, | |
privateKeyEncoding: { | |
type: 'pkcs8', | |
format: 'pem' | |
} | |
}); | |
console.log('privateKey', privateKey); | |
console.log('publicKey', publicKey); | |
const message = { | |
some: 'data', | |
abc: 123 | |
}; | |
console.log('\nEncrypted message using public key:'); | |
console.log(message); | |
const encryptedData = publicEncrypt(publicKey, Buffer.from(JSON.stringify(message))); | |
console.log('\nEncrypted message (base 64):') | |
console.log(encryptedData.toString('base64')); | |
const decryptedData = JSON.parse(privateDecrypt(privateKey, encryptedData).toString()); | |
console.log('\nDecrypted message with private key:'); | |
console.log(decryptedData); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment