Skip to main content

Overview

The node:crypto module provides cryptographic functionality that includes a set of wrappers for OpenSSL’s hash, HMAC, cipher, decipher, sign, and verify functions.
const { createHmac } = require('node:crypto');

const secret = 'abcdefg';
const hash = createHmac('sha256', secret)
               .update('I love cupcakes')
               .digest('hex');
console.log(hash);

Core Features

Hashing

Create cryptographic hash digests of data using various algorithms:
  • SHA-256, SHA-512 - Secure Hash Algorithms
  • SHA-3 - SHA-3 family algorithms
  • MD5 - Message Digest (legacy, not recommended)
const { createHash } = require('node:crypto');

const hash = createHash('sha256');
hash.update('some data to hash');
console.log(hash.digest('hex'));

Encryption and Decryption

Encrypt and decrypt data using symmetric and asymmetric algorithms:
  • AES (CBC, CTR, GCM, OCB modes)
  • ChaCha20-Poly1305
  • RSA with OAEP padding
const {
  scrypt,
  randomFill,
  createCipheriv,
} = require('node:crypto');

const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';

scrypt(password, 'salt', 24, (err, key) => {
  if (err) throw err;
  randomFill(new Uint8Array(16), (err, iv) => {
    if (err) throw err;

    const cipher = createCipheriv(algorithm, key, iv);

    let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
    encrypted += cipher.final('hex');
    console.log(encrypted);
  });
});

Digital Signatures

Sign and verify data using asymmetric key pairs:
  • RSA (PKCS1, PSS)
  • ECDSA (Elliptic Curve Digital Signature Algorithm)
  • Ed25519, Ed448 (Edwards-curve signatures)
  • ML-DSA (Post-quantum signatures)
const { generateKeyPairSync, sign, verify } = require('node:crypto');

const { publicKey, privateKey } = generateKeyPairSync('rsa', {
  modulusLength: 2048,
});

const data = Buffer.from('important message');
const signature = sign('sha256', data, privateKey);
const isValid = verify('sha256', data, publicKey, signature);

Key Classes

Certificate

Work with SPKAC (Signed Public Key and Challenge) data:
const { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
const challenge = Certificate.exportChallenge(spkac);
const publicKey = Certificate.exportPublicKey(spkac);
const isValid = Certificate.verifySpkac(spkac);

Cipheriv

Encrypt data using specified algorithm, key, and initialization vector:
  • cipher.update(data[, inputEncoding][, outputEncoding]) - Update cipher with data
  • cipher.final([outputEncoding]) - Return remaining encrypted data
  • cipher.setAAD(buffer[, options]) - Set additional authenticated data
  • cipher.getAuthTag() - Get authentication tag for authenticated encryption

Decipheriv

Decrypt data encrypted with Cipheriv:
  • decipher.update(data[, inputEncoding][, outputEncoding]) - Update decipher with encrypted data
  • decipher.final([outputEncoding]) - Return remaining decrypted data
  • decipher.setAuthTag(buffer[, encoding]) - Set authentication tag
  • decipher.setAAD(buffer[, options]) - Set additional authenticated data

Hash

Create hash digests:
  • hash.update(data[, inputEncoding]) - Update hash with data
  • hash.digest([encoding]) - Calculate and return digest
  • hash.copy([options]) - Create deep copy of hash state

Hmac

Create HMAC (Hash-based Message Authentication Code):
const { createHmac } = require('node:crypto');

const hmac = createHmac('sha256', 'secret-key');
hmac.update('message to authenticate');
console.log(hmac.digest('hex'));

KeyObject

Represent cryptographic keys:
  • keyObject.asymmetricKeyType - Type of asymmetric key (rsa, ec, ed25519, etc.)
  • keyObject.symmetricKeySize - Size of symmetric key in bytes
  • keyObject.type - Key type: ‘secret’, ‘public’, or ‘private’
  • keyObject.export([options]) - Export key in various formats

Key Generation

generateKey()

Generate symmetric keys:
const { generateKey } = require('node:crypto');

generateKey('hmac', { length: 256 }, (err, key) => {
  if (err) throw err;
  console.log(key.export().toString('hex'));
});

generateKeyPair()

Generate asymmetric key pairs:
const { generateKeyPair } = require('node:crypto');

generateKeyPair('rsa', {
  modulusLength: 2048,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem'
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem'
  }
}, (err, publicKey, privateKey) => {
  if (err) throw err;
  // Use the keys
});
Supported key types:
  • RSA - RSA key pairs
  • RSA-PSS - RSA with PSS padding
  • DSA - Digital Signature Algorithm
  • EC - Elliptic Curve (secp256k1, P-256, P-384, P-521)
  • Ed25519, Ed448 - Edwards-curve keys
  • X25519, X448 - Curve25519/448 for key agreement
  • DH - Diffie-Hellman
  • ML-DSA, ML-KEM - Post-quantum algorithms

Random Data Generation

randomBytes()

Generate cryptographically strong random data:
const { randomBytes } = require('node:crypto');

randomBytes(32, (err, buffer) => {
  if (err) throw err;
  console.log(buffer.toString('hex'));
});

randomUUID()

Generate RFC 4122 version 4 UUID:
const { randomUUID } = require('node:crypto');

console.log(randomUUID());
// Prints: '36b8f84d-df4e-4d49-b662-bcde71a8764f'

randomInt()

Generate random integer:
const { randomInt } = require('node:crypto');

randomInt(100, (err, n) => {
  if (err) throw err;
  console.log(`Random number between 0 and 99: ${n}`);
});

Key Derivation

pbkdf2()

Password-Based Key Derivation Function 2:
const { pbkdf2 } = require('node:crypto');

pbkdf2('password', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));
});

scrypt()

Scrypt key derivation function:
const { scrypt } = require('node:crypto');

scrypt('password', 'salt', 64, (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));
});

hkdf()

HMAC-based Extract-and-Expand Key Derivation Function:
const { hkdf } = require('node:crypto');

hkdf('sha256', 'input-key-material', 'salt', 'info', 32, (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));
});

Diffie-Hellman Key Exchange

DiffieHellman

Create shared secrets using Diffie-Hellman:
const { createDiffieHellman } = require('node:crypto');

const alice = createDiffieHellman(2048);
const aliceKey = alice.generateKeys();

const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());
const bobKey = bob.generateKeys();

const aliceSecret = alice.computeSecret(bobKey);
const bobSecret = bob.computeSecret(aliceKey);
// aliceSecret and bobSecret should be equal

ECDH

Elliptic Curve Diffie-Hellman:
const { createECDH } = require('node:crypto');

const alice = createECDH('secp256k1');
alice.generateKeys();

const bob = createECDH('secp256k1');
bob.generateKeys();

const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');

Asymmetric Key Types

Key TypeDescriptionOID
'rsa'RSA1.2.840.113549.1.1.1
'rsa-pss'RSA PSS1.2.840.113549.1.1.10
'dsa'DSA1.2.840.10040.4.1
'ec'Elliptic curve1.2.840.10045.2.1
'ed25519'Ed255191.3.101.112
'ed448'Ed4481.3.101.113
'x25519'X255191.3.101.110
'x448'X4481.3.101.111
'dh'Diffie-Hellman1.2.840.113549.1.3.1
'ml-dsa-44'ML-DSA-44 (post-quantum)2.16.840.1.101.3.4.3.17
'ml-dsa-65'ML-DSA-65 (post-quantum)2.16.840.1.101.3.4.3.18
'ml-dsa-87'ML-DSA-87 (post-quantum)2.16.840.1.101.3.4.3.19
'ml-kem-512'ML-KEM-512 (post-quantum)2.16.840.1.101.3.4.4.1
'ml-kem-768'ML-KEM-768 (post-quantum)2.16.840.1.101.3.4.4.2
'ml-kem-1024'ML-KEM-1024 (post-quantum)2.16.840.1.101.3.4.4.3

Utility Functions

getCiphers()

Get list of supported cipher algorithms:
const { getCiphers } = require('node:crypto');
console.log(getCiphers());
// ['aes-128-cbc', 'aes-128-ccm', 'aes-128-cfb', ...]

getHashes()

Get list of supported hash algorithms:
const { getHashes } = require('node:crypto');
console.log(getHashes());
// ['sha1', 'sha256', 'sha512', 'md5', ...]

getCurves()

Get list of supported elliptic curves:
const { getCurves } = require('node:crypto');
console.log(getCurves());
// ['secp256k1', 'prime256v1', 'secp384r1', ...]

Security Considerations

Always use cryptographically secure random number generation for keys, IVs, and salts. Never use predictable values.
MD5 and SHA-1 are cryptographically broken and should not be used for security-critical applications.
For password hashing, use scrypt() or pbkdf2() with high iteration counts. Never store passwords in plain text.