Skip to content

Repository files navigation

#Crypto module in Node JS

##Crypto module for text string

Encryption

Here we look at converting text string to an encrypted string with the use of the crypto module in Nodejs. Here we call the function encryptMyText(textString) and pass in a text string to convert.

//Node modules requiredvarcrypto=require('crypto');constfs=require('fs');//variablesconstalgorithm='aes-256-ctr';constkey='mMj6UXSrXbSNCGDw4aQIxXBjqIIaWTVTfUm5n5ztIdUyntR906wsvW5QCjuL';functionencryptMyText(textString){varcipher=crypto.createCipher(algorithm,key);varencrypted=cipher.update(textString,'utf8','hex');encrypted+=cipher.final('hex');returnencrypted;}
######function called
######Variables vartextString='Trial string to encrypt';varresult=encryptMyText(textString)
######Results from function
Unencryption textString : Trial string to encrypt
This is the encrypted string(result) : a4120c584cf3093c1b2123a4d611414022a7a6d28fd151

The file is returned encrypted.You can now save it if you so wish.

Decryption

Here we look at converting encrypted text string to an unencrypted text string with the use of the crypto module in Nodejs. Here we call the function decryptMyText(encrypted) and pass in an encrypted string to convert.

// node modules required varcrypto=require('crypto');constfs=require('fs');//variablesconstalgorithm='aes-256-ctr';constkey='mMj6UXSrXbSNCGDw4aQIxXBjqIIaWTVTfUm5n5ztIdUyntR906wsvW5QCjuL';functiondecryptMyText(encrypted){vardecipher=crypto.createDecipher(algorithm,key);vardecrypted=decipher.update(encrypted,'hex','utf8');decrypted+=decipher.final('utf8');returndecrypted;}
############function calledVariablesvarresult=a4120c584cf3093c1b2123a4d611414022a7a6d28fd151varencryptedString=result;varunencryptedString=decryptMyText(encryptedString)

############Results from function
This is the encryptedString : a4120c584cf3093c1b2123a4d611414022a7a6d28fd151
This is the unencryptedString : Trial string to encrypt

##Crypto module for Streams

Encryption

Here we look at converting Streams to an encrypted Stream with the use of the crypto module in Nodejs. Here we call the function encryptMyStream(fileIn, fileout) and pass in a fileIn, fileOut to convert then save. This method creates a read stream with the functions first argument passed, fileIn. This is then piped into encryptIt function. This function converts it into an encrpted stream. We then need to output this file somewhere. Here we pipe it into creatWriteStream function and pass a fileout. This then writes the data to a file to be saved.

//node_modulesconstcrypto=require('crypto');varfs=require('fs');varzlib=require('zlib');//variablesconstalgorithm='aes-256-ctr';constkey='14189dc35ae35e75ff31d7502e245cd9bc7803838fbfd5c773cdcd79b8a28bbd';functionencryptMyStream(fileIn,fileout){varcreateReadStream=fs.createReadStream(fileIn);varencryptit=crypto.createCipher(algorithm,key);varzipit=zlib.createGzip();varwritestream=fs.createWriteStream(fileout);/*  OPTIONAL add to gzip file createReadStream.pipe(encryptit).pipe(zipit).pipe(writestream); */createReadStream.pipe(encryptit).pipe(writestream);//delete old file optional include below writestream.on('finish',function(){console.log('Encrypted stream written to disk!');fs.exists(fileIn,function(exists){if(exists){console.log(fileIn+' still exists. Deleting it now ...');fs.unlink(fileIn,function(done){console.log('Unencrypted file removed Successful');});}else{console.log(fileIn+' not found, so not deleting.');}});//end of fs.exists});//end of output.on };// end of encryptMyStream 
######function called
######Variables conststreamdatain='files/stream.txt';conststreamdataout='files/stream.enc';
######Function
encryptMyStream(streamdatain,streamdataout);
######Results fromfunctionThistakeanunencryptedstream=teststreamtextfromfile.encryptedoutputbeforegzip=��|V�/%X?F@34\�w

Once the file is output we then emit finish. Once emitted this function checks to see if the original unencrypted file is still there. If it is we call fs.unlink function. This function deletes that file leaving only the encrypted data.

Decryption

Here we look at converting encrypted stream to an unencrypted stream with the use of the crypto module in Nodejs. Here we call the function decryptMyStream(fileIn, fileout) and pass in an encrypted stream to convert. This method creates a read stream with the functions first argument passed, fileIn. This is then piped into decryptIt function. This function converts it into an decrypted stream. We then need to output this file somewhere. Here we pipe it into creatWriteStream function and pass a fileout. This then writes the data to a file to be saved.

Decryptioncode//node_modulesconstcrypto=require('crypto');varfs=require('fs');varzlib=require('zlib');//variablesconstalgorithm='aes-256-ctr';constkey='14189dc35ae35e75ff31d7502e245cd9bc7803838fbfd5c773cdcd79b8a28bbd';functiondecryptMyStream(fileIn,fileout){varcreateReadStream=fs.createReadStream(fileIn);vardecryptit=crypto.createDecipher(algorithm,key);varunzipit=zlib.createGunzip();varwritestream=fs.createWriteStream(fileout);/*  OPTIONAL add gunzip pipe to file createReadStream.pipe(unzipit).pipe(decryptit).pipe(writestream); */createReadStream.pipe(decryptit).pipe(writestream);//delete old file optional include writestream.on('finish',function(){console.log('encrypted stream written to disk!');fs.exists(fileIn,function(exists){if(exists){console.log(fileIn+' still exists. Deleting it now ...');fs.unlink(fileIn,function(done){console.log('encrypted file removed Successful');});}else{console.log(fileIn+' not found, so not deleting.');}});//end of fs.exists});//end of output.on};// end of decryptMyStream 
######function called
######Variables conststreamdatain='files/stream.txt';conststreamdataout='files/stream.enc';
######Function
decryptMyStream(streamdataout,streamdatain);
############Results fromfunctionThistakeanencryptedstream=��|V�/%X?F@34\�wUnencryptedoutputbeforegzip=teststreamtextfromfile

Once the file is output we then emit finish. Once emitted this function checks to see if the original unencrypted file is still there. If it is we call fs.unlink function. This function deletes that file leaving only the encrypted data.

##Crypto module for Buffers

Encryption

Here we look at converting a Buffer to an encrypted Buffer with the use of the crypto module in Nodejs. Here we call the function encryptMyBuffer(buffer) and pass a buffer. This method takes a buffer and encrypts it. A cipher is created with crypto.createCipher(algorithm, key), and we pass in an algorithm and key to use. The buffer is then passed into the cipher function created and the we call buffer.concat on it producing an encrypted buffer which is returned to the function calling it.

//node_modulesconstcrypto=require('crypto');constfs=require('fs');//variablesconstalgorithm='aes-256-ctr';constkey='mMj6UXSrXbSNCGDw4aQIxXBjqIIaWTVTfUm5n5ztIdUyntR906wsvW5QCjuL';functionencryptMyBuffer(buffer){varcipher=crypto.createCipher(algorithm,key);varcrypted=Buffer.concat([cipher.update(buffer),cipher.final()]);returncrypted;
######function calledvarresult=encryptMyBuffer((newBuffer("hello world","utf8"));
######Output
Thistakeabuffer=Buffer68656c6c6f20776f726c64encryptedbufferout(result)=�$): UO�

Decryption

Here we look at converting an encrypted Buffer to an encrypted Buffer with the use of the crypto module in Nodejs. Here we call the function decryptMyBuffer(buffer) and pass in a buffer to convert (an encrypted one). This method takes an encypted buffer and decrypts it. A decipher is created with crypto.createDecipher(algorithm, key), and we pass in an algorithm and key to use. The buffer is then passed into the decipher function created and then we call buffer.concat on it producing an unencrypted buffer which is returned to the function calling it.

Decryptioncode//node_modulesconstcrypto=require('crypto');constfs=require('fs');//variablesconstalgorithm='aes-256-ctr';constkey='mMj6UXSrXbSNCGDw4aQIxXBjqIIaWTVTfUm5n5ztIdUyntR906wsvW5QCjuL';functiondecryptMyBuffer(buffer){vardecipher=crypto.createDecipher(algorithm,key);vardecrypted=Buffer.concat([decipher.update(buffer),decipher.final()]);returndecrypted;}
######function called
######Variables varresults=decryptMyBuffer(data);
############Output
Thistakeanencryptedbuffer= '�$): �	UO�;
encryptedbufferouttobuffer(results)=Buffer68656c6c6f20776f726c64;