Node.js: how to encrypt and decrypt a string

Node.js: how to encrypt and decrypt a string

In Node.js, you can use the crypto module to encrypt and decrypt a string. In this article, we will explore how to do this.

Information security is a major concern in modern application development. One of the most common techniques for protecting sensitive data is encryption. Encryption is the process of turning data into an unreadable form, known as ciphertext, so that only authorized people can read it. In Node.js, you can use the crypto module to encrypt and decrypt a string. In this article, we will explore how to do this.

To get started, create a new folder for your project and open a terminal in the project directory. You can use the following command to create a new JavaScript file for your project:


touch encrypt_decrypt.js

Within your encrypt_decrypt.js file, initialize the project by including the Node.js crypto module:


'use strict';

const crypto = require('crypto');

To encrypt a string in Node.js, you will need to use an encryption algorithm and a secret key. Here is an example of how to encrypt a string using the AES (Advanced Encryption Standard) algorithm and a secret key:


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

const mySecretKey = 'ASuperSecureSecretKey';
const plainText = 'This is a string to be encrypted';

const encryptedText = encrypt(plainText, mySecretKey);
console.log('Encrypted text:', encryptedText);

In this example, the encrypt function takes the text to be encrypted and a secret key as input. It then uses the AES-256-CBC algorithm to perform the encryption and returns the ciphertext in hexadecimal format.

To decrypt an encrypted string, we use a decrypt function that takes the ciphertext and the same secret key used for encryption:


function decrypt(encryptedText, secretKey) {
   const decipher = crypto.createDecipher('aes-256-cbc', secretKey);
   let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
   decrypted += decipher.final('utf8');
   return decrypted;
}

const decryptedText = decrypt(encryptedText, mySecretKey);
console.log('Decrypted text:', decryptedText);

Conclusions

This is just an example of how to encrypt and decrypt a string in Node.js. It is important to note that data security requires much more than simple encryption. Key management, key protection, and other security considerations are critical to effective data protection. However, this article gives you a foundation to start implementing string encryption and decryption in your Node.js projects.