+5

🔐Protecting Sensitive Data with Encryption and Hashing in Node.js Express

In this article, we will explore how to protect sensitive data using encryption and hashing techniques in a Node.js Express application. We will cover the following topics:

  1. Introduction to Encryption and Hashing
  2. Encrypting Data with Node.js Crypto Module
  3. Hashing Data with Node.js Crypto Module
  4. Implementing Encryption and Hashing in Express

1. Introduction to Encryption and Hashing

Sensitive data, such as passwords, personal information, and financial details, should always be protected when stored or transmitted. Two common methods for protecting sensitive data are encryption and hashing.

Encryption is the process of converting data into a secret code to prevent unauthorized access. It uses a secret key for both encryption and decryption, ensuring that only authorized parties can access the data. Encryption is reversible, meaning that the encrypted data can be decrypted to its original form.

Hashing is a one-way function that transforms data into a fixed-size string of characters, typically a hash value. Unlike encryption, hashing is irreversible, meaning that it is impossible to recover the original data from the hash value. This makes hashing particularly suitable for storing sensitive data like passwords, as even if the hash values are leaked, the original data remains secure.

2. Encrypting Data with Node.js Crypto Module

Node.js includes a built-in module called crypto that provides a wide range of cryptographic functions, including encryption. Let's see how to use the crypto module to perform symmetric encryption using the AES-256-CBC algorithm.

Installing Dependencies

To use the crypto module, we must first install the required dependencies:

npm install --save crypto

Encrypting and Decrypting Data

Here's an example demonstrating how to encrypt and decrypt data using AES-256-CBC:

const crypto = require("crypto");

const secretKey = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

function encrypt(text) {
  const cipher = crypto.createCipheriv("aes-256-cbc", secretKey, iv);
  let encrypted = cipher.update(text, "utf8", "hex");
  encrypted += cipher.final("hex");
  return encrypted;
}

function decrypt(encrypted) {
  const decipher = crypto.createDecipheriv("aes-256-cbc", secretKey, iv);
  let decrypted = decipher.update(encrypted, "hex", "utf8");
  decrypted += decipher.final("utf8");
  return decrypted;
}

const originalText = "Sensitive data";
const encryptedText = encrypt(originalText);
const decryptedText = decrypt(encryptedText);

console.log("Original Text:", originalText);
console.log("Encrypted Text:", encryptedText);
console.log("Decrypted Text:", decryptedText);

3. Hashing Data with Node.js Crypto Module

Now let's see how to use the crypto module to hash data using the SHA-256 algorithm.

Hashing Data

Here's an example demonstrating how to hash data using SHA-256:

const crypto = require("crypto");

function hashData(data) {
  return crypto
    .createHash("sha256")
    .update(data, "utf8")
    .digest("hex");
}

const data = "Sensitive data";
const hashedData = hashData(data);

console.log("Data:", data);
console.log("Hashed Data:", hashedData);

4. Implementing Encryption and Hashing in Express

Now let's see how to integrate encryption and hashing into an Express application.

Installing Dependencies

First, install the required dependencies:

npm install --save express body-parser crypto

Setting Up Express Application

Create a new Express application and include the necessary modules:

const express = require("express");
const bodyParser = require("body-parser");
const crypto = require("crypto");

const app = express();
app.use(bodyParser.json());

const secretKey = crypto.randomBytes(32);
const iv = crypto.randomBytes(16);

Encrypting Data in Express Route

Create a new route to handle encrypting the data sent in a POST request:

app.post("/encrypt", (req, res) => {
  const text = req.body.text;

  if (!text) {
    return res.status(400).send("No data provided");
  }

  const encryptedText = encrypt(text);
  res.status(200).send({ encrypted: encryptedText });
});

Hashing Data in Express Route

Create another route to handle hashing the data sent in a POST request:

app.post("/hash", (req, res) => {
  const data = req.body.data;

  if (!data) {
    return res.status(400).send("No data provided");
  }

  const hashedData = hashData(data);
  res.status(200).send({ hash: hashedData });
});

Starting Express Server

Finally, start the Express server and listen for incoming requests:

const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}`);
});

Now your Express application can receive requests to encrypt and hash sensitive data.

Conclusion

In this article, we have explored how to protect sensitive data using encryption and hashing in a Node.js Express application. By implementing these techniques, you can ensure that your application's data remains secure and protected from unauthorized access.

Keep in mind that the security of your application also depends on other factors such as secure storage of secret keys, secure communication channels, and proper access control mechanisms. It is crucial to adopt a comprehensive approach to security to safeguard your application and its users.

Mình hy vọng bạn thích bài viết này và học thêm được điều gì đó mới.

Donate mình một ly cafe hoặc 1 cây bút bi để mình có thêm động lực cho ra nhiều bài viết hay và chất lượng hơn trong tương lai nhé. À mà nếu bạn có bất kỳ câu hỏi nào thì đừng ngại comment hoặc liên hệ mình qua: Zalo - 0374226770 hoặc Facebook. Mình xin cảm ơn.

Momo: NGUYỄN ANH TUẤN - 0374226770

TPBank: NGUYỄN ANH TUẤN - 0374226770 (hoặc 01681423001)

image.png


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí