Encrypting and Decryption files with NodeJS

September 07, 2020

letcrypto=require('crypto'),

fs=require('fs'),

algorithm='aes-256-ctr',

secret='xxxxxxxxxxxxxxxxx';// 32 bit secret key

constencrypt=(data,secret)=>{

letiv=crypto.randomBytes(16);

console.log(iv);

letcipher=crypto.createCipheriv(algorithm,newBuffer(secret),iv);

letciphertext=Buffer.concat(\[iv,cipher.update(data) ,cipher.final()]);

returnciphertext;

}

constDecrypted=(data,secret)=>{

letiv=crypto.randomBytes(16);

console.log(iv);

letdecipher=crypto.createDecipheriv(algorithm,newBuffer(secret),data.slice(0,16));

letblob=Buffer.concat(\[decipher.update(data.slice(16,data.length)),decipher.final()]);

fs.writeFile('dcryptedfile.jpg',blob,(err)=>{

console.info('file create sussfully')

})

}

fs.readFile('simple.png',function(err,contents) {

letencrypteddat=encrypt(contents,secret);

fs.writeFile('encryptedfile',encrypteddat,(err)=>{

if(!err){

fs.readFile('encryptedfile',function(err,encruptcontents) {

Decrypted(encruptcontents,secret);

})

}

})

})

Written by Manoj Bhardwaj who lives and works in Dharamshala Himachal Pradesh (India). My stackoverflow