In my projects, I leverage two key cryptographic techniques for securing strings:
- Hash functions: These are one-way transformations that create a unique “fingerprint” of the data. They’re ideal for data integrity checks and password storage (where the original password is never retrieved).
- Encryption-decryption: This two-way process scrambles data using a secret key. Only authorized recipients with the key can decrypt the data back to its original form. This is perfect for securing sensitive information in transit or at rest.
1. Hash functions with Bcrypt (one-way)
Hash functions are essentials for store encrypted password, and the best library for nodejs is Bcrypt. Why use Bcrypt?
Install:
npm install bcrypt
To hash a password:
const bcrypt = require('bcrypt');
const saltRounds = 10;
const myPlaintextPassword = 'myPassword';
bcrypt.hash(myPlaintextPassword, saltRounds).then((hash) => {
// Store hash in your DB.
});
At user login to compare password with the one stored in the db you can use:
bcrypt.compare(plaintextPassToCheck, hashStoredInDB).then((res) => {
if(res === true){
//give access to the user
}
});
More info: github.com/kelektiv/node.bcrypt.js
2. Simple Encryption and Decryption (two-way)
In other scenarios I needed to encrypt strings in order to hide text from users but in a way that allows me to decrypt and retrieve the original content. The Node.js built-in crypto module provides this functionality (no installation needed).
To encrypt and decrypt a string using AES-256-CBC with a random initialization vector (IV):
const crypto = require('crypto');
const ENCRYPTION_KEY = crypto.randomBytes(32); // 256-bit key
const IV_LENGTH = 16;
function encrypt(text) {
const iv = crypto.randomBytes(IV_LENGTH);
const cipher = crypto.createCipheriv('aes-256-cbc', ENCRYPTION_KEY, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return iv.toString('hex') + ':' + encrypted;
}
function decrypt(text) {
const parts = text.split(':');
const iv = Buffer.from(parts.shift(), 'hex');
const encryptedText = parts.join(':');
const decipher = crypto.createDecipheriv('aes-256-cbc', ENCRYPTION_KEY, iv);
let decrypted = decipher.update(encryptedText, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
}
Note: The older
crypto.createCipher()andcrypto.createDecipher()methods are deprecated since Node.js 10. Always usecreateCipheriv/createDecipherivwith an explicit IV for security.
3. Asymmetric encryption
If you want to use private and public key to encrypt your strings, you can follow this article.