The crypto
module of Node.js provides a wide range of functions for working with cryptography, from generating hashes to encrypting and decrypting data.
Functions of the Crypto module
Generate a Hash from a string
To generate a hash from a string, you can use the crypto
module along with the desired hash algorithm, such as SHA-256. Here’s an example of how to do it:
import { createHash } from 'node:crypto';
const string = 'Message to hash';
const hash = createHash('sha256');
hash.update(string);
const hashResult = hash.digest('hex');
console.log('SHA-256 Hash:', hashResult);
Generate a Password Hash with Salt
When it comes to securely storing passwords, it is important to use techniques such as password hashing with salt.
Bcrypt is a popular library that facilitates this process. Let’s see how to generate and compare password hashes with Bcrypt:
import { hashSync, compareSync, genSaltSync } from 'bcrypt';
const password = 'password123';
// Generate hash with salt
const saltRounds = 10;
const salt = genSaltSync(saltRounds);
const hash = hashSync(password, salt);
console.log('Password hash:', hash);
// Compare hash with entered password
const correctPassword = 'password123';
const comparisonResult = compareSync(correctPassword, hash);
console.log('Passwords match:', comparisonResult);
Generate an RSA Key Pair
The RSA encryption algorithm is widely used for asymmetric encryption. We can generate an RSA key pair with the crypto
module as follows:
import { generateKeyPairSync } from 'node:crypto';
const { publicKey, privateKey } = generateKeyPairSync('rsa', {
modulusLength: 2048,
publicKeyEncoding: {
type: 'spki',
format: 'pem'
},
privateKeyEncoding: {
type: 'pkcs8',
format: 'pem'
}
});
console.log('RSA Public Key:', publicKey);
console.log('RSA Private Key:', privateKey);
Encrypt and Decrypt Data using RSA
With the generated RSA keys, we can securely encrypt and decrypt data. Here’s an example of how to do it:
import { publicEncrypt, privateDecrypt } from 'node:crypto';
const message = 'Message to encrypt';
// Encrypt with public key
const encryptedMessage = publicEncrypt(publicKey, Buffer.from(message, 'utf8'));
console.log('Encrypted message:', encryptedMessage.toString('base64'));
// Decrypt with private key
const decryptedMessage = privateDecrypt(privateKey, encryptedMessage);
console.log('Decrypted message:', decryptedMessage.toString('utf8'));
Download the code
All the code from this entry is available for download on Github