On this page

node:crypto module methods and properties

History
M

crypto.argon2

History
crypto.argon2(algorithm, parameters, callback): void
Attributes
algorithm:string
Variant of Argon2, one of "argon2d", "argon2i" or "argon2id".
parameters:Object
REQUIRED, this is the password for password hashing applications of Argon2.
REQUIRED, must be at least 8 bytes long. This is the salt for password hashing applications of Argon2.
parallelism:number
REQUIRED, degree of parallelism determines how many computational chains (lanes) can be run. Must be at least 1 and at most 2**24-1.
tagLength:number
REQUIRED, the length of the key to generate. Must be at least 4 and at most 2**32-1.
memory:number
REQUIRED, memory cost in 1KiB blocks. Must be at least 8 * parallelism and at most 2**32-1. The actual number of blocks is rounded down to the nearest multiple of 4 * parallelism.
passes:number
REQUIRED, number of passes (iterations). Must be at least 1 and at most 2**32-1.
OPTIONAL, Random additional input, similar to the salt, that should NOT be stored with the derived key. This is known as pepper in password hashing applications. If used, must have a length not greater than 2**32-1 bytes.
OPTIONAL, Additional data to be added to the hash, functionally equivalent to salt or secret, but meant for non-random data. If used, must have a length not greater than 2**32-1 bytes.
callback:Function
err:Error
derivedKey:Buffer

Provides an asynchronous Argon2 implementation. Argon2 is a password-based key derivation function that is designed to be expensive computationally and memory-wise in order to make brute-force attacks unrewarding.

The nonce should be as unique as possible. It is recommended that a nonce is random and at least 16 bytes long. See NIST SP 800-132 for details.

When passing strings for message, nonce, secret or associatedData, please consider caveats when using strings as inputs to cryptographic APIs.

The callback function is called with two arguments: err and derivedKey. err is an exception object when key derivation fails, otherwise err is null. derivedKey is passed to the callback as a Buffer.

An exception is thrown when any of the input arguments specify invalid values or types.

const { argon2, randomBytes } = await import('node:crypto');

const parameters = {
  message: 'password',
  nonce: randomBytes(16),
  parallelism: 4,
  tagLength: 64,
  memory: 65536,
  passes: 3,
};

argon2('argon2id', parameters, (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));  // 'af91dad...9520f15'
});
const { argon2, randomBytes } = require('node:crypto');

const parameters = {
  message: 'password',
  nonce: randomBytes(16),
  parallelism: 4,
  tagLength: 64,
  memory: 65536,
  passes: 3,
};

argon2('argon2id', parameters, (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));  // 'af91dad...9520f15'
});
M

crypto.argon2Sync

History
crypto.argon2Sync(algorithm, parameters): Buffer
Attributes
algorithm:string
Variant of Argon2, one of "argon2d", "argon2i" or "argon2id".
parameters:Object
REQUIRED, this is the password for password hashing applications of Argon2.
REQUIRED, must be at least 8 bytes long. This is the salt for password hashing applications of Argon2.
parallelism:number
REQUIRED, degree of parallelism determines how many computational chains (lanes) can be run. Must be at least 1 and at most 2**24-1.
tagLength:number
REQUIRED, the length of the key to generate. Must be at least 4 and at most 2**32-1.
memory:number
REQUIRED, memory cost in 1KiB blocks. Must be at least 8 * parallelism and at most 2**32-1. The actual number of blocks is rounded down to the nearest multiple of 4 * parallelism.
passes:number
REQUIRED, number of passes (iterations). Must be at least 1 and at most 2**32-1.
OPTIONAL, Random additional input, similar to the salt, that should NOT be stored with the derived key. This is known as pepper in password hashing applications. If used, must have a length not greater than 2**32-1 bytes.
OPTIONAL, Additional data to be added to the hash, functionally equivalent to salt or secret, but meant for non-random data. If used, must have a length not greater than 2**32-1 bytes.
Returns:Buffer

Provides a synchronous Argon2 implementation. Argon2 is a password-based key derivation function that is designed to be expensive computationally and memory-wise in order to make brute-force attacks unrewarding.

The nonce should be as unique as possible. It is recommended that a nonce is random and at least 16 bytes long. See NIST SP 800-132 for details.

When passing strings for message, nonce, secret or associatedData, please consider caveats when using strings as inputs to cryptographic APIs.

An exception is thrown when key derivation fails, otherwise the derived key is returned as a Buffer.

An exception is thrown when any of the input arguments specify invalid values or types.

const { argon2Sync, randomBytes } = await import('node:crypto');

const parameters = {
  message: 'password',
  nonce: randomBytes(16),
  parallelism: 4,
  tagLength: 64,
  memory: 65536,
  passes: 3,
};

const derivedKey = argon2Sync('argon2id', parameters);
console.log(derivedKey.toString('hex'));  // 'af91dad...9520f15'
const { argon2Sync, randomBytes } = require('node:crypto');

const parameters = {
  message: 'password',
  nonce: randomBytes(16),
  parallelism: 4,
  tagLength: 64,
  memory: 65536,
  passes: 3,
};

const derivedKey = argon2Sync('argon2id', parameters);
console.log(derivedKey.toString('hex'));  // 'af91dad...9520f15'
crypto.checkPrime(candidate, options?, callback): void
Attributes
A possible prime encoded as a sequence of big endian octets of arbitrary length.
options:Object
checks?:number
The number of Miller-Rabin probabilistic primality iterations to perform. When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. Care must be used when selecting a number of checks. Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. Default: 0
callback:Function
err:Error
Set to an Error object if an error occurred during check.
result:boolean
true if the candidate is a prime with an error probability less than 0.25 ** options.checks.

Checks the primality of the candidate.

M

crypto.checkPrimeSync

History
crypto.checkPrimeSync(candidate, options?): boolean
Attributes
A possible prime encoded as a sequence of big endian octets of arbitrary length.
options:Object
checks?:number
The number of Miller-Rabin probabilistic primality iterations to perform. When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. Care must be used when selecting a number of checks. Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. Default: 0
Returns:boolean
true if the candidate is a prime with an error probability less than 0.25 ** options.checks.

Checks the primality of the candidate.

P

crypto.constants

History
Type:Object

An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in Crypto constants.

M

crypto.createCipheriv

crypto.createCipheriv(algorithm, key, iv, options?): Cipheriv
Attributes

Creates and returns a Cipheriv object, with the given algorithm, key and initialization vector (iv).

The options argument controls stream behavior and is optional except when a cipher in CCM or OCB mode (e.g. 'aes-128-ccm') is used. In that case, the authTagLength option is required and specifies the length of the authentication tag in bytes, see CCM mode. In GCM mode, the authTagLength option is not required but can be used to set the length of the authentication tag that will be returned by getAuthTag() and defaults to 16 bytes. For SIV, GCM-SIV, and chacha20-poly1305, the authTagLength option defaults to 16 bytes. SIV and GCM-SIV only support 16-byte authentication tags.

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On recent OpenSSL releases, openssl list -cipher-algorithms will display the available cipher algorithms.

The key is the raw key used by the algorithm and iv is an initialization vector. Both arguments must be 'utf8' encoded strings, Buffers, TypedArray, or DataViews. The key may optionally be a KeyObject of type secret. If the cipher does not need an initialization vector, iv may be null.

When passing strings for key or iv, please consider caveats when using strings as inputs to cryptographic APIs.

Initialization vectors should be unpredictable and unique; ideally, they will be cryptographically random. They do not have to be secret: IVs are typically just added to ciphertext messages unencrypted. It may sound contradictory that something has to be unpredictable and unique, but does not have to be secret; remember that an attacker must not be able to predict ahead of time what a given IV will be.

crypto.createDecipheriv(algorithm, key, iv, options?): Decipheriv
Attributes

Creates and returns a Decipheriv object that uses the given algorithm, key and initialization vector (iv).

The options argument controls stream behavior and is optional except when a cipher in CCM or OCB mode (e.g. 'aes-128-ccm') is used. In that case, the authTagLength option is required and specifies the length of the authentication tag in bytes, see CCM mode. For AES-GCM and chacha20-poly1305, the authTagLength option defaults to 16 bytes and must be set to a different value if a different length is used. For SIV and GCM-SIV, the authTagLength option defaults to 16 bytes and only 16-byte authentication tags are supported.

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On recent OpenSSL releases, openssl list -cipher-algorithms will display the available cipher algorithms.

The key is the raw key used by the algorithm and iv is an initialization vector. Both arguments must be 'utf8' encoded strings, Buffers, TypedArray, or DataViews. The key may optionally be a KeyObject of type secret. If the cipher does not need an initialization vector, iv may be null.

When passing strings for key or iv, please consider caveats when using strings as inputs to cryptographic APIs.

Initialization vectors should be unpredictable and unique; ideally, they will be cryptographically random. They do not have to be secret: IVs are typically just added to ciphertext messages unencrypted. It may sound contradictory that something has to be unpredictable and unique, but does not have to be secret; remember that an attacker must not be able to predict ahead of time what a given IV will be.

crypto.createDiffieHellman(prime, primeEncoding?, generator?, generatorEncoding?): DiffieHellman
Attributes
primeEncoding:string
The encoding of the prime string.
Default: 2
generatorEncoding:string
The encoding of the generator string.

Creates a DiffieHellman key exchange object using the supplied prime and an optional specific generator.

The generator argument can be a number, string, or Buffer. If generator is not specified, the value 2 is used.

If primeEncoding is specified, prime is expected to be a string; otherwise a Buffer, TypedArray, or DataView is expected.

If generatorEncoding is specified, generator is expected to be a string; otherwise a number, Buffer, TypedArray, or DataView is expected.

M

crypto.createDiffieHellman

History
crypto.createDiffieHellman(primeLength, generator?): DiffieHellman
Attributes
primeLength:number
generator?:number
Default: 2

Creates a DiffieHellman key exchange object and generates a prime of primeLength bits using an optional specific numeric generator. If generator is not specified, the value 2 is used.

M

crypto.createDiffieHellmanGroup

History
crypto.createDiffieHellmanGroup(name): DiffieHellmanGroup
Attributes

An alias for crypto.getDiffieHellman()

M

crypto.createECDH

History
crypto.createECDH(curveName): ECDH
Attributes
curveName:string
Returns:ECDH

Creates an Elliptic Curve Diffie-Hellman (ECDH) key exchange object using a predefined curve specified by the curveName string. Use crypto.getCurves() to obtain a list of available curve names. On recent OpenSSL releases, openssl ecparam -list_curves will also display the name and description of each available elliptic curve.

crypto.createHash(algorithm, options?): Hash
Attributes

Creates and returns a Hash object that can be used to generate hash digests using the given algorithm. Optional options argument controls stream behavior. For XOF hash functions such as 'shake256', the outputLength option can be used to specify the desired output length in bytes.

When the data is small (< 5MB) and readily available, crypto.hash() is usually faster.

The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. On recent releases of OpenSSL, openssl list -digest-algorithms will display the available digest algorithms.

Example: generating the sha256 sum of a file

import {
  createReadStream,
} from 'node:fs';
import { argv } from 'node:process';
const {
  createHash,
} = await import('node:crypto');

const filename = argv[2];

const hash = createHash('sha256');

const input = createReadStream(filename);
input.on('readable', () => {
  // Only one element is going to be produced by the
  // hash stream.
  const data = input.read();
  if (data)
    hash.update(data);
  else {
    console.log(`${hash.digest('hex')} ${filename}`);
  }
});
const {
  createReadStream,
} = require('node:fs');
const {
  createHash,
} = require('node:crypto');
const { argv } = require('node:process');

const filename = argv[2];

const hash = createHash('sha256');

const input = createReadStream(filename);
input.on('readable', () => {
  // Only one element is going to be produced by the
  // hash stream.
  const data = input.read();
  if (data)
    hash.update(data);
  else {
    console.log(`${hash.digest('hex')} ${filename}`);
  }
});
crypto.createHmac(algorithm, key, options?): Hmac
Attributes
algorithm:string
options:Object
encoding:string
The string encoding to use when key is a string.
Returns:Hmac

Creates and returns an Hmac object that uses the given algorithm and key. Optional options argument controls stream behavior.

The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. On recent releases of OpenSSL, openssl list -digest-algorithms will display the available digest algorithms.

The key is the HMAC key used to generate the cryptographic HMAC hash. If it is a KeyObject, its type must be secret. If it is a string, please consider caveats when using strings as inputs to cryptographic APIs. If it was obtained from a cryptographically secure source of entropy, such as crypto.randomBytes() or crypto.generateKey(), its length should not exceed the block size of algorithm (e.g., 512 bits for SHA-256).

Example: generating the sha256 HMAC of a file

import {
  createReadStream,
} from 'node:fs';
import { argv } from 'node:process';
const {
  createHmac,
} = await import('node:crypto');

const filename = argv[2];

const hmac = createHmac('sha256', 'a secret');

const input = createReadStream(filename);
input.on('readable', () => {
  // Only one element is going to be produced by the
  // hash stream.
  const data = input.read();
  if (data)
    hmac.update(data);
  else {
    console.log(`${hmac.digest('hex')} ${filename}`);
  }
});
const {
  createReadStream,
} = require('node:fs');
const {
  createHmac,
} = require('node:crypto');
const { argv } = require('node:process');

const filename = argv[2];

const hmac = createHmac('sha256', 'a secret');

const input = createReadStream(filename);
input.on('readable', () => {
  // Only one element is going to be produced by the
  // hash stream.
  const data = input.read();
  if (data)
    hmac.update(data);
  else {
    console.log(`${hmac.digest('hex')} ${filename}`);
  }
});
crypto.createPrivateKey(key): KeyObject
Attributes
The key material, either in PEM, DER, JWK, or raw format, or a URL referencing an object for an OpenSSL STORE loader.
format?:string
Must be 'pem', 'der', 'jwk', 'raw-private', or 'raw-seed'. Default: 'pem'.
type:string
Must be 'pkcs1', 'pkcs8' or 'sec1'. This option is required only if the format is 'der' and ignored otherwise.
passphrase:string | Buffer
The passphrase to use for decryption. When key is a URL, this is the optional PIN/passphrase forwarded to the STORE loader.
properties:string
The optional OpenSSL property query used when fetching the STORE loader for a URL key.
encoding:string
The string encoding to use when key is a string.
asymmetricKeyType:string
Required when format is 'raw-private' or 'raw-seed' and ignored otherwise. Must be a supported key type.
namedCurve:string
Name of the curve to use. Required when asymmetricKeyType is 'ec' and ignored otherwise.
Returns:KeyObject

Creates and returns a new key object containing a private key. If key is a string or Buffer, format is assumed to be 'pem'; otherwise, key must be an object with the properties described above.

If the private key is encrypted, a passphrase must be specified. The length of the passphrase is limited to 1024 bytes.

Stability: 1.1Active development

If key is a URL (or an object whose key is a URL), the private key is loaded through an OpenSSL STORE loader. The URL is passed to OpenSSL as a URI, for example a file: URI or a provider-backed scheme such as pkcs11:. When the Permission Model is enabled, --allow-openssl-store is required.

Warning: A URI scheme does not pin an OpenSSL STORE loader or prove where the returned key came from. Node.js forwards the URI to OpenSSL, which chooses loaders according to its version and configuration. For example, OpenSSL may offer an opaque URI such as pkcs11:object=... (one without // after the scheme) to its file loader before trying the pkcs11 loader. If the complete URI is a valid local path and that file exists, it may be loaded instead. Node.js does not verify which loader supplied the key. Do not rely on a provider-specific URI scheme as proof that a key came from that provider or from a hardware device.

Configured OpenSSL STORE loaders have broad authority and may access files, devices, tokens, or the network. Access performed by a loader is not constrained by the fs.read, fs.write, or net permission scopes.

When a URL is used, format, type, asymmetricKeyType, and namedCurve are ignored even when those options would otherwise depend on each other, such as type with format: 'der' or namedCurve with asymmetricKeyType: 'ec'. The input is passed to the STORE loader as a URI, not handled as PEM, DER, JWK, or raw key material. passphrase is still used as the optional PIN/passphrase passed to the loader, and encoding applies if that passphrase is a string.

Use passphrase instead of embedding credentials in the URI passed to the STORE loader. Node.js redacts the URI from its own permission-denial resource and diagnostics. Errors reported by OpenSSL or a provider after loading begins may include the URI.

When properties is specified with a URL key, it is passed to OpenSSL as the property query for selecting the STORE loader. It is not appended to the URL and is distinct from provider-specific URI parameters.

crypto.createPublicKey(key): KeyObject
Attributes
The key material, either in PEM, DER, JWK, or raw format.
format?:string
Must be 'pem', 'der', 'jwk', or 'raw-public'. Default: 'pem'.
type:string
Must be 'pkcs1' or 'spki'. This option is required only if the format is 'der' and ignored otherwise.
encoding:string
The string encoding to use when key is a string.
asymmetricKeyType:string
Required when format is 'raw-public' and ignored otherwise. Must be a supported key type.
namedCurve:string
Name of the curve to use. Required when asymmetricKeyType is 'ec' and ignored otherwise.
Returns:KeyObject

Creates and returns a new key object containing a public key. If key is a string or Buffer, format is assumed to be 'pem'; if key is a KeyObject with type 'private', the public key is derived from the given private key; otherwise, key must be an object with the properties described above.

If the format is 'pem', the 'key' may also be an X.509 certificate.

Because public keys can be derived from private keys, a private key may be passed instead of a public key. In that case, this function behaves as if crypto.createPrivateKey() had been called, except that the type of the returned KeyObject will be 'public' and that the private key cannot be extracted from the returned KeyObject. Similarly, if a KeyObject with type 'private' is given, a new KeyObject with type 'public' will be returned and it will be impossible to extract the private key from the returned object.

A store-backed private key can be used as a public key by first loading it with crypto.createPrivateKey(); a URL cannot be passed to crypto.createPublicKey() directly.

crypto.createSecretKey(key, encoding?): KeyObject
Attributes
encoding:string
The string encoding when key is a string.
Returns:KeyObject

Creates and returns a new key object containing a secret key for symmetric encryption or Hmac.

M

crypto.createSign

History
crypto.createSign(algorithm, options?): Sign
Attributes
algorithm:string
Returns:Sign

Creates and returns a Sign object that uses the given algorithm. Use crypto.getHashes() to obtain the names of the available digest algorithms. Optional options argument controls the stream.Writable behavior.

In some cases, a Sign instance can be created using the name of a signature algorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use the corresponding digest algorithm. This does not work for all signature algorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest algorithm names.

M

crypto.createVerify

History
crypto.createVerify(algorithm, options?): Verify
Attributes

Creates and returns a Verify object that uses the given algorithm. Use crypto.getHashes() to obtain an array of names of the available signing algorithms. Optional options argument controls the stream.Writable behavior.

In some cases, a Verify instance can be created using the name of a signature algorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use the corresponding digest algorithm. This does not work for all signature algorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest algorithm names.

M

crypto.decapsulate

History
crypto.decapsulate(key, ciphertext, callback?): Buffer
Attributes
callback:Function
err:Error
sharedKey:Buffer
Returns:Buffer
if the callback function is not provided.

Key decapsulation using a KEM algorithm with a private key.

Supported key types and their KEM algorithms are:

  • 'rsa'1 RSA Secret Value Encapsulation
  • 'ec'2 DHKEM(P-256, HKDF-SHA256), DHKEM(P-384, HKDF-SHA256), DHKEM(P-521, HKDF-SHA256)
  • 'x25519'2 DHKEM(X25519, HKDF-SHA256)
  • 'x448'2 DHKEM(X448, HKDF-SHA512)
  • 'ml-kem-512'3 ML-KEM
  • 'ml-kem-768'3 ML-KEM
  • 'ml-kem-1024'3 ML-KEM

If key is not a KeyObject, this function behaves as if key had been passed to crypto.createPrivateKey().

If the callback function is provided this function uses libuv's threadpool.

crypto.diffieHellman(options, callback?): Buffer
Attributes
callback:Function
err:Error
secret:Buffer
Returns:Buffer
if the callback function is not provided.

Computes the Diffie-Hellman shared secret based on a privateKey and a publicKey. Both keys must represent the same asymmetric key type and must support either the DH or ECDH operation.

If options.privateKey is not a KeyObject, this function behaves as if options.privateKey had been passed to crypto.createPrivateKey().

If options.publicKey is not a KeyObject, this function behaves as if options.publicKey had been passed to crypto.createPublicKey().

If the callback function is provided this function uses libuv's threadpool.

M

crypto.encapsulate

History
crypto.encapsulate(key, callback?): Object
Attributes
callback:Function
err:Error
result:Object
sharedKey:Buffer
ciphertext:Buffer
Returns:Object
if the callback function is not provided.
sharedKey:Buffer
ciphertext:Buffer

Key encapsulation using a KEM algorithm with a public key.

Supported key types and their KEM algorithms are:

  • 'rsa'1 RSA Secret Value Encapsulation
  • 'ec'2 DHKEM(P-256, HKDF-SHA256), DHKEM(P-384, HKDF-SHA256), DHKEM(P-521, HKDF-SHA256)
  • 'x25519'2 DHKEM(X25519, HKDF-SHA256)
  • 'x448'2 DHKEM(X448, HKDF-SHA512)
  • 'ml-kem-512'3 ML-KEM
  • 'ml-kem-768'3 ML-KEM
  • 'ml-kem-1024'3 ML-KEM

If key is not a KeyObject, this function behaves as if key had been passed to crypto.createPublicKey().

If the callback function is provided this function uses libuv's threadpool.

P

crypto.fips

History
Stability: 0Deprecated

Deprecated property for checking and controlling FIPS mode. Use crypto.getFips() and crypto.setFips() instead.

crypto.generateKey(type, options, callback): void
Attributes
type:string
The intended use of the generated secret key. Currently accepted values are 'hmac' and 'aes'.
options:Object
length:number
The bit length of the key to generate. This must be a value greater than 0.
callback:Function

Asynchronously generates a new random secret key of the given length. The type will determine which validations will be performed on the length.

const {
  generateKey,
} = await import('node:crypto');

generateKey('hmac', { length: 512 }, (err, key) => {
  if (err) throw err;
  console.log(key.export().toString('hex'));  // 46e..........620
});
const {
  generateKey,
} = require('node:crypto');

generateKey('hmac', { length: 512 }, (err, key) => {
  if (err) throw err;
  console.log(key.export().toString('hex'));  // 46e..........620
});

The size of a generated HMAC key should not exceed the block size of the underlying hash function. See crypto.createHmac() for more information.

crypto.generateKeyPair(type, options, callback): void
Attributes
type:string
The asymmetric key type to generate. See the supported asymmetric key types.
options:Object
modulusLength:number
Key size in bits (RSA, DSA).
publicExponent?:number
Public exponent (RSA). Default: 0x10001.
hashAlgorithm:string
Name of the message digest (RSA-PSS).
mgf1HashAlgorithm:string
Name of the message digest used by MGF1 (RSA-PSS).
saltLength:number
Minimal salt length in bytes (RSA-PSS).
divisorLength:number
Size of q in bits (DSA).
namedCurve:string
Name of the curve to use (EC).
prime:Buffer
The prime parameter (DH).
primeLength:number
Prime length in bits (DH).
generator?:number
Custom generator (DH). Default: 2.
groupName:string
Diffie-Hellman group name (DH). See crypto.getDiffieHellman().
paramEncoding?:string
Must be 'named' or 'explicit' (EC). Default: 'named'.
publicKeyEncoding:Object
privateKeyEncoding:Object
callback:Function
err:Error
publicKey:string | Buffer | KeyObject
privateKey:string | Buffer | KeyObject

Generates a new asymmetric key pair of the given type. See the supported asymmetric key types.

If a publicKeyEncoding or privateKeyEncoding was specified, this function behaves as if keyObject.export() had been called on its result. Otherwise, the respective part of the key is returned as a KeyObject.

It is recommended to encode public keys as 'spki' and private keys as 'pkcs8' with encryption for long-term storage:

const {
  generateKeyPair,
} = await import('node:crypto');

generateKeyPair('rsa', {
  modulusLength: 4096,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem',
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem',
    cipher: 'aes-256-cbc',
    passphrase: 'top secret',
  },
}, (err, publicKey, privateKey) => {
  // Handle errors and use the generated key pair.
});
const {
  generateKeyPair,
} = require('node:crypto');

generateKeyPair('rsa', {
  modulusLength: 4096,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem',
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem',
    cipher: 'aes-256-cbc',
    passphrase: 'top secret',
  },
}, (err, publicKey, privateKey) => {
  // Handle errors and use the generated key pair.
});

On completion, callback will be called with err set to undefined and publicKey / privateKey representing the generated key pair.

If this method is invoked as its util.promisify()ed version, it returns a Promise for an Object with publicKey and privateKey properties.

crypto.generateKeyPairSync(type, options): Object
Attributes
type:string
The asymmetric key type to generate. See the supported asymmetric key types.
options:Object
modulusLength:number
Key size in bits (RSA, DSA).
publicExponent?:number
Public exponent (RSA). Default: 0x10001.
hashAlgorithm:string
Name of the message digest (RSA-PSS).
mgf1HashAlgorithm:string
Name of the message digest used by MGF1 (RSA-PSS).
saltLength:number
Minimal salt length in bytes (RSA-PSS).
divisorLength:number
Size of q in bits (DSA).
namedCurve:string
Name of the curve to use (EC).
prime:Buffer
The prime parameter (DH).
primeLength:number
Prime length in bits (DH).
generator?:number
Custom generator (DH). Default: 2.
groupName:string
Diffie-Hellman group name (DH). See crypto.getDiffieHellman().
paramEncoding?:string
Must be 'named' or 'explicit' (EC). Default: 'named'.
publicKeyEncoding:Object
privateKeyEncoding:Object
Returns:Object
publicKey:string | Buffer | KeyObject
privateKey:string | Buffer | KeyObject

Generates a new asymmetric key pair of the given type. See the supported asymmetric key types.

If a publicKeyEncoding or privateKeyEncoding was specified, this function behaves as if keyObject.export() had been called on its result. Otherwise, the respective part of the key is returned as a KeyObject.

When encoding public keys, it is recommended to use 'spki'. When encoding private keys, it is recommended to use 'pkcs8' with a strong passphrase, and to keep the passphrase confidential.

const {
  generateKeyPairSync,
} = await import('node:crypto');

const {
  publicKey,
  privateKey,
} = generateKeyPairSync('rsa', {
  modulusLength: 4096,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem',
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem',
    cipher: 'aes-256-cbc',
    passphrase: 'top secret',
  },
});
const {
  generateKeyPairSync,
} = require('node:crypto');

const {
  publicKey,
  privateKey,
} = generateKeyPairSync('rsa', {
  modulusLength: 4096,
  publicKeyEncoding: {
    type: 'spki',
    format: 'pem',
  },
  privateKeyEncoding: {
    type: 'pkcs8',
    format: 'pem',
    cipher: 'aes-256-cbc',
    passphrase: 'top secret',
  },
});

The return value { publicKey, privateKey } represents the generated key pair. When PEM encoding was selected, the respective key will be a string, otherwise it will be a buffer containing the data encoded as DER.

M

crypto.generateKeySync

History
crypto.generateKeySync(type, options): KeyObject
Attributes
type:string
The intended use of the generated secret key. Currently accepted values are 'hmac' and 'aes'.
options:Object
length:number
The bit length of the key to generate.
Returns:KeyObject

Synchronously generates a new random secret key of the given length. The type will determine which validations will be performed on the length.

const {
  generateKeySync,
} = await import('node:crypto');

const key = generateKeySync('hmac', { length: 512 });
console.log(key.export().toString('hex'));  // e89..........41e
const {
  generateKeySync,
} = require('node:crypto');

const key = generateKeySync('hmac', { length: 512 });
console.log(key.export().toString('hex'));  // e89..........41e

The size of a generated HMAC key should not exceed the block size of the underlying hash function. See crypto.createHmac() for more information.

crypto.generatePrime(size, options?, callback): void
Attributes
size:number
The size (in bits) of the prime to generate.
options:Object
safe?:boolean
Default: false.
bigint:boolean
When true, the generated prime is returned as a bigint.
callback:Function

Generates a pseudorandom prime of size bits.

If options.safe is true, the prime will be a safe prime -- that is, (prime - 1) / 2 will also be a prime.

The options.add and options.rem parameters can be used to enforce additional requirements, e.g., for Diffie-Hellman:

  • If options.add and options.rem are both set, the prime will satisfy the condition that prime % add = rem.
  • If only options.add is set and options.safe is not true, the prime will satisfy the condition that prime % add = 1.
  • If only options.add is set and options.safe is set to true, the prime will instead satisfy the condition that prime % add = 3. This is necessary because prime % add = 1 for options.add > 2 would contradict the condition enforced by options.safe.
  • options.rem is ignored if options.add is not given.

Both options.add and options.rem must be encoded as big-endian sequences if given as an ArrayBuffer, SharedArrayBuffer, TypedArray, Buffer, or DataView.

By default, the prime is encoded as a big-endian sequence of octets in an ArrayBuffer. If the bigint option is true, then a bigint is provided.

The size of the prime will have a direct impact on how long it takes to generate the prime. The larger the size, the longer it will take. Because we use OpenSSL's BN_generate_prime_ex function, which provides only minimal control over our ability to interrupt the generation process, it is not recommended to generate overly large primes, as doing so may make the process unresponsive.

M

crypto.generatePrimeSync

History
crypto.generatePrimeSync(size, options?): ArrayBuffer | bigint
Attributes
size:number
The size (in bits) of the prime to generate.
options:Object
safe?:boolean
Default: false.
bigint:boolean
When true, the generated prime is returned as a bigint.

Generates a pseudorandom prime of size bits.

If options.safe is true, the prime will be a safe prime -- that is, (prime - 1) / 2 will also be a prime.

The options.add and options.rem parameters can be used to enforce additional requirements, e.g., for Diffie-Hellman:

  • If options.add and options.rem are both set, the prime will satisfy the condition that prime % add = rem.
  • If only options.add is set and options.safe is not true, the prime will satisfy the condition that prime % add = 1.
  • If only options.add is set and options.safe is set to true, the prime will instead satisfy the condition that prime % add = 3. This is necessary because prime % add = 1 for options.add > 2 would contradict the condition enforced by options.safe.
  • options.rem is ignored if options.add is not given.

Both options.add and options.rem must be encoded as big-endian sequences if given as an ArrayBuffer, SharedArrayBuffer, TypedArray, Buffer, or DataView.

By default, the prime is encoded as a big-endian sequence of octets in an ArrayBuffer. If the bigint option is true, then a bigint is provided.

The size of the prime will have a direct impact on how long it takes to generate the prime. The larger the size, the longer it will take. Because we use OpenSSL's BN_generate_prime_ex function, which provides only minimal control over our ability to interrupt the generation process, it is not recommended to generate overly large primes, as doing so may make the process unresponsive.

M

crypto.getCipherInfo

History
crypto.getCipherInfo(nameOrNid, options?): Object
Attributes
nameOrNid:string | number
The name or nid of the cipher to query.
options:Object
keyLength:number
A test key length.
ivLength:number
A test IV length.
Returns:Object
name:string
The name of the cipher
The nid of the cipher. This property is undefined if the cipher has no OpenSSL nid.
blockSize:number | undefined
The block size of the cipher in bytes. This property is undefined when mode is 'stream'.
ivLength:number | undefined
The expected or default initialization vector length in bytes. This property is undefined if the cipher does not use an initialization vector.
keyLength:number
The expected or default key length in bytes.
mode:string
The cipher mode. One of 'cbc', 'ccm', 'cfb', 'ctr', 'ecb', 'gcm', 'gcm-siv', 'ocb', 'ofb', 'siv', 'stream', 'wrap', 'xts'.

Returns information about a given cipher.

Some ciphers accept variable length keys and initialization vectors. By default, the crypto.getCipherInfo() method will return the default values for these ciphers. To test if a given key length or iv length is acceptable for given cipher, use the keyLength and ivLength options. If the given values are unacceptable, undefined will be returned.

M

crypto.getCiphers

History
crypto.getCiphers(): string[]
Returns:string[]
An array with the names of the supported cipher algorithms.
const {
  getCiphers,
} = await import('node:crypto');

console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
const {
  getCiphers,
} = require('node:crypto');

console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
M

crypto.getCurves

History
crypto.getCurves(): string[]
Returns:string[]
An array with the names of the supported elliptic curves.
const {
  getCurves,
} = await import('node:crypto');

console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
const {
  getCurves,
} = require('node:crypto');

console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
M

crypto.getDiffieHellman

History
crypto.getDiffieHellman(groupName): DiffieHellmanGroup
Attributes
groupName:string

Creates a predefined DiffieHellmanGroup key exchange object. The supported groups are listed in the documentation for DiffieHellmanGroup.

The returned object mimics the interface of objects created by crypto.createDiffieHellman(), but will not allow changing the keys (with diffieHellman.setPublicKey(), for example). The advantage of using this method is that the parties do not have to generate nor exchange a group modulus beforehand, saving both processor and communication time.

Example (obtaining a shared secret):

const {
  getDiffieHellman,
} = await import('node:crypto');
const alice = getDiffieHellman('modp14');
const bob = getDiffieHellman('modp14');

alice.generateKeys();
bob.generateKeys();

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

/* aliceSecret and bobSecret should be the same */
console.log(aliceSecret === bobSecret);
const {
  getDiffieHellman,
} = require('node:crypto');

const alice = getDiffieHellman('modp14');
const bob = getDiffieHellman('modp14');

alice.generateKeys();
bob.generateKeys();

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

/* aliceSecret and bobSecret should be the same */
console.log(aliceSecret === bobSecret);
M

crypto.getFips

History
crypto.getFips(): number
Returns:number
1 if FIPS mode is enabled, 0 otherwise. A future semver-major release may change the return type of this API to a boolean.

With OpenSSL 3, this reports whether the default property query includes fips=yes. It does not establish that a FIPS provider is loaded or validated. It can return 1 even when a requested cryptographic implementation cannot be fetched because no loaded provider supplies a match for fips=yes. See FIPS mode.

M

crypto.getHashes

History
crypto.getHashes(): string[]
Returns:string[]
An array of the names of the supported hash algorithms, such as 'RSA-SHA256'. Hash algorithms are also called "digest" algorithms.
const {
  getHashes,
} = await import('node:crypto');

console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
const {
  getHashes,
} = require('node:crypto');

console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
M

crypto.getRandomValues

History
crypto.getRandomValues(typedArray): Buffer | TypedArray | DataView | ArrayBuffer
Attributes
Returns typedArray.

A convenient alias for crypto.webcrypto.getRandomValues(). This implementation is not compliant with the Web Crypto spec, to write web-compatible code use crypto.webcrypto.getRandomValues() instead.

crypto.hash(algorithm, data, options?): string | Buffer
Attributes
algorithm:string | undefined
When data is a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user could encode the string into a TypedArray using either TextEncoder or Buffer.from() and passing the encoded TypedArray into this API instead.
options:Object | string
outputEncoding?:string
Encoding used to encode the returned digest. Default: 'hex'.
outputLength:number
For XOF hash functions such as 'shake256', the outputLength option can be used to specify the desired output length in bytes.
Returns:string | Buffer

A utility for creating one-shot hash digests of data. It can be faster than the object-based crypto.createHash() when hashing a smaller amount of data (<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use crypto.createHash() instead.

The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. On recent releases of OpenSSL, openssl list -digest-algorithms will display the available digest algorithms.

If options is a string, then it specifies the outputEncoding.

Example:

const crypto = require('node:crypto');
const { Buffer } = require('node:buffer');

// Hashing a string and return the result as a hex-encoded string.
const string = 'Node.js';
// 10b3493287f831e81a438811a1ffba01f8cec4b7
console.log(crypto.hash('sha1', string));

// Encode a base64-encoded string into a Buffer, hash it and return
// the result as a buffer.
const base64 = 'Tm9kZS5qcw==';
// <Buffer 10 b3 49 32 87 f8 31 e8 1a 43 88 11 a1 ff ba 01 f8 ce c4 b7>
console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer'));
import crypto from 'node:crypto';
import { Buffer } from 'node:buffer';

// Hashing a string and return the result as a hex-encoded string.
const string = 'Node.js';
// 10b3493287f831e81a438811a1ffba01f8cec4b7
console.log(crypto.hash('sha1', string));

// Encode a base64-encoded string into a Buffer, hash it and return
// the result as a buffer.
const base64 = 'Tm9kZS5qcw==';
// <Buffer 10 b3 49 32 87 f8 31 e8 1a 43 88 11 a1 ff ba 01 f8 ce c4 b7>
console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer'));
crypto.hkdf(digest, ikm, salt, info, keylen, callback): void
Attributes
digest:string
The digest algorithm to use.
The input keying material. Must be provided but can be zero-length.
The salt value. Must be provided but can be zero-length.
Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.
keylen:number
The length of the key to generate. Must be greater than 0. The maximum allowable value is 255 times the number of bytes produced by the selected digest function (e.g. sha512 generates 64-byte hashes, making the maximum HKDF output 16320 bytes).
callback:Function
err:Error
derivedKey:ArrayBuffer

HKDF is a simple key derivation function defined in RFC 5869. The given ikm, salt and info are used with the digest to derive a key of keylen bytes.

The supplied callback function is called with two arguments: err and derivedKey. If an error occurs while deriving the key, err will be set; otherwise err will be null. The successfully generated derivedKey will be passed to the callback as an ArrayBuffer. An error will be thrown if any of the input arguments specify invalid values or types.

import { Buffer } from 'node:buffer';
const {
  hkdf,
} = await import('node:crypto');

hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
  if (err) throw err;
  console.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'
});
const {
  hkdf,
} = require('node:crypto');
const { Buffer } = require('node:buffer');

hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
  if (err) throw err;
  console.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'
});
crypto.hkdfSync(digest, ikm, salt, info, keylen): ArrayBuffer
Attributes
digest:string
The digest algorithm to use.
The input keying material. Must be provided but can be zero-length.
The salt value. Must be provided but can be zero-length.
Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.
keylen:number
The length of the key to generate. Must be greater than 0. The maximum allowable value is 255 times the number of bytes produced by the selected digest function (e.g. sha512 generates 64-byte hashes, making the maximum HKDF output 16320 bytes).
Returns:ArrayBuffer

Provides a synchronous HKDF key derivation function as defined in RFC 5869. The given ikm, salt and info are used with the digest to derive a key of keylen bytes.

The successfully generated derivedKey will be returned as an ArrayBuffer.

An error will be thrown if any of the input arguments specify invalid values or types, or if the derived key cannot be generated.

import { Buffer } from 'node:buffer';
const {
  hkdfSync,
} = await import('node:crypto');

const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
console.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'
const {
  hkdfSync,
} = require('node:crypto');
const { Buffer } = require('node:buffer');

const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
console.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'
crypto.pbkdf2(password, salt, iterations, keylen, digest, callback): void
Attributes
iterations:number
keylen:number
digest:string
callback:Function
err:Error
derivedKey:Buffer

Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) implementation. A selected HMAC digest algorithm specified by digest is applied to derive a key of the requested byte length (keylen) from the password, salt and iterations.

The supplied callback function is called with two arguments: err and derivedKey. If an error occurs while deriving the key, err will be set; otherwise err will be null. By default, the successfully generated derivedKey will be passed to the callback as a Buffer. An error will be thrown if any of the input arguments specify invalid values or types.

The iterations argument must be a number set as high as possible. The higher the number of iterations, the more secure the derived key will be, but will take a longer amount of time to complete.

The salt should be as unique as possible. It is recommended that a salt is random and at least 16 bytes long. See NIST SP 800-132 for details.

When passing strings for password or salt, please consider caveats when using strings as inputs to cryptographic APIs.

const {
  pbkdf2,
} = await import('node:crypto');

pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
});
const {
  pbkdf2,
} = require('node:crypto');

pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
});

An array of supported digest functions can be retrieved using crypto.getHashes().

This API uses libuv's threadpool, which can have surprising and negative performance implications for some applications; see the UV_THREADPOOL_SIZE documentation for more information.

crypto.pbkdf2Sync(password, salt, iterations, keylen, digest): Buffer
Attributes
iterations:number
keylen:number
digest:string
Returns:Buffer

Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) implementation. A selected HMAC digest algorithm specified by digest is applied to derive a key of the requested byte length (keylen) from the password, salt and iterations.

If an error occurs an Error will be thrown, otherwise the derived key will be returned as a Buffer.

The iterations argument must be a number set as high as possible. The higher the number of iterations, the more secure the derived key will be, but will take a longer amount of time to complete.

The salt should be as unique as possible. It is recommended that a salt is random and at least 16 bytes long. See NIST SP 800-132 for details.

When passing strings for password or salt, please consider caveats when using strings as inputs to cryptographic APIs.

const {
  pbkdf2Sync,
} = await import('node:crypto');

const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
console.log(key.toString('hex'));  // '3745e48...08d59ae'
const {
  pbkdf2Sync,
} = require('node:crypto');

const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
console.log(key.toString('hex'));  // '3745e48...08d59ae'

An array of supported digest functions can be retrieved using crypto.getHashes().

crypto.privateDecrypt(privateKey, buffer): Buffer
Attributes
oaepHash?:string
The hash function to use for OAEP padding and, unless mgf1Hash is set, MGF1. Default: 'sha1'
mgf1Hash:string
The hash function to use for the MGF1 mask generation function of OAEP padding. If not specified, the value of oaepHash is used. This allows the OAEP digest and the MGF1 digest to differ.
The label to use for OAEP padding. If not specified, no label is used.
An optional padding value defined in crypto.constants, which may be: crypto.constants.RSA_NO_PADDING, crypto.constants.RSA_PKCS1_PADDING, or crypto.constants.RSA_PKCS1_OAEP_PADDING.
Returns:Buffer
A new Buffer with the decrypted content.

Decrypts buffer with privateKey. buffer was previously encrypted using the corresponding public key, for example using crypto.publicEncrypt().

If privateKey is not a KeyObject, this function behaves as if privateKey had been passed to crypto.createPrivateKey(). If it is an object, the padding property can be passed. Otherwise, this function uses RSA_PKCS1_OAEP_PADDING.

Using crypto.constants.RSA_PKCS1_PADDING in crypto.privateDecrypt() requires OpenSSL to support implicit rejection (rsa_pkcs1_implicit_rejection). If the version of OpenSSL used by Node.js does not support this feature, attempting to use RSA_PKCS1_PADDING will fail.

crypto.privateEncrypt(privateKey, buffer): Buffer
Attributes
The private key material, a KeyObject, or a URL referencing an object for an OpenSSL STORE loader.
An optional passphrase for the private key.
An optional padding value defined in crypto.constants, which may be: crypto.constants.RSA_NO_PADDING or crypto.constants.RSA_PKCS1_PADDING.
encoding:string
The string encoding to use when buffer, key, or passphrase are strings.
Returns:Buffer
A new Buffer with the encrypted content.

Encrypts buffer with privateKey. The returned data can be decrypted using the corresponding public key, for example using crypto.publicDecrypt().

If privateKey is not a KeyObject, this function behaves as if privateKey had been passed to crypto.createPrivateKey(). If it is an object, the padding property can be passed. Otherwise, this function uses RSA_PKCS1_PADDING.

crypto.publicDecrypt(key, buffer): Buffer
Attributes
An optional passphrase for the private key.
An optional padding value defined in crypto.constants, which may be: crypto.constants.RSA_NO_PADDING or crypto.constants.RSA_PKCS1_PADDING.
encoding:string
The string encoding to use when buffer, key, or passphrase are strings.
Returns:Buffer
A new Buffer with the decrypted content.

Decrypts buffer with key. buffer was previously encrypted using the corresponding private key, for example using crypto.privateEncrypt().

If key is not a KeyObject, this function behaves as if key had been passed to crypto.createPublicKey(). If it is an object, the padding property can be passed. Otherwise, this function uses RSA_PKCS1_PADDING.

Because RSA public keys can be derived from private keys, a private key may be passed instead of a public key.

crypto.publicEncrypt(key, buffer): Buffer
Attributes
A PEM encoded public or private key, KeyObject, or CryptoKey.
oaepHash?:string
The hash function to use for OAEP padding and, unless mgf1Hash is set, MGF1. Default: 'sha1'
mgf1Hash:string
The hash function to use for the MGF1 mask generation function of OAEP padding. If not specified, the value of oaepHash is used. This allows the OAEP digest and the MGF1 digest to differ.
The label to use for OAEP padding. If not specified, no label is used.
An optional passphrase for the private key.
An optional padding value defined in crypto.constants, which may be: crypto.constants.RSA_NO_PADDING, crypto.constants.RSA_PKCS1_PADDING, or crypto.constants.RSA_PKCS1_OAEP_PADDING.
encoding:string
The string encoding to use when buffer, key, oaepLabel, or passphrase are strings.
Returns:Buffer
A new Buffer with the encrypted content.

Encrypts the content of buffer with key and returns a new Buffer with encrypted content. The returned data can be decrypted using the corresponding private key, for example using crypto.privateDecrypt().

If key is not a KeyObject, this function behaves as if key had been passed to crypto.createPublicKey(). If it is an object, the padding property can be passed. Otherwise, this function uses RSA_PKCS1_OAEP_PADDING.

Because RSA public keys can be derived from private keys, a private key may be passed instead of a public key.

crypto.randomBytes(size, callback?): Buffer
Attributes
size:number
The number of bytes to generate. The size must not be larger than 2**31 - 1.
callback:Function
err:Error
buf:Buffer
Returns:Buffer
if the callback function is not provided.

Generates cryptographically strong pseudorandom data. The size argument is a number indicating the number of bytes to generate.

If a callback function is provided, the bytes are generated asynchronously and the callback function is invoked with two arguments: err and buf. If an error occurs, err will be an Error object; otherwise it is null. The buf argument is a Buffer containing the generated bytes.

// Asynchronous
const {
  randomBytes,
} = await import('node:crypto');

randomBytes(256, (err, buf) => {
  if (err) throw err;
  console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});
// Asynchronous
const {
  randomBytes,
} = require('node:crypto');

randomBytes(256, (err, buf) => {
  if (err) throw err;
  console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
});

If the callback function is not provided, the random bytes are generated synchronously and returned as a Buffer. An error will be thrown if there is a problem generating the bytes.

// Synchronous
const {
  randomBytes,
} = await import('node:crypto');

const buf = randomBytes(256);
console.log(
  `${buf.length} bytes of random data: ${buf.toString('hex')}`);
// Synchronous
const {
  randomBytes,
} = require('node:crypto');

const buf = randomBytes(256);
console.log(
  `${buf.length} bytes of random data: ${buf.toString('hex')}`);

The crypto.randomBytes() method will not complete until there is sufficient entropy available. This should normally never take longer than a few milliseconds. The only time when generating the random bytes may conceivably block for a longer period of time is right after boot, when the whole system is still low on entropy.

This API uses libuv's threadpool, which can have surprising and negative performance implications for some applications; see the UV_THREADPOOL_SIZE documentation for more information.

The asynchronous version of crypto.randomBytes() is carried out in a single threadpool request. To minimize threadpool task length variation, partition large randomBytes requests when doing so as part of fulfilling a client request.

crypto.randomFill(buffer, offset?, size?, callback): void
Attributes
Must be supplied. The size of the provided buffer must not be larger than 2**31 - 1.
offset?:number
The start position, in elements for a TypedArray and in bytes for an ArrayBuffer or DataView. Default: 0
size?:number
The amount to fill, in the same units as offset. Default: buffer.length - offset for a TypedArray, or buffer.byteLength - offset for an ArrayBuffer or DataView. The size must not be larger than 2**31 - 1.
callback:Function
function(err, buf) {}.

This function is similar to crypto.randomBytes() but requires the first argument to be a Buffer that will be filled. It also requires that a callback is passed in.

If the callback function is not provided, an error will be thrown.

import { Buffer } from 'node:buffer';
const { randomFill } = await import('node:crypto');

const buf = Buffer.alloc(10);
randomFill(buf, (err, buf) => {
  if (err) throw err;
  console.log(buf.toString('hex'));
});

randomFill(buf, 5, (err, buf) => {
  if (err) throw err;
  console.log(buf.toString('hex'));
});

// The above is equivalent to the following:
randomFill(buf, 5, 5, (err, buf) => {
  if (err) throw err;
  console.log(buf.toString('hex'));
});
const { randomFill } = require('node:crypto');
const { Buffer } = require('node:buffer');

const buf = Buffer.alloc(10);
randomFill(buf, (err, buf) => {
  if (err) throw err;
  console.log(buf.toString('hex'));
});

randomFill(buf, 5, (err, buf) => {
  if (err) throw err;
  console.log(buf.toString('hex'));
});

// The above is equivalent to the following:
randomFill(buf, 5, 5, (err, buf) => {
  if (err) throw err;
  console.log(buf.toString('hex'));
});

Any ArrayBuffer, TypedArray, or DataView instance may be passed as buffer.

While this includes instances of Float32Array and Float64Array, this function should not be used to generate random floating-point numbers. The result may contain +Infinity, -Infinity, and NaN, and even if the array contains finite numbers only, they are not drawn from a uniform random distribution and have no meaningful lower or upper bounds.

import { Buffer } from 'node:buffer';
const { randomFill } = await import('node:crypto');

const a = new Uint32Array(10);
randomFill(a, (err, buf) => {
  if (err) throw err;
  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
    .toString('hex'));
});

const b = new DataView(new ArrayBuffer(10));
randomFill(b, (err, buf) => {
  if (err) throw err;
  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
    .toString('hex'));
});

const c = new ArrayBuffer(10);
randomFill(c, (err, buf) => {
  if (err) throw err;
  console.log(Buffer.from(buf).toString('hex'));
});
const { randomFill } = require('node:crypto');
const { Buffer } = require('node:buffer');

const a = new Uint32Array(10);
randomFill(a, (err, buf) => {
  if (err) throw err;
  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
    .toString('hex'));
});

const b = new DataView(new ArrayBuffer(10));
randomFill(b, (err, buf) => {
  if (err) throw err;
  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
    .toString('hex'));
});

const c = new ArrayBuffer(10);
randomFill(c, (err, buf) => {
  if (err) throw err;
  console.log(Buffer.from(buf).toString('hex'));
});

This API uses libuv's threadpool, which can have surprising and negative performance implications for some applications; see the UV_THREADPOOL_SIZE documentation for more information.

The asynchronous version of crypto.randomFill() is carried out in a single threadpool request. To minimize threadpool task length variation, partition large randomFill requests when doing so as part of fulfilling a client request.

crypto.randomFillSync(buffer, offset?, size?): ArrayBuffer | Buffer | TypedArray | DataView
Attributes
Must be supplied. The size of the provided buffer must not be larger than 2**31 - 1.
offset?:number
The start position, in elements for a TypedArray and in bytes for an ArrayBuffer or DataView. Default: 0
size?:number
The amount to fill, in the same units as offset. Default: buffer.length - offset for a TypedArray, or buffer.byteLength - offset for an ArrayBuffer or DataView. The size must not be larger than 2**31 - 1.
The object passed as buffer argument.

Synchronous version of crypto.randomFill().

import { Buffer } from 'node:buffer';
const { randomFillSync } = await import('node:crypto');

const buf = Buffer.alloc(10);
console.log(randomFillSync(buf).toString('hex'));

randomFillSync(buf, 5);
console.log(buf.toString('hex'));

// The above is equivalent to the following:
randomFillSync(buf, 5, 5);
console.log(buf.toString('hex'));
const { randomFillSync } = require('node:crypto');
const { Buffer } = require('node:buffer');

const buf = Buffer.alloc(10);
console.log(randomFillSync(buf).toString('hex'));

randomFillSync(buf, 5);
console.log(buf.toString('hex'));

// The above is equivalent to the following:
randomFillSync(buf, 5, 5);
console.log(buf.toString('hex'));

Any ArrayBuffer, TypedArray or DataView instance may be passed as buffer.

import { Buffer } from 'node:buffer';
const { randomFillSync } = await import('node:crypto');

const a = new Uint32Array(10);
console.log(Buffer.from(randomFillSync(a).buffer,
                        a.byteOffset, a.byteLength).toString('hex'));

const b = new DataView(new ArrayBuffer(10));
console.log(Buffer.from(randomFillSync(b).buffer,
                        b.byteOffset, b.byteLength).toString('hex'));

const c = new ArrayBuffer(10);
console.log(Buffer.from(randomFillSync(c)).toString('hex'));
const { randomFillSync } = require('node:crypto');
const { Buffer } = require('node:buffer');

const a = new Uint32Array(10);
console.log(Buffer.from(randomFillSync(a).buffer,
                        a.byteOffset, a.byteLength).toString('hex'));

const b = new DataView(new ArrayBuffer(10));
console.log(Buffer.from(randomFillSync(b).buffer,
                        b.byteOffset, b.byteLength).toString('hex'));

const c = new ArrayBuffer(10);
console.log(Buffer.from(randomFillSync(c)).toString('hex'));
crypto.randomInt(min?, max, callback?): void
Attributes
min?:integer
Start of random range (inclusive). Default: 0.
End of random range (exclusive).
callback:Function
function(err, n) {}.

Return a random integer n such that min <= n < max. This implementation avoids modulo bias.

The range (max - min) must be less than 248. min and max must be safe integers.

If the callback function is not provided, the random integer is generated synchronously.

// Asynchronous
const {
  randomInt,
} = await import('node:crypto');

randomInt(3, (err, n) => {
  if (err) throw err;
  console.log(`Random number chosen from (0, 1, 2): ${n}`);
});
// Asynchronous
const {
  randomInt,
} = require('node:crypto');

randomInt(3, (err, n) => {
  if (err) throw err;
  console.log(`Random number chosen from (0, 1, 2): ${n}`);
});
// Synchronous
const {
  randomInt,
} = await import('node:crypto');

const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);
// Synchronous
const {
  randomInt,
} = require('node:crypto');

const n = randomInt(3);
console.log(`Random number chosen from (0, 1, 2): ${n}`);
// With `min` argument
const {
  randomInt,
} = await import('node:crypto');

const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);
// With `min` argument
const {
  randomInt,
} = require('node:crypto');

const n = randomInt(1, 7);
console.log(`The dice rolled: ${n}`);
M

crypto.randomUUID

History
crypto.randomUUID(options?): string
Attributes
options:Object
disableEntropyCache?:boolean
By default, to improve performance, Node.js generates and caches enough random data to generate up to 128 random UUIDs. To generate a UUID without using the cache, set disableEntropyCache to true. Default: false.
Returns:string

Generates a random RFC 4122 version 4 UUID. The UUID is generated using a cryptographic pseudorandom number generator.

M

crypto.randomUUIDv7

History
crypto.randomUUIDv7(options?): string
Attributes
options:Object
disableEntropyCache?:boolean
By default, to improve performance, Node.js generates and caches enough random data to generate up to 128 random UUIDs. To generate a UUID without using the cache, set disableEntropyCache to true. Default: false.
Returns:string

Generates a random RFC 9562 version 7 UUID. The UUID contains a millisecond precision Unix timestamp in the most significant 48 bits, followed by cryptographically secure random bits for the remaining fields, making it suitable for use as a database key with time-based sorting. The embedded timestamp relies on a non-monotonic clock and is not guaranteed to be strictly increasing.

crypto.scrypt(password, salt, keylen, options?, callback): void
Attributes
keylen:number
options:Object
cost?:number
CPU/memory cost parameter. Must be a power of two greater than one. Default: 16384.
blockSize?:number
Block size parameter. Default: 8.
parallelization?:number
Parallelization parameter. Default: 1.
Alias for cost. Only one of both may be specified.
Alias for blockSize. Only one of both may be specified.
Alias for parallelization. Only one of both may be specified.
maxmem?:number
Memory upper bound. It is an error when (approximately) 128 * N * r > maxmem. Default: 32 * 1024 * 1024.
callback:Function
err:Error
derivedKey:Buffer

Provides an asynchronous scrypt implementation. Scrypt is a password-based key derivation function that is designed to be expensive computationally and memory-wise in order to make brute-force attacks unrewarding.

The salt should be as unique as possible. It is recommended that a salt is random and at least 16 bytes long. See NIST SP 800-132 for details.

When passing strings for password or salt, please consider caveats when using strings as inputs to cryptographic APIs.

The callback function is called with two arguments: err and derivedKey. err is an exception object when key derivation fails, otherwise err is null. derivedKey is passed to the callback as a Buffer.

An exception is thrown when any of the input arguments specify invalid values or types.

const {
  scrypt,
} = await import('node:crypto');

// Using the factory defaults.
scrypt('password', 'salt', 64, (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
});
// Using a custom N parameter. Must be a power of two.
scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));  // '3745e48...aa39b34'
});
const {
  scrypt,
} = require('node:crypto');

// Using the factory defaults.
scrypt('password', 'salt', 64, (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
});
// Using a custom N parameter. Must be a power of two.
scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
  if (err) throw err;
  console.log(derivedKey.toString('hex'));  // '3745e48...aa39b34'
});
crypto.scryptSync(password, salt, keylen, options?): Buffer
Attributes
keylen:number
options:Object
cost?:number
CPU/memory cost parameter. Must be a power of two greater than one. Default: 16384.
blockSize?:number
Block size parameter. Default: 8.
parallelization?:number
Parallelization parameter. Default: 1.
Alias for cost. Only one of both may be specified.
Alias for blockSize. Only one of both may be specified.
Alias for parallelization. Only one of both may be specified.
maxmem?:number
Memory upper bound. It is an error when (approximately) 128 * N * r > maxmem. Default: 32 * 1024 * 1024.
Returns:Buffer

Provides a synchronous scrypt implementation. Scrypt is a password-based key derivation function that is designed to be expensive computationally and memory-wise in order to make brute-force attacks unrewarding.

The salt should be as unique as possible. It is recommended that a salt is random and at least 16 bytes long. See NIST SP 800-132 for details.

When passing strings for password or salt, please consider caveats when using strings as inputs to cryptographic APIs.

An exception is thrown when key derivation fails, otherwise the derived key is returned as a Buffer.

An exception is thrown when any of the input arguments specify invalid values or types.

const {
  scryptSync,
} = await import('node:crypto');
// Using the factory defaults.

const key1 = scryptSync('password', 'salt', 64);
console.log(key1.toString('hex'));  // '3745e48...08d59ae'
// Using a custom N parameter. Must be a power of two.
const key2 = scryptSync('password', 'salt', 64, { N: 1024 });
console.log(key2.toString('hex'));  // '3745e48...aa39b34'
const {
  scryptSync,
} = require('node:crypto');
// Using the factory defaults.

const key1 = scryptSync('password', 'salt', 64);
console.log(key1.toString('hex'));  // '3745e48...08d59ae'
// Using a custom N parameter. Must be a power of two.
const key2 = scryptSync('password', 'salt', 64, { N: 1024 });
console.log(key2.toString('hex'));  // '3745e48...aa39b34'
M

crypto.secureHeapUsed

History
crypto.secureHeapUsed(): Object
Returns:Object
total:number
The total allocated secure heap size as specified using the --secure-heap=n command-line flag.
min:number
The minimum allocation from the secure heap as specified using the --secure-heap-min command-line flag.
used:number
The total number of bytes currently allocated from the secure heap.
utilization:number
The calculated ratio of used to total allocated bytes.
crypto.setEngine(engine, flags?): void
Attributes
engine:string
Default: crypto.constants.ENGINE_METHOD_ALL

Load and set the engine for some or all OpenSSL functions (selected by flags). Support for custom engines in OpenSSL is deprecated from OpenSSL 3.

engine could be either an id or a path to the engine's shared library.

The optional flags argument uses ENGINE_METHOD_ALL by default. The flags is a bit field taking one of or a mix of the following flags (defined in crypto.constants):

  • crypto.constants.ENGINE_METHOD_RSA
  • crypto.constants.ENGINE_METHOD_DSA
  • crypto.constants.ENGINE_METHOD_DH
  • crypto.constants.ENGINE_METHOD_RAND
  • crypto.constants.ENGINE_METHOD_EC
  • crypto.constants.ENGINE_METHOD_CIPHERS
  • crypto.constants.ENGINE_METHOD_DIGESTS
  • crypto.constants.ENGINE_METHOD_PKEY_METHS
  • crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS
  • crypto.constants.ENGINE_METHOD_ALL
  • crypto.constants.ENGINE_METHOD_NONE
M

crypto.setFips

History
crypto.setFips(bool): void
Attributes
bool:boolean
true to enable FIPS mode, false to disable it.

Changes FIPS mode. With OpenSSL 3, this only adds or removes fips=yes in the default property query. It does not install, load, initialize, or validate a FIPS provider. For a usable FIPS configuration, install the provider and configure OpenSSL to load it when Node.js starts, as described in FIPS mode.

If no loaded provider supplies a requested cryptographic implementation matching fips=yes, the call can still succeed and crypto.getFips() can still return 1, but fetching that implementation fails. Affected node:crypto operations typically fail with ERR_OSSL_EVP_UNSUPPORTED. Operations that do not require a new fetch, including those using previously fetched implementations or initialized operation contexts, may still succeed. Call this method during application initialization, before application code uses other OpenSSL-backed APIs.

This method only affects subsequent algorithm fetches. Node.js initializes some OpenSSL state before application code runs. When the property query must be active from process startup, set default_properties = fips=yes in the OpenSSL configuration or use --enable-fips or --force-fips. The command-line flags additionally require a configured provider named fips to initialize and pass its self-test; Node.js fails to start otherwise.

Throws an error if OpenSSL cannot change the state. FIPS mode cannot be disabled when Node.js was started with --force-fips. With OpenSSL 1.1.1, enabling FIPS mode requires a FIPS-capable OpenSSL build.

crypto.sign(algorithm, data, key, callback?): Buffer
Attributes
algorithm:string | null | undefined
callback:Function
err:Error
signature:Buffer
Returns:Buffer
if the callback function is not provided.

Calculates and returns the signature for data using the given private key and algorithm. If algorithm is null or undefined, then the algorithm is dependent upon the key type.

algorithm is required to be null or undefined for Ed25519, Ed448, and ML-DSA.

If key is not a KeyObject, this function behaves as if key had been passed to crypto.createPrivateKey(). When key is a string, ArrayBuffer, Buffer, TypedArray, or DataView, it must contain PEM-encoded key material. If it is an object, the following additional properties can be passed:

Attributes
dsaEncoding:string
For DSA and ECDSA, this option specifies the format of the generated signature. It can be one of the following:
'der':
(default): DER-encoded ASN.1 signature structure encoding (r, s).
'ieee-p1363':
Signature format r || s as proposed in IEEE-P1363.
padding:integer
Optional padding value for RSA, one of the following:
crypto.constants.RSA_PKCS1_PADDING:
(default)
crypto.constants.RSA_PKCS1_PSS_PADDING:
saltLength:integer
Salt length for when padding is RSA_PKCS1_PSS_PADDING. The special value crypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest size, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the maximum permissible value.
For Ed255191 (using Ed25519ctx from RFC 8032), Ed448, ML-DSA, and SLH-DSA, this option specifies the optional context to differentiate signatures generated for different purposes with the same key.

If the callback function is provided this function uses libuv's threadpool.

P

crypto.subtle

History

A convenient alias for crypto.webcrypto.subtle.

crypto.timingSafeEqual(a, b): boolean
Attributes

This function compares the underlying bytes that represent the given ArrayBuffer, TypedArray, or DataView instances using a constant-time algorithm.

This function does not leak timing information that would allow an attacker to guess one of the values. This is suitable for comparing HMAC digests or secret values like authentication cookies or capability urls.

a and b must both be Buffers, TypedArrays, or DataViews, and they must have the same byte length. An error is thrown if a and b have different byte lengths.

If at least one of a and b is a TypedArray with more than one byte per entry, such as Uint16Array, the result will be computed using the platform byte order.

When both of the inputs are Float32Arrays or Float64Arrays, this function might return unexpected results due to IEEE 754 encoding of floating-point numbers. In particular, neither x === y nor Object.is(x, y) implies that the byte representations of two floating-point numbers x and y are equal.

Use of crypto.timingSafeEqual does not guarantee that the surrounding code is timing-safe. Care should be taken to ensure that the surrounding code does not introduce timing vulnerabilities.

crypto.verify(algorithm, data, key, signature, callback?): boolean
Attributes
algorithm:string | null | undefined
callback:Function
err:Error
result:boolean
Returns:boolean
true or false depending on the validity of the signature for the data and public key if the callback function is not provided.

Verifies the given signature for data using the given key and algorithm. If algorithm is null or undefined, then the algorithm is dependent upon the key type.

algorithm is required to be null or undefined for Ed25519, Ed448, and ML-DSA.

If key is not a KeyObject, this function behaves as if key had been passed to crypto.createPublicKey(). When key is a string, ArrayBuffer, Buffer, TypedArray, or DataView, it must contain PEM-encoded key material. If it is an object, the following additional properties can be passed:

Attributes
dsaEncoding:string
For DSA and ECDSA, this option specifies the format of the signature. It can be one of the following:
'der':
(default): DER-encoded ASN.1 signature structure encoding (r, s).
'ieee-p1363':
Signature format r || s as proposed in IEEE-P1363.
padding:integer
Optional padding value for RSA, one of the following:
crypto.constants.RSA_PKCS1_PADDING:
(default)
crypto.constants.RSA_PKCS1_PSS_PADDING:
saltLength:integer
Salt length for when padding is RSA_PKCS1_PSS_PADDING. The special value crypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest size, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the maximum permissible value.
For Ed255191 (using Ed25519ctx from RFC 8032), Ed448, ML-DSA, and SLH-DSA, this option specifies the optional context to differentiate signatures generated for different purposes with the same key.

The signature argument is the previously calculated signature for the data.

Because public keys can be derived from private keys, a private key or a public key may be passed for key.

If the callback function is provided this function uses libuv's threadpool.

P

crypto.webcrypto

History

Type: Crypto An implementation of the Web Crypto API standard.

See the Web Crypto API documentation for details.