Cyber Security is very important irrespective of which domain you are in. In this article, I will show how to implement AES 256 encryption and decryption using NodeJS backend. With increase in cyber attacks around the world, it becomes irresistible for developers to use various encryption algorithms.
Please note we can’t decrypt data on client side. This will lead to exposure of secret key and application will become vulnerable.
Let’s start :)
We will set up NodeJS project first and then add dependancies.Create a folder called aes-using-node. Open command prompt from project folder and run below command.
npm init
This will create package.json in project folder. From same command prompt run
npm install
It will install dependancy in the project and after installation is done, you will see node_modules folder and package-lock.json. Create app.js file where all server code will be written.
Lets know about AES npm packages and various algorithm types.
Official documentation can be found on link below
Here we will be using AES 256 algorithm for encryption and decryption.There are two modes in AES algorithm : -
- EBC
- CBC
We will be implementing EBC mode for now.
Nothing fancy yet.
From root of project, run below command
npm i crypto-js — save
Create a file called crypto.js in utility folder and paste below code
‘use strict’;
const CryptoJS = require(‘crypto-js’);
module.exports = {
aesEncrypt: aesEncrypt,
aesDecrypt: aesDecrypt
};
function aesEncrypt(content) {
const parsedkey = CryptoJS.enc.Utf8.parse(secret_key);
const iv = CryptoJS.enc.Utf8.parse(your_secret_iv);
const encrypted = CryptoJS.AES.encrypt(content, parsedkey, { iv: iv, mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
return encrypted.toString();
};
function aesDecrypt(word) {
var keys = CryptoJS.enc.Utf8.parse(secret_key);
let base64 = CryptoJS.enc.Base64.parse(word);
let src = CryptoJS.enc.Base64.stringify(base64);
var decrypt = CryptoJS.AES.decrypt(src, keys, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 });
return decrypt.toString(CryptoJS.enc.Utf8);
};