Mysql Store Encryption and Decryption in Node.js using Crypto Curl Api

NodeJS Mysql Encryption Decryption Crypto Curl Api

Web applications have access to large amounts of data that belongs to people, organizations, and governments. The more the data is accessed, the higher the threat to data security. In the software development industry, developers use cryptography and encryption techniques to protect sensitive data from malicious parties.

Cryptography is used to secure data stored in a database or transferred over a software development industry network. When handling, moving, and storing data, you must do it safely and securely.

Thus as a node.js developer, you should understand how to encrypt and decrypt data to secure data processed by your system. Node.js has a built-in library called crypto for data encryption and decryption.

Cryptography in node.js

Cryptography is crucial for software development. Data must be protected. Cryptography is a study of techniques on how to keep the data secure. It converts the data into a secret by converting plaintext into unreadable text and vice versa. Hence only the sender and the receiver of that data can understand its content.

The three main components of a cryptosystem include plaintext, ciphertext, and algorithm. To make information a secret, we use a cipher and an algorithm that turns plaintext into ciphertext. Converting data into unreadable text is called encryption, and reversing it back to plaintext is decryption.

Cryptographic algorithms use a key to convert plaintext to ciphertext. Converting ciphertext back to plaintext is possible only if you have the right key with you.

Create a new project

Create a new directory in your local file system and switch to it by typing the following:

mkdir crypto && cd crypto

Now execute the following command to initialize a new Node.js project:

npm init -y

After creating project install node package run command:

npm install --save @babel/polyfill body-parser express morgan sequelize mysql2

install node dev dependencies package run command:

npm install --save-dev @babel/core @babel/cli @babel/preset-env @babel/node nodemon

create the .babelrc file and add this code :

{
    "presets": [
        "@babel/preset-env"
    ]
}

 open package.json and change "scripts"

"scripts": {
    "dev": "nodemon src/server.js --exec babel-node",
    "build": "babel src --out-dir dist",
    "start": "node dist/server.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  }

create the server.js file and add this code :

import app from './app';
import "@babel/polyfill"
async function main(){
await app.listen(process.env.PORT || 7557);
   console.log("server run on 7557");
}
main();

create the app.js file and add this code :

import express from 'express';
import morgan from 'morgan';
import path from 'path';
import "@babel/polyfill";
let crypto;
try {
    crypto = require('crypto');
} catch (err) {
    //   console.log('crypto support is disabled!');
}

//Importing Routes
import ProductRoutes from './routes/product';

const app = express();

//middlewares
app.all('*', function(req, res, next) {
    req.headers['if-none-match'] = 'no-match-for-this';
    res.setHeader("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "POST, PUT, OPTIONS, DELETE, GET");
    res.header("Access-Control-Max-Age", "3600");
    res.header("Access-Control-Allow-Headers", "Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With, x-access-token");
    next();
});

app.use('/', express.static(path.join(__dirname, '../app')));
app.use(morgan('dev'));
app.use(express.json({
    limit: '100mb'
}));
app.use(express.urlencoded({
    limit: '50mb',
    'extended': 'true'
}));
app.use(express.json({
    type: 'application/vnd.api+json'
}));

app.get('/', (req, res) => {
    return res.status(200).sendFile(path.join(__dirname, '../app', 'index.html'));
})

//routes
app.use('/api/product', ProductRoutes)

export default app;

Create product.js in routes folder <project name>/src/routes/product.js and add this code :

import {
    Router
} from 'express';
const ProductrRouter = Router();
import "@babel/polyfill"

import {
    createProduct,
    getProduct,
    getProducts,
    deleteProduct,
    updateProducts
} from '../controllers/product.controller';

ProductrRouter.get('/', getProducts);
ProductrRouter.get('/:id', getProduct);
ProductrRouter.post('/', createProduct);
ProductrRouter.delete('/:id', deleteProduct);
ProductrRouter.put('/:id', updateProducts);

export default ProductrRouter;

Create product.js in models folder <project name>/src/models/product.js and add this code :

import Sequelize from 'sequelize';
import {
    sequelize
} from '../database/database'

const Product = sequelize.define('product', {
    id: {
        type: Sequelize.INTEGER,
        primaryKey: true
    },
    name: {
        type: Sequelize.STRING
    },
    price: {
        type: Sequelize.STRING,
    }
}, {
    timestamps: false
});

export default Product;

 

Create product.js in models folder <project name>/src/security/product.js and add this code :

const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const iv = Buffer.from("crypto.randomBytes(16) like ndkwndkwndwndiwndiwn121", 'hex'); //crypto.randomBytes(16);

let key = '';
export const encreption = async (data) => {
    key = crypto.createHash('sha256').update(data.encreptionKey).digest('base64').substr(0, 32);
    data.name = await data.name && data.name !== '' ? encrypt(data.name).toString() : '';
    data.price = await data.price && data.price !== '' ? encrypt(data.price).toString() : '';
    return data;
};

export const decreption = async (data, type, keydata) => {
    key = crypto.createHash('sha256').update(keydata).digest('base64').substr(0, 32);
    if (await type === 'array') {
        await data.map(item => {
            item.name = item.name && item.name !== '' ? decrypt(item.name) : '';
            item.price = item.price && item.price !== '' ? decrypt(item.price) : '';
        });
        return data;
    } else if (type === "object") {
        data.dataValues.name = data.dataValues.name && data.dataValues.name !== '' ? decrypt(data.dataValues.name) : '';
        data.dataValues.price = data.dataValues.price && data.dataValues.price !== '' ? decrypt(data.dataValues.price) : '';
        return data;
    } else {
        return data;
    }
};

function encrypt(text) {
    let cipher = crypto.createCipheriv(algorithm, Buffer.from(key), iv);
    let encrypted = cipher.update(text);
    encrypted = Buffer.concat([encrypted, cipher.final()]);
    return encrypted.toString('hex');
}

function decrypt(text) {
    let encryptedText = Buffer.from(text, 'hex');
    let decipher = crypto.createDecipheriv(algorithm, Buffer.from(key), iv);
    let decrypted = decipher.update(encryptedText);
    decrypted = Buffer.concat([decrypted, decipher.final()]);
    return decrypted.toString();
}

Create product.controller.js in models folder <project name>/src/models/product.controller.js and add this code :

import Product from '../models/product';
import Sequelize from 'sequelize';
import {
    decreption,
    encreption
} from '../security/product';
const Op = Sequelize.Op;

export async function getProducts(req, res) {
    try {
        let getdata = await Product.findAll({});
        if (getdata) {
            let respoonse = await decreption(getdata, 'array', 'info@codesolution.co.in')
            res.json({
                success: true,
                message: "Product Fetch Successfully",
                data: respoonse
            });
        }
    } catch (err) {
        res.status(500).json({
            success: false,
            message: "Something went wrong!"
        })
    }
}

export async function getProduct(req, res) {
    try {
        let createdata = await Product.findOne({
            where: {
                id: req.params.id
            }
        });
        if (createdata) {
            let respoonse = await decreption(createdata, 'object', 'info@codesolution.co.in')
            res.json({
                success: true,
                message: "Product fetch Successfully",
                data: respoonse
            });
        }
    } catch (err) {
        res.status(500).json({
            success: false,
            message: "Something went wrong!"
        })
    }
}

export async function createProduct(req, res) {
    try {
        req.body.encreptionKey = 'info@codesolution.co.in';
        let data = await encreption(req.body);
        let createdata = await Product.create(data, {
            fields: ['name', 'price']
        });
        if (createdata) {
            res.json({
                success: true,
                message: "Product Created Successfully",
                data: createdata
            });
        }
    } catch (err) {
        res.status(500).json({
            success: false,
            message: "Something went wrong!"
        })
    }
}

export async function deleteProduct(req, res) {
    try {
        let deletedata = await Product.destroy({
            where: {
                id: req.params.id
            }
        });
        if (deletedata) {
            res.json({
                success: true,
                message: "Product Created Successfully",
                data: deletedata
            });
        }
    } catch (err) {
        res.status(500).json({
            success: false,
            message: "Something went wrong!"
        })
    }
}

export async function updateProducts(req, res) {
    try {
        req.body.encreptionKey = 'info@codesolution.co.in';
        let updatedata = await encreption(req.body);
        let finddata = await Product.findOne({
            where: {
                id: req.params.id
            }
        });

        if (finddata) {
            finddata.update(updatedata);
        }

        return res.json({
            success: true,
            message: "Product Created Successfully",
            data: finddata
        });
    } catch (err) {
        res.status(500).json({
            success: false,
            message: "Something went wrong!"
        })
    }
}

Create database.js in models folder <project name>/src/models/database.js and add this code :

import Sequelize from 'sequelize';

export const sequelize = new Sequelize('db name', 'username', 'password', {
    host: "localhost",
    dialect: 'mysql',
    login: false,
    logging: false,
});

sequelize.authenticate()
    .then(() => {
        console.log('Connection has been established successfully.');
    })
    .catch(err => {
        console.error('Unable to connect to the database:', err);
    });

 

Rest API Using  Sequelize, babel, and ES6 in NodeJs with Mysql database Done.

Run command

npm run dev // development server with babel-node
npm start // development server
npm test // testing server
npm run build // create dist folder for producation 

Thank you smiley

About the author
Code solution

info@codesolution.co.in

Discussion
  • 0 comments

Add comment To Login
Add comment