Encrypt and Decrypt Strings using Node JS and Mongo DB

In this tutorial, we are going to teach you, how you can encrypt and decrypt the strings using Node JS and Mongo DB. The encrypted strings will be saved in the database and upon retrieval will be decrypted.

Setup the Project

First, create an empty folder and open a command prompt in it. Then run the following commands in it one by one:

1
2
3
4
npm init
npm install express http mongodb crypto ejs
npm install -g nodemon
nodemon server.js

crypto module will be used to encrypt and decrypt the strings. ejs module will be used to render HTML files. Then create a file named server.js at the root of folder. Open server.js file and write the following code in it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
// initialize express JS
const express = require("express");
const app = express();
 
// create HTTP server
const http = require("http").createServer(app);
 
// [include Mongo DB module here]
 
// start the server
http.listen(process.env.PORT || 3000, function () {
    console.log("Server started running...");
 
    // [connect with Mongo DB here]
});

Open your terminal and you will see the message that the server has been started. You can access your project at http://localhost:3000/

Setup Mongo DB

Write the following lines in place of [include Mongo DB module here] section in your server.js file:

1
2
3
// include mongo DB
var mongodb = require("mongodb");
var MongoClient = mongodb.MongoClient;

Then connect the database in the [connect with Mongo DB here] section:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// connect with mongo DB server
MongoClient.connect("mongodb://localhost:27017", function (error, client) {
    if (error) {
        console.error(error);
        return;
    }
 
    // set database
    db = client.db("encrypt_decrypt_string");
    console.log("Database connected");
 
    // [routes goes here]
 
});

Save the file and open your terminal, now you will see another message that the database has been connected as well.

Encrypt the String

First, include the crypto module at the top of your server.js file:

1
2
3
4
5
6
7
8
9
10
11
// include crypto module
const crypto = require("crypto")
 
// set encryption algorithm
const algorithm = 'aes-256-cbc'
 
// private key
const key = "adnan-tech-programming-computers" // must be of 32 characters
 
// random 16 digit initialization vector
const iv = crypto.randomBytes(16)

The key and initialization vector can be any string of 32 and 16 characters respectively. But it is recommended to keep the key hard-coded and initialization vector to be random. Because IV will be saved in database.

We cannot save the key in the database, because if the database gets hacked then all your encrypted strings will be compromised as well.

After that, create a GET route that will encrypt the string and save in Mongo DB. Write the following code in the [routes goes here] section:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
// route to encrypt the message
app.get("/encrypt/:message", async function (request, result) {
    // get message from URL
    const message = request.params.message;
 
    // random 16 digit initialization vector
    const iv = crypto.randomBytes(16);
 
    // encrypt the string using encryption algorithm, private key and initialization vector
    const cipher = crypto.createCipheriv(algorithm, key, iv);
    let encryptedData = cipher.update(message, "utf-8", "hex");
    encryptedData += cipher.final("hex");
 
    // convert the initialization vector to base64 string
    const base64data = Buffer.from(iv, 'binary').toString('base64');
     
    // save encrypted string along wtih initialization vector in database
    await db.collection("strings").insertOne({
        iv: base64data,
        encryptedData: encryptedData
    });
 
    // show the encrypted message
    result.send(encryptedData);
});

Save the file and try to access the URL: http://localhost:3000/encrypt/This is a test string

You can write any string in the URL and you will see the encrypted text in the browser and also in your Mongo DB.

Show all Encrypted Strings

To show all encrypted strings, we are going to use a module named ejs. Write the following line at the top of your server.js file:

1
2
// set templating engine as EJS
app.set("view engine", "ejs");

The create the following GET route to show all encrypted strings:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
// route to show all encrypted messages
app.get("/", async function (request, result) {
    // get all data from database
    const data = await db.collection("strings")
        .find({})
        .sort({
            _id: -1
        }).toArray();
 
    // render index.ejs
    result.render("index", {
        data: data
    });
});

Create a new folder named views and inside it create a file named index.ejs. It will have the following code:

1
2
3
4
5
6
7
8
9
10
11
<table>
    <% for (let d in data) { %>
        <tr>
            <td>
                <a href="/decrypt/<%= data[d].encryptedData %>" target="_blank">
                    <%= data[d].encryptedData %>
                </a>
            </td>
        </tr>
    <% } %>
</table>

Access the URL: http://localhost:3000/ and you will see all your encrypted strings in descending order.

Decrypt the String

To decrypt the string, create a GET route and fetch the encrypted string and initialization vector from Mongo DB. Then we can apply the decryption using key.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// route to decrypt the message
app.get("/decrypt/:encrypted", async function (request, result) {
    // get encrypted text from URL
    const encrypted = request.params.encrypted;
 
    // check if text exists in database
    const obj = await db.collection("strings").findOne({
        encryptedData: encrypted
    });
 
    if (obj == null) {
        result.status(404).send("Not found");
        return;
    }
 
    // convert initialize vector from base64 to buffer
    const origionalData = Buffer.from(obj.iv, 'base64')
 
    // decrypt the string using encryption algorithm and private key
    const decipher = crypto.createDecipheriv(algorithm, key, origionalData);
    let decryptedData = decipher.update(obj.encryptedData, "hex", "utf-8");
    decryptedData += decipher.final("utf8");
 
    // display the decrypted string
    result.send(decryptedData);
});

If you click on any string now, you will see the actual string.

[wpdm_package id=’1554′]

Detect page leave – HTML & Javascript

In this article, we are going to teach you, how you can detect page leave event using Javascript. Sometimes we would want some action, like an AJAX call when the user leave the page and move to another tab. Or minimize the browser.

We will create a simple video tag. And we will pause the video as soon as the user leaves the tab using Javascript. Also, we will play the video when the user comes back again on the site.

First, you need to create a video tag.

1
<video src="media/test.mp4" style="width: 100%;" controls id="video"></video>
  • The src attribute will be the path of the video file.
  • The width is 100% so the video will not overflow the webpage.
  • controls attribute to display play/pause, volume up/down, and other controls.
  • Unique ID so it can be accessible in Javascript.

At this point, you will see a video player on your website. If you play the video and move to another tab, the video will keep playing in the background. So the following Javascript code will make sure the video gets paused as soon as the user leaves the tab, and play the video back when the user re-enters the tab.

1
2
3
4
5
6
7
8
9
const video = document.getElementById("video");
 
document.addEventListener("visibilitychange", function () {
    if (document["hidden"]) {
        video.pause();
    } else {
        video.play();
    }
});

Refresh the page and play the video again. Now if you move to another tab, you will see that the video automatically gets paused and resumed from the same point where it was left when you re-open the tab.

So that’s how you can detect page leave event on your website using simple and plain Javascript. You can check out our other Javascript tutorials to learn more about Javascript.

[wpdm_package id=’1559′]