node:crypto module methods and properties
History
crypto.argon2(algorithm, parameters, callback): void
string"argon2d", "argon2i" or "argon2id".Objectstring | ArrayBuffer | Buffer | TypedArray | DataViewstring | ArrayBuffer | Buffer | TypedArray | DataViewnumber1 and at most 2**24-1.number4 and
at most 2**32-1.number8 * parallelism and at most 2**32-1. The actual number of blocks is rounded
down to the nearest multiple of 4 * parallelism.number1 and at most
2**32-1.string | ArrayBuffer | Buffer | TypedArray | DataView | undefined2**32-1 bytes.string | ArrayBuffer | Buffer | TypedArray | DataView | undefined2**32-1 bytes.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' });
crypto.argon2Sync(algorithm, parameters): Buffer
string"argon2d", "argon2i" or "argon2id".Objectstring | ArrayBuffer | Buffer | TypedArray | DataViewstring | ArrayBuffer | Buffer | TypedArray | DataViewnumber2**24-1.number4 and
at most 2**32-1.number8 * parallelism and at most 2**32-1. The actual number of blocks is rounded
down to the nearest multiple of 4 * parallelism.number1 and at most
2**32-1.string | ArrayBuffer | Buffer | TypedArray | DataView | undefined2**32-1 bytes.string | ArrayBuffer | Buffer | TypedArray | DataView | undefined2**32-1 bytes.BufferProvides 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
ArrayBuffer | SharedArrayBuffer | TypedArray | Buffer | DataView | bigintObjectnumber0 (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: 0Checks the primality of the candidate.
crypto.checkPrimeSync(candidate, options?): boolean
ArrayBuffer | SharedArrayBuffer | TypedArray | Buffer | DataView | bigintObjectnumber0 (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: 0booleantrue if the candidate is a prime with an error
probability less than 0.25 ** options.checks.Checks the primality of the candidate.
ObjectAn object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in Crypto constants.
crypto.createCipheriv
History
key is no longer supported.ctsMode and xtsStandard options were added.key is deprecated.authTagLength option is now optional when using the chacha20-poly1305 cipher and defaults to 16 bytes.key argument can now be a KeyObject.chacha20-poly1305 (the IETF variant of ChaCha20-Poly1305) is now supported.authTagLength option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes.iv parameter may now be null for ciphers which do not need an initialization vector.crypto.createCipheriv(algorithm, key, iv, options?): Cipheriv
stringstring | ArrayBuffer | Buffer | TypedArray | DataView | KeyObjectstring | ArrayBuffer | Buffer | TypedArray | DataView | nullObjectstream.transform options with these additional
properties:numberstring'CS1', 'CS2',
or 'CS3'. The values are case-sensitive. Default: 'CS1'.stringkey is a string. This
option does not affect a string iv, which is always interpreted as UTF-8.
Default: 'utf8'.stringsm4-xts. One of 'GB' or
'IEEE'. The values are case-sensitive. Default: 'GB'.CipherivCreates and returns a Cipheriv object, with the given algorithm, key and
initialization vector (iv).
The options argument controls cipher-specific settings and stream behavior.
It 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 ctsMode and xtsStandard options configure parameters exposed by OpenSSL
providers. They are not available with BoringSSL and require a provider that
supports the corresponding parameter. ctsMode applies only to CBC-CTS
ciphers, and xtsStandard applies only to sm4-xts. Supplying either option
for an available cipher implementation that does not support it throws an
ERR_CRYPTO_UNSUPPORTED_OPERATION error. See CBC-CTS mode and XTS mode
for details.
The available algorithms depend on OpenSSL. crypto.getCiphers() lists the
algorithms exposed by Node.js. On recent OpenSSL releases,
openssl list -cipher-algorithms displays the algorithms available to OpenSSL,
which can include algorithms that Node.js does not expose.
The key is the raw key used by the algorithm and iv is an
initialization vector. Each may be a string, ArrayBuffer, Buffer,
TypedArray, or DataView. A string key is decoded using options.encoding,
which defaults to 'utf8'; a string iv is always decoded as UTF-8. 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 vector requirements depend on the algorithm. For some algorithms, an IV must be unpredictable and unique; for others, uniqueness alone is sufficient, a fixed value is required, or no IV is used. Follow the requirements for the selected algorithm. IVs typically do not have to be secret and can be transmitted with the ciphertext.
crypto.createDecipheriv
History
key is no longer supported.ctsMode and xtsStandard options were added.key is deprecated.authTagLength option is now optional when using the chacha20-poly1305 cipher and defaults to 16 bytes.key argument can now be a KeyObject.chacha20-poly1305 (the IETF variant of ChaCha20-Poly1305) is now supported.authTagLength option can now be used to restrict accepted GCM authentication tag lengths.iv parameter may now be null for ciphers which do not need an initialization vector.crypto.createDecipheriv(algorithm, key, iv, options?): Decipheriv
stringstring | ArrayBuffer | Buffer | TypedArray | DataView | KeyObjectstring | ArrayBuffer | Buffer | TypedArray | DataView | nullObjectstream.transform options with these additional
properties:numberstring'CS1', 'CS2',
or 'CS3'. The values are case-sensitive. Default: 'CS1'.stringkey is a string. This
option does not affect a string iv, which is always interpreted as UTF-8.
Default: 'utf8'.stringsm4-xts. One of 'GB' or
'IEEE'. The values are case-sensitive. Default: 'GB'.DecipherivCreates and returns a Decipheriv object that uses the given algorithm, key
and initialization vector (iv).
The options argument controls cipher-specific settings and stream behavior.
It 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 GCM and
chacha20-poly1305, the authTagLength option defaults to 16 bytes and must be
set 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 ctsMode and xtsStandard options configure parameters exposed by OpenSSL
providers. They are not available with BoringSSL and require a provider that
supports the corresponding parameter. ctsMode applies only to CBC-CTS
ciphers, and xtsStandard applies only to sm4-xts. Supplying either option
for an available cipher implementation that does not support it throws an
ERR_CRYPTO_UNSUPPORTED_OPERATION error. See CBC-CTS mode and XTS mode
for details.
The available algorithms depend on OpenSSL. crypto.getCiphers() lists the
algorithms exposed by Node.js. On recent OpenSSL releases,
openssl list -cipher-algorithms displays the algorithms available to OpenSSL,
which can include algorithms that Node.js does not expose.
The key is the raw key used by the algorithm and iv is an
initialization vector. Each may be a string, ArrayBuffer, Buffer,
TypedArray, or DataView. A string key is decoded using options.encoding,
which defaults to 'utf8'; a string iv is always decoded as UTF-8. 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 vector requirements depend on the algorithm. For some algorithms, an IV must be unpredictable and unique; for others, uniqueness alone is sufficient, a fixed value is required, or no IV is used. Follow the requirements for the selected algorithm. IVs typically do not have to be secret and can be transmitted with the ciphertext.
crypto.createDiffieHellman(prime, primeEncoding?, generator?, generatorEncoding?): DiffieHellman
string | ArrayBuffer | Buffer | TypedArray | DataViewnumber | string | ArrayBuffer | Buffer | TypedArray | DataView2DiffieHellmanCreates 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.
crypto.createDiffieHellman(primeLength, generator?): DiffieHellman
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.
crypto.createDiffieHellmanGroup(name): DiffieHellmanGroup
stringDiffieHellmanGroupAn alias for crypto.getDiffieHellman()
crypto.createECDH(curveName): 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
History
outputLength option is now required for XOF hash functions without default output lengths.functionName and customization options were added for cSHAKE hash functions.outputLength option was added for XOF hash functions.crypto.createHash(algorithm, options?): Hash
stringObjectstring | ArrayBuffer | Buffer | TypedArray | DataViewstring | ArrayBuffer | Buffer | TypedArray | DataViewnumberHashCreates and returns a Hash object that can be used to generate hash digests
using the given algorithm. The optional options argument controls stream
behavior. For XOF hash functions such as 'shake256', the outputLength option
specifies the desired output length in bytes. It is required for XOF hash
functions without a default output length.
The selected digest determines which options are supported in addition to the
standard stream.transform options.
For readily available data up to 5 MB, crypto.hash() can be faster.
The available algorithms depend on the version and configuration of OpenSSL on
the platform. Examples are 'sha256' and 'sha512'. Use
crypto.getHashes() to obtain the list of hash algorithms available to the
Node.js process.
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
History
key is no longer supported.key is deprecated.key argument can now be a KeyObject.crypto.createHmac(algorithm, key, options?): Hmac
stringstring | ArrayBuffer | Buffer | TypedArray | DataView | KeyObjectHmacCreates and returns an Hmac object that uses the given algorithm and key.
Optional options argument controls stream behavior.
The available algorithms depend on the version and configuration of OpenSSL on
the platform. Examples are 'sha256' and 'sha512'.
crypto.getHashes() lists algorithms available to the hashing APIs, but
HMAC imposes additional restrictions, so not every listed algorithm is
suitable.
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.createMac(algorithm, key, options?): Mac
stringArrayBuffer | Buffer | TypedArray | DataView | KeyObjectObjectstringstringArrayBuffer | Buffer | TypedArray | DataViewArrayBuffer | Buffer | TypedArray | DataViewArrayBuffer | Buffer | TypedArray | DataViewnumberMacalgorithm must be a non-empty MAC name. Use crypto.getMacs() to list
available algorithms. The selected MAC determines which options it accepts.
Supplying an unsupported MAC-specific option causes an error.
The following table summarizes the MAC-specific options accepted by MAC
implementations in OpenSSL's built-in providers. The key argument is required
for every MAC. The table lists only MAC-specific options; standard
stream.transform options remain available for every family.
| MAC family | Required options | Optional options | Notes |
|---|---|---|---|
| HMAC | digest | None | |
| CMAC | cipher using CBC mode | None | |
| GMAC | cipher using GCM mode, non-empty iv | None | Requires a unique IV for every message authenticated with a given key. |
| KMAC | None | customization, outputLength | |
| BLAKE2 MAC | None | customization, salt, outputLength | |
| Poly1305 | None | None | Each key must be used for only one message. |
| SipHash | None | outputLength |
outputLength configures the size of the tag computed by the MAC. KMAC, for
example, incorporates the requested length into the tag computation. A value
of 0 is accepted only for MACs that support an empty tag. When omitted, the
default output size is used and must be nonzero.
The key must contain bytes or be a KeyObject of type secret. Key
length and other key requirements depend on the selected MAC algorithm.
crypto.createPrivateKey
History
properties option was added.key is no longer supported.key is deprecated.'raw-private' and 'raw-seed' formats.crypto.createPrivateKey(key): KeyObject
Object | string | ArrayBuffer | Buffer | TypedArray | DataView | URLstring | ArrayBuffer | Buffer | TypedArray | DataView | Object | URLURL referencing an
object for an OpenSSL STORE loader.string'pem', 'der', 'jwk', 'raw-private',
or 'raw-seed'. Default: 'pem'.string'pkcs1', 'pkcs8' or 'sec1'. This option is
required only if the format is 'der' and ignored otherwise.key is a URL, this is the optional PIN/passphrase forwarded to the
STORE loader.stringURL key.stringkey is a string.stringformat is 'raw-private'
or 'raw-seed' and ignored otherwise.
Must be a supported key type.stringasymmetricKeyType is 'ec' and ignored otherwise.KeyObjectCreates 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.
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 itsfileloader before trying thepkcs11loader. 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
History
key is no longer supported.key is deprecated.'raw-public' format.key argument can now be a KeyObject with type private.key argument can now be a private key.crypto.createPublicKey(key): KeyObject
Object | string | ArrayBuffer | Buffer | TypedArray | DataViewstring | ArrayBuffer | Buffer | TypedArray | DataView | Objectstring'pem', 'der', 'jwk', or 'raw-public'.
Default: 'pem'.string'pkcs1' or 'spki'. This option is
required only if the format is 'der' and ignored otherwise.stringkey is a string.stringstringasymmetricKeyType is 'ec' and ignored otherwise.KeyObjectCreates 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
string | ArrayBuffer | Buffer | TypedArray | DataViewstringkey is a string.KeyObjectCreates and returns a new key object containing a secret key for symmetric
encryption or Hmac.
crypto.createSign(algorithm, options?): Sign
Creates and returns a Sign object that uses the given algorithm. Use
crypto.getHashes() to obtain the names available to the hashing APIs. The
key type and signature scheme can impose additional restrictions on which
digests can be used. 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.
crypto.createVerify(algorithm, options?): Verify
Creates and returns a Verify object that uses the given algorithm.
Use crypto.getHashes() to obtain the names available to the hashing APIs.
The key type and signature scheme can impose additional restrictions on which
digests can be used. 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.
crypto.decapsulate(key, ciphertext, callback?): Buffer
Object | string | ArrayBuffer | Buffer | TypedArray | DataView | KeyObject | URLArrayBuffer | Buffer | TypedArray | DataViewBuffercallback 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
History
crypto.diffieHellman(options, callback?): Buffer
ObjectObject | string | ArrayBuffer | Buffer | TypedArray | DataView | KeyObject | URLObject | string | ArrayBuffer | Buffer | TypedArray | DataView | KeyObjectBuffercallback 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.
crypto.encapsulate(key, callback?): Object
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.
crypto.generateKey(type, options, callback): void
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
History
callback argument now throws ERR_INVALID_ARG_TYPE instead of ERR_INVALID_CALLBACK.RSASSA-PSS-params sequence parameters for RSA-PSS keys pairs.generateKeyPair and generateKeyPairSync functions now produce key objects if no encoding was specified.crypto.generateKeyPair(type, options, callback): void
stringObjectnumbernumber0x10001.stringstringnumbernumberq in bits (DSA).stringBuffernumbernumber2.stringcrypto.getDiffieHellman().string'named' or 'explicit' (EC).
Default: 'named'.ObjectkeyObject.export().ObjectkeyObject.export().Generates a new asymmetric key pair of the given type. See the
supported asymmetric key types.
For RSA-PSS keys, crypto.getHashes() lists algorithms available to the
hashing APIs, but not every listed digest can be encoded in RSA-PSS parameters
or is supported by the active RSA implementation.
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
History
RSASSA-PSS-params sequence parameters for RSA-PSS keys pairs.generateKeyPair and generateKeyPairSync functions now produce key objects if no encoding was specified.crypto.generateKeyPairSync(type, options): Object
stringObjectnumbernumber0x10001.stringstringnumbernumberq in bits (DSA).stringBuffernumbernumber2.stringcrypto.getDiffieHellman().string'named' or 'explicit' (EC).
Default: 'named'.ObjectkeyObject.export().ObjectkeyObject.export().Generates a new asymmetric key pair of the given type. See the
supported asymmetric key types.
For RSA-PSS keys, crypto.getHashes() lists algorithms available to the
hashing APIs, but not every listed digest can be encoded in RSA-PSS parameters
or is supported by the active RSA implementation.
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.
crypto.generateKeySync(type, options): 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
numberObjectArrayBuffer | SharedArrayBuffer | TypedArray | Buffer | DataView | bigintArrayBuffer | SharedArrayBuffer | TypedArray | Buffer | DataView | bigintbooleanfalse.booleantrue, the generated prime is returned
as a bigint.FunctionErrorArrayBuffer | bigintGenerates 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.addandoptions.remare both set, the prime will satisfy the condition thatprime % add = rem. - If only
options.addis set andoptions.safeis nottrue, the prime will satisfy the condition thatprime % add = 1. - If only
options.addis set andoptions.safeis set totrue, the prime will instead satisfy the condition thatprime % add = 3. This is necessary becauseprime % add = 1foroptions.add > 2would contradict the condition enforced byoptions.safe. options.remis ignored ifoptions.addis 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.
crypto.generatePrimeSync(size, options?): ArrayBuffer | bigint
numberObjectArrayBuffer | SharedArrayBuffer | TypedArray | Buffer | DataView | bigintArrayBuffer | SharedArrayBuffer | TypedArray | Buffer | DataView | bigintbooleanfalse.booleantrue, the generated prime is returned
as a bigint.ArrayBuffer | bigintGenerates 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.addandoptions.remare both set, the prime will satisfy the condition thatprime % add = rem. - If only
options.addis set andoptions.safeis nottrue, the prime will satisfy the condition thatprime % add = 1. - If only
options.addis set andoptions.safeis set totrue, the prime will instead satisfy the condition thatprime % add = 3. This is necessary becauseprime % add = 1foroptions.add > 2would contradict the condition enforced byoptions.safe. options.remis ignored ifoptions.addis 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.
crypto.generateX509Certificate(options, callback): void
Objectstring | ArrayBuffer | Buffer | TypedArray | DataViewsubject or publicKey.Array<Object | Object[]> | ArrayBuffer | Buffer | TypedArray | DataViewcsr is
supplied. See Distinguished name inputs.KeyObject | string | ArrayBuffer | Buffer | TypedArray | DataView | Objectcrypto.createPublicKey(). Required
unless csr is supplied.X509Certificatebigint1n through
(1n << 159n) - 1n.DateDateObjectKeyObject | string | URL | ArrayBuffer | Buffer | TypedArray | DataView | Objectcrypto.sign(). Its padding and
saltLength RSA options apply to certificate signing; signature encoding
and context options do not apply.Object[]FunctionErrorX509CertificateGenerates and signs an X.509 v3 certificate. Validation errors are thrown
synchronously, and mutable input data is copied before asynchronous work.
Certificate request signature verification and signing errors are passed to
callback. The function is compatible with util.promisify(). Supported
key and digest combinations depend on the configured crypto backend.
Dates are accepted from 1950 through 9999 and truncated to whole seconds.
After truncation, notAfter must be later than notBefore. No extensions are
added implicitly.
For a self-signed certificate, the subject must not be empty and
signature.key must match the certificate public key. With an issuer, the
issuer subject must not be empty and its public key must match signature.key.
If the backend cannot compare the keys, the caller must ensure they match.
The returned certificate is standalone; the supplied issuer and its certificate
chain are not attached to the result through issuerCertificate.
This function does not validate a certification path or determine whether the certificate is trusted.
When csr is supplied, the request supplies the certificate subject and public
key. The configured crypto backend parses the request, after which Node.js
invokes options.selectExtensions synchronously before verifying the request
signature. The callback therefore receives unauthenticated request data and
must apply the issuer's policy. A thrown exception propagates synchronously,
and returning a Promise is not supported. The request signature is verified
before the certificate is signed, so an invalid proof of possession cannot
produce a certificate.
Requested extensions are never copied implicitly. The policy callback receives
fresh raw extension objects in request order. Each object has type: 'raw', a
canonical dotted oid string, critical boolean, and value Buffer
containing the extnValue bytes. It may return those objects, filter them, or
replace them with any forms described in Extension inputs. The returned
list is validated in the same way as options.extensions. For an
empty-subject request, the returned list must contain a typed,
critical, nonempty Subject Alternative Name. Echoing a raw Subject Alternative
Name does not satisfy this certificate construction check.
import { generateX509Certificate, X509Certificate, } from 'node:crypto'; import { readFileSync } from 'node:fs'; const allowedExtensionOids = new Set([ '2.5.29.15', // Key Usage '2.5.29.17', // Subject Alternative Name ]); generateX509Certificate({ csr: readFileSync('request.csr'), issuer: new X509Certificate(readFileSync('issuer-cert.pem')), serialNumber: 1n, notBefore: new Date('2026-01-01T00:00:00Z'), notAfter: new Date('2027-01-01T00:00:00Z'), signature: { key: readFileSync('issuer-key.pem'), digest: 'sha256', }, selectExtensions(requestedExtensions) { return requestedExtensions.filter(({ oid }) => allowedExtensionOids.has(oid)); }, }, (err, certificate) => { if (err) throw err; console.log(certificate.toString()); });
In its structured form, subject Array<Object | Object[]> is an ordered array
whose entries are attribute objects or nonempty arrays of attribute objects.
Each entry in the outer array forms one relative distinguished name (RDN). An
attribute has name string and value string. name is a canonical dotted
OID or one of commonName/CN,
countryName/C, localityName/L, stateOrProvinceName/ST,
organizationName/O, organizationalUnitName/OU, serialNumber,
streetAddress, postalCode, domainComponent/DC, userId/UID,
emailAddress/E, title, surname/SN, or givenName/GN. value must
not contain NUL characters.
const subject = [ { name: 'countryName', value: 'US' }, { name: 'organizationName', value: 'Example Inc.' }, [ { name: 'commonName', value: 'example.com' }, { name: 'serialNumber', value: '1234' }, ], ];
The final nested array places commonName and serialNumber in the same RDN.
RDN sequence and grouping are preserved. DER canonical ordering applies inside a multi-valued RDN. The crypto backend selects and validates each attribute's ASN.1 string type according to its OID.
Alternatively, subject may be an
ArrayBuffer | Buffer | TypedArray | DataView containing the complete DER encoding
of exactly one X.509 Name, including its outer SEQUENCE tag and length.
The input is copied synchronously. If accepted by
the configured crypto backend, the encoded name is preserved byte-for-byte,
including its RDN grouping, attribute order, and ASN.1 string types. This form
can reproduce an existing name exactly, for example by using
subject: certificate.subjectName.raw. The subjectName.rdns view is not a
generation input format and does not include ASN.1 value types. The caller is
responsible for ensuring that the supplied encoding is canonical DER.
options.extensions and the value returned by options.selectExtensions are
ordered arrays of extension objects. Each extension object has one of the
following forms. Except where noted, all forms accept an optional critical
boolean, which defaults to false.
const extensions = [ { type: 'keyUsage', critical: true, usages: ['digitalSignature'], }, { type: 'subjectAltName', names: [ { type: 'dns', value: 'example.com' }, { type: 'ip', value: '192.0.2.1' }, ], }, ];
- Basic Constraints:
type: 'basicConstraints',caboolean, and optionalpathLengthnumber, which must be a non-negative integer. - Key Usage:
type: 'keyUsage'and nonemptyusagesstring[]. A usage isdigitalSignature,contentCommitment,keyEncipherment,dataEncipherment,keyAgreement,keyCertSign,crlSign,encipherOnly, ordecipherOnly. - Extended Key Usage:
type: 'extendedKeyUsage'and nonemptyusagesstring[]. A usage is a canonical dotted OID orserverAuth,clientAuth,codeSigning,emailProtection,timeStamping,ocspSigning, oranyExtendedKeyUsage. - Subject Alternative Name:
type: 'subjectAltName'and nonemptynamesObject[]. Each name hastypeset to'dns','ip','email', or'uri', and a stringvalue. IP values must be IPv4 or IPv6 addresses and must not contain an IPv6 zone identifier. The other values must be nonempty ASCII strings without NUL and are not otherwise validated. - Subject Key Identifier:
type: 'subjectKeyIdentifier'andvalue: 'auto'orvalueArrayBuffer | TypedArray | Buffer | DataView. A binary value contains the nonempty key identifier bytes, not DER.'auto'uses RFC 7093 method 1: the leftmost 160 bits of the SHA-256 digest of thesubjectPublicKeyBIT STRING contents. This typed form is always noncritical. - Authority Key Identifier:
type: 'authorityKeyIdentifier'andvalue: 'auto'orvalueArrayBuffer | TypedArray | Buffer | DataView. A binary value contains the nonempty key identifier bytes and populates only the extension'skeyIdentifierfield. Whenoptions.issueris supplied,'auto'asks the configured crypto backend to decode and copy its Subject Key Identifier. If the extension is absent, the identifier is instead derived from the issuer public key using RFC 7093 method 1. The operation fails if the backend cannot decode a single Subject Key Identifier. Whenoptions.issueris omitted,'auto'copies an explicit typed Subject Key Identifier in the same extension list, or derives the identifier from the certificate public key. This typed form is always noncritical. - Raw:
type: 'raw',oidstring, andvalueArrayBuffer | TypedArray | Buffer | DataView.valueis copied intoextnValue. Raw values are not parsed or semantically validated and may use an OID that also has a typed form. The caller is responsible for their DER syntax and semantics. The selected crypto backend may reject a raw encoding. If it reports success without retaining the extension, generation throwsERR_CRYPTO_UNSUPPORTED_OPERATIONinstead of returning an altered certificate.
Duplicate extension OIDs are rejected. Structural checks use only typed forms:
a Key Usage containing keyCertSign requires CA Basic Constraints, and
pathLength requires CA Basic Constraints and a Key Usage that includes
keyCertSign. An empty subject is permitted only for an issuer-signed
certificate and requires an explicitly critical, nonempty typed Subject
Alternative Name extension.
For an existing certificate source, the following fields can be included in
generation options to copy its encoded subject and raw extension contents:
const copiedFields = { subject: source.subjectName.raw, extensions: source.extensions.map((extension) => ({ type: 'raw', ...extension, })), };
This copies the name encoding and extension values, not the original certificate as a whole. Generation validation still applies, including the rejection of duplicate extension OIDs exposed by inspection.
crypto.generateX509CertificateSync(options): X509Certificate
ObjectX509CertificateSynchronous version of crypto.generateX509Certificate().
crypto.getCipherInfo(nameOrNid, options?): Object
Objectstringundefined if the
cipher has no OpenSSL nid.undefined when mode is 'stream'.undefined if the cipher does not use an initialization
vector.numberstring'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.
crypto.getCiphers(): string[]
string[]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', ...]
crypto.getCurves(): string[]
string[]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', ...]
crypto.getDiffieHellman(groupName): DiffieHellmanGroup
stringDiffieHellmanGroupCreates 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);
crypto.getFips(): number
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.
crypto.getHashes(): string[]
string[]'RSA-SHA256'. Hash algorithms are also called "digest" algorithms.This is the authoritative Node.js list of hash algorithms available to
crypto.createHash() and crypto.hash() in the current process. With
OpenSSL, the list depends on the loaded providers and the default property query
in effect when the list is first generated. Some listed algorithms can require
API-specific options, such as outputLength for XOF hash functions.
A listed hash algorithm is not necessarily supported by APIs that combine a digest with another cryptographic operation, such as HMAC, key derivation, or signing. Those operations can apply additional restrictions.
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', ...]
crypto.getMacs(): string[]
string[]A listed MAC can require additional options or a key of a specific length.
See crypto.createMac() for the options that apply to each MAC family.
After a successful FIPS mode change made with crypto.setFips(), subsequent
calls reflect the new mode, and newly created Mac objects use it. Existing
Mac objects continue using the implementation selected when they were created.
const { getMacs } = await import('node:crypto'); console.log(getMacs()); // ['blake2bmac', 'blake2smac', 'cmac', 'gmac', 'hmac', ...]
crypto.getRandomValues(typedArray): Buffer | TypedArray | DataView | ArrayBuffer
Buffer | TypedArray | DataView | ArrayBufferBuffer | TypedArray | DataView | ArrayBuffertypedArray.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
History
outputLength option is now required for XOF hash functions without default output lengths.functionName and customization options were added for cSHAKE hash functions.outputLength option was added for XOF hash functions.crypto.hash(algorithm, data, options?): string | Buffer
stringstring | Buffer | TypedArray | DataViewdata 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.string | ArrayBuffer | Buffer | TypedArray | DataViewstring | ArrayBuffer | Buffer | TypedArray | DataViewnumberA utility for creating one-shot hash digests of data. It can be faster than
crypto.createHash() for readily available data up to 5 MB. Use
crypto.createHash() for large inputs or streamed data.
The available algorithms depend on the version and configuration of OpenSSL on
the platform. Examples are 'sha256' and 'sha512'. Use
crypto.getHashes() to obtain the list of hash algorithms available to the
Node.js process.
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
stringstring | ArrayBuffer | Buffer | TypedArray | DataView | KeyObjectstring | ArrayBuffer | Buffer | TypedArray | DataViewstring | ArrayBuffer | Buffer | TypedArray | DataViewnumber255 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).FunctionErrorArrayBufferHKDF 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 available digest algorithms depend on the version and configuration of
OpenSSL. HKDF uses HMAC internally. crypto.getHashes() lists algorithms
available to the hashing APIs, but not every listed algorithm is necessarily
suitable for HMAC or HKDF.
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
History
crypto.hkdfSync(digest, ikm, salt, info, keylen): ArrayBuffer
stringstring | ArrayBuffer | Buffer | TypedArray | DataView | KeyObjectstring | ArrayBuffer | Buffer | TypedArray | DataViewstring | ArrayBuffer | Buffer | TypedArray | DataViewnumber255 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).ArrayBufferProvides 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 available digest algorithms depend on the version and configuration of
OpenSSL. HKDF uses HMAC internally. crypto.getHashes() lists algorithms
available to the hashing APIs, but not every listed algorithm is necessarily
suitable for HMAC or HKDF.
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.parsePKCS12(bundle, options?): Object
ArrayBuffer | Buffer | TypedArray | DataView.p12 or .pfx) bundle.Objectstring | ArrayBuffer | Buffer | TypedArray | DataView''.ObjectX509Certificate | nullprivateKey,
or null if no matching certificate is present.X509Certificate[]Parses a PKCS#12 bundle, commonly stored with a .p12 or .pfx extension,
and returns its private key and certificates.
import { parsePKCS12 } from 'node:crypto'; import { readFileSync } from 'node:fs'; const { privateKey, certificate, additionalCertificates } = parsePKCS12( readFileSync('bundle.p12'), { passphrase: 'secret' }, );
crypto.pbkdf2
History
callback argument now throws ERR_INVALID_ARG_TYPE instead of ERR_INVALID_CALLBACK.iterations parameter is now restricted to positive values. Earlier releases treated other values as one.digest parameter is always required now.digest parameter is deprecated now and will emit a warning.password if it is a string changed from binary to utf8.crypto.pbkdf2(password, salt, iterations, keylen, digest, callback): void
string | ArrayBuffer | Buffer | TypedArray | DataViewstring | ArrayBuffer | Buffer | TypedArray | DataViewnumbernumberstringProvides 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' });
The available digest algorithms depend on the version and configuration of
OpenSSL. PBKDF2 uses HMAC internally. crypto.getHashes() lists algorithms
available to the hashing APIs, but not every listed algorithm is necessarily
suitable for HMAC or PBKDF2.
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
History
iterations parameter is now restricted to positive values. Earlier releases treated other values as one.digest parameter is deprecated now and will emit a warning.password if it is a string changed from binary to utf8.crypto.pbkdf2Sync(password, salt, iterations, keylen, digest): Buffer
string | ArrayBuffer | Buffer | TypedArray | DataViewstring | ArrayBuffer | Buffer | TypedArray | DataViewnumbernumberstringBufferProvides 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'
The available digest algorithms depend on the version and configuration of
OpenSSL. PBKDF2 uses HMAC internally. crypto.getHashes() lists algorithms
available to the hashing APIs, but not every listed algorithm is necessarily
suitable for HMAC or PBKDF2.
crypto.privateDecrypt
History
privateKey is no longer supported.mgf1Hash option was added.RSA_PKCS1_PADDING padding was disabled unless the OpenSSL build supports implicit rejection.oaepLabel option was added.oaepHash option was added.crypto.privateDecrypt(privateKey, buffer): Buffer
Object | string | ArrayBuffer | Buffer | TypedArray | DataView | KeyObject | URLstringmgf1Hash is set, MGF1. Default: 'sha1'stringoaepHash is used.
This allows the OAEP digest and the MGF1 digest to differ.string | ArrayBuffer | Buffer | TypedArray | DataViewcrypto.constantscrypto.constants, which may be: crypto.constants.RSA_NO_PADDING,
crypto.constants.RSA_PKCS1_PADDING, or
crypto.constants.RSA_PKCS1_OAEP_PADDING.string | ArrayBuffer | Buffer | TypedArray | DataViewBufferBuffer with the decrypted content.Decrypts buffer with privateKey. buffer was previously encrypted using
the corresponding public key, for example using crypto.publicEncrypt().
crypto.getHashes() lists algorithms available to the hashing APIs, but
the active RSA implementation can impose additional restrictions on digests
used for OAEP or MGF1.
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
History
privateKey is no longer supported.crypto.privateEncrypt(privateKey, buffer): Buffer
Object | string | ArrayBuffer | Buffer | TypedArray | DataView | KeyObject | URLstring | ArrayBuffer | Buffer | TypedArray | DataView | KeyObject | URLstring | ArrayBuffer | Buffer | TypedArray | DataViewcrypto.constantscrypto.constants, which may be: crypto.constants.RSA_NO_PADDING or
crypto.constants.RSA_PKCS1_PADDING.stringbuffer, key,
or passphrase are strings.string | ArrayBuffer | Buffer | TypedArray | DataViewBufferBuffer 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
History
key is no longer supported.crypto.publicDecrypt(key, buffer): Buffer
Object | string | ArrayBuffer | Buffer | TypedArray | DataView | KeyObjectstring | ArrayBuffer | Buffer | TypedArray | DataViewcrypto.constantscrypto.constants, which may be: crypto.constants.RSA_NO_PADDING or
crypto.constants.RSA_PKCS1_PADDING.stringbuffer, key,
or passphrase are strings.string | ArrayBuffer | Buffer | TypedArray | DataViewBufferBuffer 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
History
key is no longer supported.mgf1Hash option was added.oaepLabel option was added.oaepHash option was added.crypto.publicEncrypt(key, buffer): Buffer
Object | string | ArrayBuffer | Buffer | TypedArray | DataView | KeyObjectstring | ArrayBuffer | Buffer | TypedArray | DataView | KeyObjectKeyObject.stringmgf1Hash is set, MGF1. Default: 'sha1'stringoaepHash is used.
This allows the OAEP digest and the MGF1 digest to differ.string | ArrayBuffer | Buffer | TypedArray | DataViewstring | ArrayBuffer | Buffer | TypedArray | DataViewcrypto.constantscrypto.constants, which may be: crypto.constants.RSA_NO_PADDING,
crypto.constants.RSA_PKCS1_PADDING, or
crypto.constants.RSA_PKCS1_OAEP_PADDING.stringbuffer, key,
oaepLabel, or passphrase are strings.string | ArrayBuffer | Buffer | TypedArray | DataViewBufferBuffer 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().
crypto.getHashes() lists algorithms available to the hashing APIs, but
the active RSA implementation can impose additional restrictions on digests
used for OAEP or MGF1.
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
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
ArrayBuffer | Buffer | TypedArray | DataViewbuffer must not be larger than 2**31 - 1.numberTypedArray and in
bytes for an ArrayBuffer or DataView. Default: 0numberoffset.
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.Functionfunction(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
History
buffer argument may be any TypedArray or DataView.crypto.randomFillSync(buffer, offset?, size?): ArrayBuffer | Buffer | TypedArray | DataView
ArrayBuffer | Buffer | TypedArray | DataViewbuffer must not be larger than 2**31 - 1.numberTypedArray and in
bytes for an ArrayBuffer or DataView. Default: 0numberoffset.
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.ArrayBuffer | Buffer | TypedArray | DataViewbuffer 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
History
callback argument now throws ERR_INVALID_ARG_TYPE instead of ERR_INVALID_CALLBACK.crypto.randomInt(min?, max, callback?): void
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}`);
crypto.randomUUID(options?): string
Generates a random RFC 4122 version 4 UUID. The UUID is generated using a cryptographic pseudorandom number generator.
crypto.randomUUIDv7(options?): 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
History
callback argument now throws ERR_INVALID_ARG_TYPE instead of ERR_INVALID_CALLBACK.maxmem value can now be any safe integer.cost, blockSize and parallelization option names have been added.crypto.scrypt(password, salt, keylen, options?, callback): void
string | ArrayBuffer | Buffer | TypedArray | DataViewstring | ArrayBuffer | Buffer | TypedArray | DataViewnumberObjectnumber16384.number8.number1.numbercost. Only one of both may be specified.numberblockSize. Only one of both may be specified.numberparallelization. Only one of both may be specified.number128 * N * r > maxmem. Default: 32 * 1024 * 1024.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
string | Buffer | TypedArray | DataViewstring | Buffer | TypedArray | DataViewnumberObjectnumber16384.number8.number1.numbercost. Only one of both may be specified.numberblockSize. Only one of both may be specified.numberparallelization. Only one of both may be specified.number128 * N * r > maxmem. Default: 32 * 1024 * 1024.BufferProvides 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'
crypto.secureHeapUsed(): Object
Objectnumber--secure-heap=n command-line flag.number--secure-heap-min command-line flag.numbernumberused to total
allocated bytes.crypto.setFips(bool): void
booleantrue to enable FIPS mode, false to disable it.Changes FIPS mode. 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. Like this method,
the command-line flags change the property query without loading or validating
a provider or running its self-tests.
Throws an error if OpenSSL cannot change the state. FIPS mode cannot be
disabled when Node.js was started with --force-fips.
crypto.sign
History
key is no longer supported.callback argument now throws ERR_INVALID_ARG_TYPE instead of ERR_INVALID_CALLBACK.crypto.sign(algorithm, data, key, callback?): Buffer
ArrayBuffer | Buffer | SharedArrayBuffer | TypedArray | DataView | stringObject | string | ArrayBuffer | Buffer | TypedArray | DataView | KeyObject | URLBuffercallback 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, ML-DSA,
and SLH-DSA.
crypto.getHashes() lists algorithms available to the hashing APIs, but
the key type and signature scheme determine whether a listed digest can be
used for signing.
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:
string(r, s).r || s as proposed in IEEE-P1363.integerintegerRSA_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.Buffer | TypedArray | DataViewIf the callback function is provided this function uses libuv's threadpool.
SubtleCryptoA convenient alias for crypto.webcrypto.subtle.
crypto.timingSafeEqual
History
crypto.timingSafeEqual(a, b): boolean
ArrayBuffer | Buffer | TypedArray | DataViewArrayBuffer | Buffer | TypedArray | DataViewbooleanThis 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
History
key is no longer supported.callback argument now throws ERR_INVALID_ARG_TYPE instead of ERR_INVALID_CALLBACK.crypto.verify(algorithm, data, key, signature, callback?): boolean
ArrayBuffer | Buffer | SharedArrayBuffer | TypedArray | DataView | stringObject | string | ArrayBuffer | Buffer | TypedArray | DataView | KeyObjectArrayBuffer | Buffer | SharedArrayBuffer | TypedArray | DataViewbooleantrue 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, ML-DSA,
and SLH-DSA.
crypto.getHashes() lists algorithms available to the hashing APIs, but
the key type and signature scheme determine whether a listed digest can be
used for verification.
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:
string(r, s).r || s as proposed in IEEE-P1363.integerintegerRSA_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.Buffer | TypedArray | DataViewThe 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.
Type: Crypto An implementation of the Web Crypto API standard.
See the Web Crypto API documentation for details.