Skip to content

Instantly share code, notes, and snippets.

@chetbox
Last active August 6, 2019 13:46
Show Gist options
  • Save chetbox/35c100f709d634bc9ec8b8451a1233a7 to your computer and use it in GitHub Desktop.
Save chetbox/35c100f709d634bc9ec8b8451a1233a7 to your computer and use it in GitHub Desktop.
RSA asymmetric data encrypt and decrypt in Node JS
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