Skip to content
Home ยป Blockchain ยป Complete Guide to Node.js Crypto Module

Complete Guide to Node.js Crypto Module

node js crypto module logo on an image

The Node.js crypto module is a built-in module that provides a variety of cryptographic functions for Node.js applications, which are written in JavaScript. JavaScript is a programming language that is primarily used for creating web applications, and Node.js is a JavaScript runtime that allows developers to run JavaScript code on a server.

How does it work?

The Node.js crypto module provides a collection of cryptographic functionality like creating hashes, signing and verifying messages, and encrypting and decrypting data. These functions can be used to perform different types of encryption, decryption, signing, and hashing operations.

It is implemented in C++ and it’s considered to be relatively fast and efficient. The crypto module is a great tool for adding security to your application by performing cryptographic operations on sensitive data.

Setting up Node.js crypto module and additional crypto npm package

1. The crypto module is a built-in module in Node.js, which means it is included with the Node.js installation package and does not need to be installed separately.

You can check for the availability of the crypto module by using the require function. If the module is available, it will return an object containing the module’s exports. If the module is not available, it will throw an error.

For example:

try {
    var crypto = require('crypto');
    console.log('crypto module is available');
} catch (err) {
    console.log('crypto module is not available');
}

You can also use typeof crypto to check crypto module availability.

if (typeof crypto !== 'undefined') {
    console.log('crypto module is available');
} else {
    console.log('crypto module is not available');
}

2. There is also a npm crypto package. This package is not a replacement of the built-in crypto library, it is an addition. It provides additional functionality and flexibility over the built-in crypto library.

If you wish to use the additional functionality provided by the npm package, you can install it using npm in your application and use it along with the built-in crypto library.

Here’s how to do it. ๐Ÿ‘‡๐Ÿผ

npm install crypto

This will install the crypto package to your application and you can use it by requiring it in your code.

const crypto = require('crypto');

It’s important to note that if you’re using the crypto module in a development environment, you should always use the latest version of Node.js, as it may contain security updates and bug fixes.

Uses of the crypto module

Here are a few examples of the functionality provided by the crypto module:

1. Hashing

You can use the crypto.createHash() method to create a hash object and then use the .update() and .digest() methods to add data to the hash and generate a digest.

const crypto = require('crypto');
const hash = crypto.createHash('sha256');
hash.update('some data to hash');
console.log(hash.digest('hex')); //outputs the hash of 'some data to hash'

2. HMAC

The crypto module also provides a way to create a keyed-hash message authentication code (HMAC) by using the crypto.createHmac() method.

const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', 'a secret key');
hmac.update('some data to hash');
console.log(hmac.digest('hex')); //outputs the hmac of 'some data to hash'

3. Generating random data

You can use the crypto.randomBytes() method to generate cryptographically secure random data.

const crypto = require('crypto');
const buf = crypto.randomBytes(16);
console.log(buf.toString('hex')); // outputs a random 16 bytes hexadecimal string

4. Encryption and decryption

The crypto module provides a way to encrypt and decrypt data using symmetric key ciphers like AES.

const crypto = require('crypto');
const algorithm = 'aes-256-cbc';
const password = 'my secret key';
const key = crypto.scryptSync(password, 'salt', 32);
const iv = Buffer.alloc(16, 0);

const cipher = crypto.createCipheriv(algorithm, key, iv);
let encrypted = cipher.update('some data to encrypt', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted); // outputs the encrypted data

const decipher = crypto.createDecipheriv(algorithm, key, iv);
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted); // outputs the decrypted data

These are just a few examples of the functionality provided by the crypto module in Node.js.

The module provides many other cryptographic functions as well, such as creating digital signatures, Diffie-Hellman key exchange and various crypto primitives like RSA, ECDSA, and EdDSA.

Commonly used functions in the crypto module

crypto.createHash(algorithm): creates a hash object that can be used to generate a hash (also known as a digest) of some data using the specified algorithm. The supported algorithms are sha1, sha256, sha512, md5, etc.

crypto.createHmac(algorithm, key): creates a Hmac object that can be used to generate a hash-based message authentication code (HMAC) using the specified algorithm and key. The supported algorithms are sha1, sha256, sha512, md5, etc.

crypto.createSign(algorithm): creates a signing object that can be used to sign data using the specified algorithm. The supported algorithms are RSA-SHA1, RSA-SHA256, RSA-SHA512, etc.

crypto.createVerify(algorithm): creates a verification object that can be used to verify signed data using the specified algorithm. The supported algorithms are RSA-SHA1, RSA-SHA256, RSA-SHA512, etc.

crypto.createCipher(algorithm, password): creates a cipher object that can be used to encrypt data using the specified algorithm and password. The supported algorithms are AES-128-CBC, AES-192-CBC, AES-256-CBC, etc.

crypto.createDecipher(algorithm, password): creates a decipher object that can be used to decrypt data using the specified algorithm and password. The supported algorithms are AES-128-CBC, AES-192-CBC, AES-256-CBC, etc.

crypto.createDiffieHellman(primeLength): creates a Diffie-Hellman key exchange object that can be used to securely exchange keys. The primeLength can be any value between 512 and 8192 in increments of 64.

crypto.createECDH(curve): creates a Elliptic Curve Diffie-Hellman (ECDH) key exchange object that can be used to securely exchange keys. The curve can be any one of the named curves such as ‘secp521r1’, ‘secp384r1’, ‘prime256v1’, etc.

crypto.createDecipheriv(algorithm, key, iv): creates a decipher object that can be used to decrypt data using the specified algorithm, key and initialization vector (iv).

crypto.createHash(algorithm, options): creates a hash object that can be used to generate a hash (also known as a digest) of some data using the specified algorithm and options.

crypto.randomBytes(size): generates cryptographically strong pseudo-random data of the specified size. It is commonly used to generate random keys or nonces.

crypto.randomFill(buffer, offset, size): fills the specified buffer with cryptographically strong pseudo-random data starting at the specified offset and continuing for the specified size.

crypto.pbkdf2Sync(password, salt, iterations, keylen, digest): generates a derived key using the PBKDF2 algorithm, which is a password-based key derivation function.

crypto.scryptSync(password, salt, keylen, options): generates a derived key using the scrypt algorithm, which is a password-based key derivation function designed to be more computationally expensive than PBKDF2.

crypto.getCiphers(): returns an array of the names of the supported ciphers.

crypto.getHashes(): returns an array of the names of the supported hash algorithms.

crypto.getDiffieHellman(group_name): returns a predefined Diffie-Hellman key exchange object.

crypto.createCredentials(options): creates a credentials object that can be used to establish secure connections using the tls module.

crypto.createECDH(curve) : creates a Elliptic Curve Diffie-Hellman (ECDH) key exchange object that can be used to securely exchange keys.

crypto.publicEncrypt(key, buffer) : encrypts the given buffer with the given public key.

crypto.privateDecrypt(key, buffer) : decrypts the given buffer with the given private key.

crypto.generateKeyPairSync(type, options) : generates a public/private key pair in synchronous way.

crypto.createCipheriv(algorithm, key, iv): creates a cipher object that can be used to encrypt data using the specified algorithm, key and initialization vector (iv).

crypto.createCredentials(options): creates a credentials object that can be used to establish secure connections using the tls module.

That’s all for this guide. Hopefully you found it useful! ๐Ÿ”ฎ

Tags: