← back to the blog

Encrypt and decrypt string of text example with Node JS in 5 steps

Posted on April 4th, 2019 in NodeJS by George


Cryptography is about constructing and analyzing protocols that prevent third parties or the public from reading private messages. Various aspects of information security such as data confidentialitydata integrityauthentication, and non-repudiation are central to modern cryptography. Node package library offers a few alternatives for encryption. In this example will use node-rsa.


1. Use fs node module to be able to open, read and write the files. Require NodeRSA to generate keys and use encrypt and decrypt functionality.


var fs = require('fs'); 
var NodeRSA = require('node-rsa');


2. Generate keyPair and assign a public key to be used on the encryption and another private key for decryption.  


var key =new NodeRSA().generateKeyPair();
var publicKey = key.exportKey('pkcs8-public-pem');
var privateKey = key.exportKey('pkcs1-pem');


3. Using fs module save the keys for later use.


fs.openSync('./keys/public.pem', 'w');
fs.writeFileSync('./keys/public.pem', publicKey , 'utf8');
fs.openSync('./keys/private.pem', 'w');
fs.writeFileSync('./keys/private.pem', privateKey, 'utf8');


4. Encrypt data provided to process.argv third argument, in this case an .txt file with some text string.


// encrypt data
var encrypt = key.encrypt(process.argv[2],'base64');

//create new file encrypted.txt and write (see the second argument for openSync);

//add to encrypted.txt file the encrypted data
fs.writeFileSync('test/encrypted.txt', encrypt, 'utf8');


5. Finally, using fs. read the encrypted data and pass it to decrypt function.


var textnow = fs.readFileSync('test/encrypted.txt','utf8');
console.log(textnow,'this is the data enctypted');

console.log( key.decrypt(textnow,'utf8'), 'this is the data decrypted');