Skip to content

nodejs encryption decryption

Vijay Pratap edited this page Jul 20, 2024 · 2 revisions

NodeJS Encryption & Decryption

This repository demonstrates how to use CryptoJS for encrypting and decrypting data in a NodeJS application.

Prerequisites

  • NodeJS installed on your machine
  • express and crypto-js libraries installed

You can install crypto-js using npm:

npm install crypto-js

Environment Variables

Ensure you have the following environment variables set up in your .env file:

ENCRYPTION_SECRET_KEY=KALSJDFKAJS3LJLJ45LKJ2L346KLJLK23
APP_DEBUG=true

Encryption and Decryption Functions

Encryption

The encrypt function takes a data object as input, converts it to a JSON string, and encrypts it using the AES encryption algorithm with a secret key.

const CryptoJS = require('crypto-js');
const ENCRYPTION_SECRET_KEY = process.env.ENCRYPTION_SECRET_KEY;

const encrypt = (data) => {
    try {
        if (!data) return;
        return CryptoJS.AES.encrypt(JSON.stringify(data), ENCRYPTION_SECRET_KEY).toString();
    } catch (error) {
        console.log(error);
    }
};

Decryption

The decrypt function takes the encrypted data as input, decrypts it using the AES decryption algorithm with the same secret key, and parses the resulting JSON string back into a JavaScript object.

const decrypt = (data) => {
    try {
        if (!data) return;
        const bytes = CryptoJS.AES.decrypt(data, ENCRYPTION_SECRET_KEY);
        return JSON.parse(bytes.toString(CryptoJS.enc.Utf8));
    } catch (error) {
        console.log(error);
    }
};

API Response Function

The apiResponse function standardizes the API responses. It handles the response status, message, and data, and can show different messages based on the debug mode.

const apiResponse = (res, status, message, data) => {
    let newMessage = '';
    let responseData = data || [];

    if (process.env.APP_DEBUG === 'true') {
        newMessage = message?.message || message;
    } else {
        newMessage = message.message ? 'Something went wrong, please try again later' : message;
    }

    res.status(status).send({ data: responseData, status: status, message: newMessage });
};

Usage Example

Here is an example of how to use the encryption and decryption functions in an Express application:

const express = require('express');
const app = express();
app.use(express.json());
const { encrypt, decrypt, apiResponse } = require('./utilities');

app.post('/encrypt', (req, res) => {
    try {
        const encryptedData = encrypt(req.body);
        apiResponse(res, 200, 'Data encrypted successfully', encryptedData);
    } catch (error) {
        apiResponse(res, 500, error);
    }
});

app.post('/decrypt', (req, res) => {
    try {
        const decryptedData = decrypt(req.body.encryptedData);
        apiResponse(res, 200, 'Data decrypted successfully', decryptedData);
    } catch (error) {
        apiResponse(res, 500, error);
    }
});

app.listen(3000, () => {
    console.log('Server running on port 3000');
});

Example Requests

To encrypt data:

curl -X POST http://localhost:3000/encrypt -H "Content-Type: application/json" -d '{"name": "ABC", "password": "Qwerty@123"}'

To decrypt data:

curl -X POST http://localhost:3000/decrypt -H "Content-Type: application/json" -d '{"encryptedData": "YOUR_ENCRYPTED_DATA_HERE"}'

Notes

  • Ensure that the ENCRYPTION_SECRET_KEY is kept secure and not hard-coded in a real application. Consider using environment variables for storing the secret key.
  • Handle errors appropriately in a production environment, rather than just logging them.
Clone this wiki locally