Node.js Crypto Module

Prepare for Node.js backend, security, and platform engineering interviews with this comprehensive collection of Node.js Crypto API interview questions. This flashcard set covers the complete cryptographic ecosystem available through the Node.js Crypto module, helping developers understand both practical implementation and architectural decision-making. Topics include symmetric and asymmetric encryption, hashing algorithms, HMAC generation, digital signatures, certificate management, key handling, Diffie-Hellman and ECDH key exchange, authenticated encryption modes, secure random generation, and cryptographic best practices. The questions go beyond basic API usage and explore real-world scenarios such as securing APIs, protecting sensitive user data, implementing authentication systems, encrypting files, managing secrets, validating certificates, preventing common cryptographic mistakes, and designing secure distributed systems. You'll also learn the trade-offs between different algorithms, how authenticated encryption works, when to use hashes versus HMACs, how public/private key cryptography differs from symmetric encryption, and how Node.js integrates with OpenSSL and FIPS-compliant environments. This set is suitable for Backend Developers, Full-Stack Engineers, Security Engineers, DevOps Specialists, Technical Leads, and Software Architects preparing for middle, senior, and staff-level interviews. Whether you're studying for a job interview, improving application security, reviewing cryptographic fundamentals, or building production-grade Node.js services, these cards provide a structured and practical learning path focused on both theory and implementation. You may also be interested in: Master Node.js: From Basics to Production Node.js Stream Module Node.js Cluster Module Node.js Child Process Module Node.js Buffer API Interview Questions Node.js Operating System Module Node.js File System Module

Knowledge check

Take a test before studying to see which topics you know and where the gaps are.

Take the test

Messenger lessons

Study cards and revisit what you have learned in interactive lessons.

How lessons work

Spaced repetition

Get individual cards to review at intervals that help you remember them longer.

How repetition works
Crypto

The node:crypto module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.

The node:crypto module provides primitives for hashing, message authentication, encryption, signatures, key agreement, and secure random values. Choose algorithms and key sizes according to current security guidance. A hash is not encryption, and a signature does not make data secret. Use well-tested protocols rather than designing a new cryptographic scheme from primitives.

1/145
Determining if crypto support is unavailable

It is possible for Node.js to be built without including support for the node:crypto module. In such cases, attempting to import from crypto or calling require('node:crypto') will result in an error being thrown.

2/145
Class: Certificate

SPKAC is a Certificate Signing Request mechanism originally implemented by Netscape and was specified formally as part of HTML5's keygen element.


<keygen> is deprecated since HTML 5.2 and new projects should not use this element anymore.

3/145
exportChallenge

Exports a cryptographic challenge associated with a certificate, often used in secure communication protocols to verify ownership of a certificate or domain.

4/145
exportPublicKey

It allows to extract the public key material, which can then be used for cryptographic operations like encryption, signature verification, or sharing securely.

5/145
verifySpkac

It is used to verify and decode a SPKAC (Signed Public Key and Challenge) structure.


SPKAC is typically generated as part of the key generation and certificate signing request process in browsers.

6/145
Class: Cipher

Extends: <stream.Transform>


Instances of the Cipher class are used to encrypt data.

7/145
cipher.final()

It is used to finalize the encryption process.


After encrypting data in chunks using a Cipher object, you call cipher.final() to generate the final encrypted data block.

8/145
cipher.getAuthTag()

It is used with authenticated encryption modes, such as GCM (Galois/Counter Mode), to retrieve the authentication tag generated during the encryption process.

9/145
cipher.setAAD()

When using an authenticated encryption mode (GCM, CCM, OCB, and chacha20-poly1305 are currently supported), the method sets the value used for the additional authenticated data (AAD) input parameter.

10/145
setAutoPadding()

When using block encryption algorithms, the Cipher class will automatically add padding to the input data to the appropriate block size.


To disable the default padding call cipher.setAutoPadding(false).

11/145
update()

Updates the cipher with data.


If the inputEncoding argument is given, the data argument is a string using the specified encoding.

12/145
Class: Decipher

Extends: <stream.Transform>


Instances of the Decipher class are used to decrypt data.

13/145
final()

Once the decipher.final() method has been called, the Decipher object can no longer be used to decrypt data.


Attempts to call decipher.final() more than once will result in an error being thrown.

14/145
decipher.setAAD()

When using an authenticated encryption mode (GCM, CCM, OCB, and chacha20-poly1305 are currently supported), the decipher.setAAD() method sets the value used for the additional authenticated data (AAD) input parameter.

15/145
decipher.setAuthTag(buffer[, encoding])
buffer <string> | <Buffer> | <ArrayBuffer> | <TypedArray> | <DataView> encoding <string> String encoding to use when buffer is a string. Returns: <Decipher> The same Decipher for method chaining.
16/145
decipher.setAutoPadding([autoPadding])
autoPadding <boolean> Default: true Returns: <Decipher> The same Decipher for method chaining. Turning auto padding off will only work if the input data's length is a multiple of the ciphers block size.
17/145
decipher.update(data[, inputEncoding][, outputEncoding])
data <string> | <Buffer> | <TypedArray> | <DataView> inputEncoding <string> The encoding of the data string. outputEncoding <string> The encoding of the return value. Returns: <Buffer> | <string>
18/145
Class: DiffieHellman
The DiffieHellman class is a utility for creating Diffie-Hellman key exchanges. Instances of the DiffieHellman class can be created using the crypto.createDiffieHellman() function.

DiffieHellman lets two parties derive a shared secret from their own private key and the other party’s public key. generateKeys() creates a key pair and computeSecret() derives the result. The shared secret should usually be processed by a key-derivation function before being used as an application key. Authenticate the peer to prevent man-in-the-middle attacks.

19/145
diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])
otherPublicKey <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> inputEncoding <string> The encoding of an otherPublicKey string. outputEncoding <string> The encoding of the return value.
20/145
diffieHellman.generateKeys([encoding])
encoding <string> The encoding of the return value. Returns: <Buffer> | <string>
21/145
diffieHellman.getGenerator([encoding])
encoding <string> The encoding of the return value. Returns: <Buffer> | <string> Returns the Diffie-Hellman generator in the specified encoding. If encoding is provided a string is returned; otherwise a Buffer is returned.
22/145
diffieHellman.getPrime([encoding])
encoding <string> The encoding of the return value. Returns: <Buffer> | <string> Returns the Diffie-Hellman prime in the specified encoding. If encoding is provided a string is returned; otherwise a Buffer is returned.
23/145
diffieHellman.getPrivateKey([encoding])
encoding <string> The encoding of the return value. Returns: <Buffer> | <string> Returns the Diffie-Hellman private key in the specified encoding. If encoding is provided a string is returned; otherwise a Buffer is returned.
24/145
diffieHellman.getPublicKey([encoding])
encoding <string> The encoding of the return value. Returns: <Buffer> | <string> Returns the Diffie-Hellman public key in the specified encoding. If encoding is provided a string is returned; otherwise a Buffer is returned.
25/145
diffieHellman.setPrivateKey(privateKey[, encoding])
privateKey <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> encoding <string> The encoding of the privateKey string.
26/145
diffieHellman.setPublicKey(publicKey[, encoding])
publicKey <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> encoding <string> The encoding of the publicKey string.
27/145
diffieHellman.verifyError
A bit field containing any warnings and/or errors resulting from a check performed during initialization of the DiffieHellman object. The following values are valid for this property (as defined in node:constants module): DH_CHECK_P_NOT_SAFE_PRIME DH_CHECK_P_NOT_PRIME DH_NOT_SUITABLE_GENERATOR
28/145
Class: DiffieHellmanGroup
The DiffieHellmanGroup class takes a well-known modp group as its argument. It works the same as DiffieHellman, except that it does not allow changing its keys after creation. In other words, it does not implement setPublicKey() or setPrivateKey() methods.
29/145
Class: ECDH
The ECDH class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) key exchanges. Instances of the ECDH class can be created using the crypto.createECDH() function.

ECDH performs elliptic-curve Diffie-Hellman key agreement. createECDH(curveName) creates an instance, generateKeys() makes a key pair, and computeSecret(otherPublicKey) derives shared material. The parties must agree on the curve. Key agreement alone does not authenticate the other party; a protocol must bind public keys to identities.

30/145
Static method: ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])
key <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> curve <string> inputEncoding <string> The encoding of the key string. outputEncoding <string> The encoding of the return value.
31/145
ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])
otherPublicKey <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> inputEncoding <string> The encoding of the otherPublicKey string. outputEncoding <string> The encoding of the return value.
32/145
ecdh.generateKeys([encoding[, format]])
encoding <string> The encoding of the return value. format <string> Default: 'uncompressed' Returns: <Buffer> | <string> If encoding is provided a string is returned; otherwise a Buffer is returned.
33/145
ecdh.getPrivateKey([encoding])
encoding <string> The encoding of the return value. Returns: <Buffer> | <string> The EC Diffie-Hellman in the specified encoding. If encoding is specified, a string is returned; otherwise a Buffer is returned.
34/145
ecdh.getPublicKey([encoding][, format])
encoding <string> The encoding of the return value. format <string> Default: 'uncompressed' Returns: <Buffer> | <string> The EC Diffie-Hellman public key in the specified encoding and format.
35/145
ecdh.setPrivateKey(privateKey[, encoding])
privateKey <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> encoding <string> The encoding of the privateKey string.
36/145
Class: Hash
Extends: <stream.Transform> The Hash class is a utility for creating hash digests of data. It can be used in one of two ways: As a stream that is both readable and writable, where data is written to produce a computed hash digest on the readable side, or
37/145
hash.copy([options])
options <Object> stream.transform options Returns: <Hash> Creates a new Hash object that contains a deep copy of the internal state of the current Hash object.
38/145
hash.digest([encoding])
encoding <string> The encoding of the return value. Returns: <Buffer> | <string> Calculates the digest of all of the data passed to be hashed (using the hash.update() method). If encoding is provided a string will be returned; otherwise a Buffer is returned.
39/145
hash.update(data[, inputEncoding])
data <string> | <Buffer> | <TypedArray> | <DataView> inputEncoding <string> The encoding of the data string. This can be called many times with new data as it is streamed.
40/145
Class: Hmac
Extends: <stream.Transform> The Hmac class is a utility for creating cryptographic HMAC digests. It can be used in one of two ways: As a stream that is both readable and writable, where data is written to produce a computed HMAC digest on the readable side, or
41/145
hmac.digest([encoding])
encoding <string> The encoding of the return value. Returns: <Buffer> | <string> Calculates the HMAC digest of all of the data passed using hmac.update(). If encoding is provided a string is returned; otherwise a Buffer is returned;
42/145
hmac.update(data[, inputEncoding])
data <string> | <Buffer> | <TypedArray> | <DataView> inputEncoding <string> The encoding of the data string. This can be called many times with new data as it is streamed.
43/145
Class: KeyObject
Node.js uses a KeyObject class to represent a symmetric or asymmetric key, and each kind of key exposes different functions. The crypto.createSecretKey(), crypto.createPublicKey() and crypto.createPrivateKey() methods are used to create KeyObject instances. KeyObject objects are not to be created directly using the new keyword.
44/145
Static method: KeyObject.from(key)
key <CryptoKey> Returns: <KeyObject> Example: Converting a CryptoKey instance to a KeyObject:

KeyObject.from(key) converts a Web Crypto CryptoKey to a Node.js KeyObject. The result represents the same key material in the Node crypto API. It does not generate a new key pair or turn a public key into a private key. Check the key type and permitted usages before selecting a signing, verification, or encryption operation.

45/145
keyObject.asymmetricKeyDetails
<Object> modulusLength: <number> Key size in bits (RSA, DSA). publicExponent: <bigint> Public exponent (RSA). 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 (EC).
46/145
keyObject.asymmetricKeyType
<string> For asymmetric keys, this property represents the type of the key. Supported key types are: 'rsa' (OID 1.2.840.113549.1.1.1) 'rsa-pss' (OID 1.2.840.113549.1.1.10) 'dsa' (OID 1.2.840.10040.4.1) 'ec' (OID 1.2.840.10045.2.1) 'x25519' (OID 1.3.101.110) 'x448' (OID 1.3.101.111)
47/145
keyObject.equals(otherKeyObject)
otherKeyObject: <KeyObject> A KeyObject with which to compare keyObject. Returns: <boolean> Returns true or false depending on whether the keys have exactly the same type, value, and parameters. This method is not constant time.
48/145
keyObject.export([options])
options: <Object> Returns: <string> | <Buffer> | <Object> For symmetric keys, the following encoding options can be used: format: <string> Must be 'buffer' (default) or 'jwk'. For public keys, the following encoding options can be used:
49/145
keyObject.symmetricKeySize
<number> For secret keys, this property represents the size of the key in bytes. This property is undefined for asymmetric keys.

keyObject.symmetricKeySize is the size of a secret key in bytes. It applies to a symmetric KeyObject, not a public or private key. Compare the byte count with the selected algorithm’s key-length requirement. The property reports size; it does not reveal or export the key bytes.

50/145
keyObject.toCryptoKey(algorithm, extractable, keyUsages)
lint disable maximum-line-length remark-lint algorithm: <AlgorithmIdentifier> | <RsaHashedImportParams> | <EcKeyImportParams> | <HmacImportParams> lint enable maximum-line-length remark-lint extractable: <boolean> Returns: <CryptoKey>

keyObject.toCryptoKey(algorithm, extractable, keyUsages) converts a Node.js KeyObject to a Web Crypto CryptoKey. The algorithm identifies how the key will be used, extractable controls whether it can be exported, and keyUsages lists permitted operations. The method does not change a secret key into a public key.

51/145
keyObject.type
<string> Depending on the type of this KeyObject, this property is either 'secret' for secret (symmetric) keys, 'public' for public (asymmetric) keys or 'private' for private (asymmetric) keys.

keyObject.type is secret for a symmetric key, public for a public asymmetric key, or private for a private asymmetric key. This type helps select appropriate operations: a private key can sign, while a corresponding public key can verify. The property describes the key category, not its algorithm or byte length.

52/145
Class: Sign
Extends: <stream.Writable> The Sign class is a utility for generating signatures. It can be used in one of two ways: As a writable stream, where data to be signed is written and the sign.sign() method is used to generate and return the signature, or
53/145
sign.sign(privateKey[, outputEncoding])
lint disable maximum-line-length remark-lint outputEncoding <string> The encoding of the return value. Returns: <Buffer> | <string> lint enable maximum-line-length remark-lint If outputEncoding is provided a string is returned; otherwise a Buffer is returned.
54/145
sign.update(data[, inputEncoding])
data <string> | <Buffer> | <TypedArray> | <DataView> inputEncoding <string> The encoding of the data string. This can be called many times with new data as it is streamed.
55/145
Class: Verify
Extends: <stream.Writable> The Verify class is a utility for verifying signatures. It can be used in one of two ways: As a writable stream where written data is used to validate against the supplied signature, or See Sign for examples.
56/145
verify.update(data[, inputEncoding])
data <string> | <Buffer> | <TypedArray> | <DataView> inputEncoding <string> The encoding of the data string. This can be called many times with new data as it is streamed.
57/145
verify.verify(object, signature[, signatureEncoding])
lint disable maximum-line-length remark-lint signature <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> signatureEncoding <string> The encoding of the signature string. lint enable maximum-line-length remark-lint
58/145
Class: X509Certificate
Encapsulates an X509 certificate and provides read-only access to its information.

X509Certificate is Node.js’s parsed representation of an X.509 certificate. It exposes identity, issuer, validity, public-key, and fingerprint information. Methods can check names or verify a signature with a candidate issuer key. A complete trust decision still needs chain validation and an appropriate trust store.

59/145
new X509Certificate(buffer)
buffer <string> | <TypedArray> | <Buffer> | <DataView> A PEM or DER encoded X509 Certificate.

new X509Certificate(buffer) parses a PEM- or DER-encoded X.509 certificate from a string or byte-oriented input. The resulting object exposes fields such as subject, issuer, publicKey, and validity dates. Constructing the object parses data; it does not by itself verify that a certificate is trusted or matches a hostname.

60/145
x509.ca
Type: <boolean> Will be true if this is a Certificate Authority (CA) certificate.

x509.ca is a boolean indicating whether the X.509 certificate is marked as a certificate-authority certificate. A CA certificate may issue other certificates. This flag alone does not establish that the certificate is trusted; a verifier must also validate signatures, dates, names, and the certificate chain under its trust policy.

61/145
x509.checkEmail(email[, options])
email <string> options <Object> subject <string> 'default', 'always', or 'never'. Default: 'default'. Returns: <string> | <undefined> Returns email if the certificate matches, undefined if it does not.
62/145
x509.checkHost(name[, options])
name <string> Returns: <string> | <undefined> Returns a subject name that matches name, or undefined if no subject name matches name. Checks whether the certificate matches the given host name.
63/145
x509.checkIP(ip)
ip <string> Returns: <string> | <undefined> Returns ip if the certificate matches, undefined if it does not. Checks whether the certificate matches the given IP address (IPv4 or IPv6).
64/145
x509.checkIssued(otherCert)
otherCert <X509Certificate> Returns: <boolean> Checks whether this certificate was issued by the given otherCert.

x509.checkIssued(otherCert) compares certificate metadata to decide whether otherCert could be this certificate’s issuer. A true result narrows candidate issuers; it is not proof that the issuer signed the certificate. Verify the signature with x509.verify(otherCert.publicKey) and apply the rest of the certificate validation policy.

65/145
x509.checkPrivateKey(privateKey)
privateKey <KeyObject> A private key. Returns: <boolean> Checks whether the public key for this certificate is consistent with the given private key.

x509.checkPrivateKey(privateKey) returns a boolean indicating whether the supplied private KeyObject corresponds to the public key in the certificate. This is useful when loading a certificate and private key together. It does not check whether the certificate is trusted, within its validity period, or appropriate for a hostname.

66/145
x509.keyUsage

x509.keyUsage returns an array of strings describing the certificate’s extended key usages. The values can indicate purposes such as server authentication or client authentication, depending on the certificate. The property describes an extension; it does not establish certificate trust.

Use the current Node.js property name keyUsage. The older extKeyUsage name in this card is not part of the current documented X509Certificate API. Validate the certificate chain, signature, names, and dates separately.

67/145
x509.fingerprint
Type: <string> The SHA-1 fingerprint of this certificate. Because SHA-1 is cryptographically broken and because the security of SHA-1 is significantly worse than that of algorithms that are commonly used to sign certificates, consider using x509.fingerprint256 instead.
68/145
x509.fingerprint256
Type: <string> The SHA-256 fingerprint of this certificate.

x509.fingerprint256 is the SHA-256 digest of the certificate represented as a fingerprint string. It can help identify a specific certificate. Compare x509.fingerprint, which uses SHA-1 and is weaker. A matching fingerprint identifies the certificate bytes but does not alone validate its trust chain or hostname.

69/145
x509.fingerprint512
Type: <string> The SHA-512 fingerprint of this certificate.
70/145
x509.infoAccess
Type: <string> A textual representation of the certificate's authority information access extension.
71/145
x509.issuer
Type: <string> The issuer identification included in this certificate.

x509.issuer is a string containing the issuer identification recorded in the certificate. It names the entity that claims to have issued the certificate. A name match does not prove the issuer signed it; signature and chain validation are separate checks. Compare x509.subject for the identity represented by this certificate.

72/145
x509.issuerCertificate
Type: <X509Certificate> The issuer certificate or undefined if the issuer certificate is not available.

x509.issuerCertificate contains an X509Certificate object for the issuer when that certificate is available, or undefined otherwise. It can help inspect a supplied chain. Availability of an issuer object does not by itself establish trust; verify the signature and evaluate the chain against trusted roots.

73/145
x509.publicKey
Type: <KeyObject> The public key <KeyObject> for this certificate.

x509.publicKey is a KeyObject containing the certificate’s public key. It can be used for supported verification operations. It is not the corresponding private key and cannot be used to sign as the certificate holder. The certificate’s issuer key is a different key used to verify the certificate signature.

74/145
x509.raw
Type: <Buffer> A Buffer containing the DER encoding of this certificate.

x509.raw is a Buffer containing the certificate’s DER-encoded bytes. DER is a binary representation; x509.toString() returns PEM text instead. The raw bytes can be stored or hashed, but reading them does not validate certificate trust, dates, or subject names.

75/145
x509.serialNumber
Type: <string> The serial number of this certificate. Serial numbers are assigned by certificate authorities and do not uniquely identify certificates. Consider using x509.fingerprint256 as a unique identifier instead.
76/145
x509.subject
Type: <string> The complete subject of this certificate.

x509.subject is a string describing the entity identified by the certificate. It is distinct from x509.issuer, which describes the claimed issuing entity. For TLS hostname checks, use x509.checkHost() or a complete TLS verifier rather than comparing an arbitrary subject substring.

77/145
x509.subjectAltName
Type: <string> The subject alternative name specified for this certificate. This is a comma-separated list of subject alternative names. Each entry begins with a string identifying the kind of the subject alternative name followed by a colon and the value associated with the entry.
78/145
x509.toJSON()
Type: <string> There is no standard JSON encoding for X509 certificates. The toJSON() method returns a string containing the PEM encoded certificate.

x509.toJSON() returns a string containing the PEM-encoded certificate. There is no standard JSON object encoding for an X.509 certificate in this method. JSON.stringify() can use the method during serialization. The returned text represents the certificate; it is not a validation result.

79/145
x509.toLegacyObject()
Type: <Object> Returns information about this certificate using the legacy certificate object encoding.

x509.toLegacyObject() returns an object using Node.js’s older certificate information format. It is mainly useful for compatibility with code expecting that shape. For new code, the X509Certificate properties expose fields directly. The legacy object is descriptive data, not proof that the certificate is trusted.

80/145
x509.toString()
Type: <string> Returns the PEM-encoded certificate.

x509.toString() returns the certificate as PEM-encoded text. PEM wraps encoded certificate bytes in a textual form suitable for files and transport. x509.raw instead provides DER bytes. Serializing a certificate does not verify its trust chain or whether a name matches a server.

81/145
x509.validFrom
Type: <string> The date/time from which this certificate is valid.

x509.validFrom is a string describing the start of the certificate’s validity period. x509.validFromDate exposes the same boundary as a Date object in supported Node.js versions. A certificate is not valid before this time; the end boundary is x509.validTo. Valid dates alone do not establish trust.

82/145
x509.validFromDate
Type: <Date> The date/time from which this certificate is valid, encapsulated in a Date object.

x509.validFromDate is a Date object representing when the certificate begins to be valid. It is the structured-date counterpart to the string-valued x509.validFrom. Compare it with the current time and x509.validToDate to inspect the validity interval. This property does not verify the issuer or hostname.

83/145
x509.validTo
Type: <string> The date/time until which this certificate is valid.

x509.validTo is a string describing the end of the certificate’s validity period. x509.validToDate exposes that boundary as a Date object in supported Node.js versions. Compare the current time with both validFrom and validTo. A certificate within its dates is not automatically trusted.

84/145
x509.validToDate
Type: <Date> The date/time until which this certificate is valid, encapsulated in a Date object.

x509.validToDate is a Date object representing the end of the certificate’s validity interval. It corresponds to the string-valued x509.validTo. A certificate is expired after this boundary. Checking dates is only one part of validation; issuer signatures, chain trust, and names also matter.

85/145
x509.verify(publicKey)
publicKey <KeyObject> A public key. Returns: <boolean> Verifies that this certificate was signed by the given public key. Does not perform any other validation checks on the certificate.

x509.verify(publicKey) checks whether the certificate signature verifies under the supplied public KeyObject. For a candidate issuer, use that issuer certificate’s publicKey. A true result checks the signature, but a full certificate decision also requires name, validity, chain, and trust-policy checks.

86/145
crypto.checkPrime(candidate[, options], callback)
candidate <ArrayBuffer> | <SharedArrayBuffer> | <TypedArray> | <Buffer> | <DataView> | <bigint> A possible prime encoded as a sequence of big endian octets of arbitrary length. Checks the primality of the candidate.
87/145
crypto.checkPrimeSync(candidate[, options])
candidate <ArrayBuffer> | <SharedArrayBuffer> | <TypedArray> | <Buffer> | <DataView> | <bigint> A possible prime encoded as a sequence of big endian octets of arbitrary length. Checks the primality of the candidate.
88/145
crypto.constants
<Object> An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in Crypto constants.

crypto.constants exposes named constants used by Node.js cryptographic APIs, including option flags inherited from OpenSSL. Read the API’s documented option before choosing one; a constant value alone does not select a secure algorithm. The set of constants can depend on the Node.js and OpenSSL build.

89/145
crypto.createCipheriv(algorithm, key, iv[, options])
algorithm <string> key <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey> options <Object> stream.transform options Returns: <Cipher>
90/145
crypto.createDecipheriv(algorithm, key, iv[, options])
algorithm <string> key <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey> options <Object> stream.transform options Returns: <Decipher>
91/145
crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])
prime <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> primeEncoding <string> The encoding of the prime string. generatorEncoding <string> The encoding of the generator string.
92/145
crypto.createDiffieHellman(primeLength[, generator])
primeLength <number> generator <number> Default: 2 Returns: <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.
93/145
crypto.createDiffieHellmanGroup(name)
name <string> Returns: <DiffieHellmanGroup> An alias for crypto.getDiffieHellman()

crypto.createDiffieHellmanGroup(name) creates a DiffieHellmanGroup for a named, predefined modular group. Both peers must use compatible group parameters before computing a shared secret. The returned object supports key generation and agreement. Key agreement alone does not authenticate a peer or derive a final application key.

94/145
crypto.createECDH(curveName)
curveName <string> Returns: <ECDH>
95/145
crypto.createHash(algorithm[, options])
algorithm <string> options <Object> stream.transform options Returns: <Hash> Example: generating the sha256 sum of a file
96/145
crypto.createHmac(algorithm, key[, options])
algorithm <string> key <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey> Returns: <Hmac> Example: generating the sha256 HMAC of a file
97/145
crypto.createPrivateKey(key)
lint disable maximum-line-length remark-lint Returns: <KeyObject> lint enable maximum-line-length remark-lint If the private key is encrypted, a passphrase must be specified. The length of the passphrase is limited to 1024 bytes.
98/145
crypto.createPublicKey(key)
lint disable maximum-line-length remark-lint Returns: <KeyObject> lint enable maximum-line-length remark-lint If the format is 'pem', the 'key' may also be an X.509 certificate.
99/145
crypto.createSecretKey(key[, encoding])
key <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> encoding <string> The string encoding when key is a string. Returns: <KeyObject>
100/145
crypto.createSign(algorithm[, options])
algorithm <string> options <Object> stream.Writable options Returns: <Sign>
101/145
crypto.createVerify(algorithm[, options])
algorithm <string> options <Object> stream.Writable options Returns: <Verify>
102/145
crypto.diffieHellman(options)
options: <Object> privateKey: <KeyObject> publicKey: <KeyObject> Returns: <Buffer>
103/145
crypto.generateKey(type, options, callback)
type: <string> The intended use of the generated secret key. Currently accepted values are 'hmac' and 'aes'. callback: <Function> err: <Error> key: <KeyObject>
104/145
crypto.generateKeyPair(type, options, callback)
type: <string> Must be 'rsa', 'rsa-pss', 'dsa', 'ec', 'ed25519', 'ed448', 'x25519', 'x448', or 'dh'. Generates a new asymmetric key pair of the given type. RSA, RSA-PSS, DSA, EC, Ed25519, Ed448, X25519, X448, and DH are currently supported.
105/145
crypto.generateKeyPairSync(type, options)
type: <string> Must be 'rsa', 'rsa-pss', 'dsa', 'ec', 'ed25519', 'ed448', 'x25519', 'x448', or 'dh'. Generates a new asymmetric key pair of the given type. RSA, RSA-PSS, DSA, EC, Ed25519, Ed448, X25519, X448, and DH are currently supported.
106/145
crypto.generateKeySync(type, options)
type: <string> The intended use of the generated secret key. Currently accepted values are 'hmac' and 'aes'. Returns: <KeyObject>
107/145
crypto.generatePrime(size[, options[, callback]])
size <number> The size (in bits) of the prime to generate. callback <Function> err <Error> prime <ArrayBuffer> | <bigint> Generates a pseudorandom prime of size bits.
108/145
crypto.generatePrimeSync(size[, options])
size <number> The size (in bits) of the prime to generate. Returns: <ArrayBuffer> | <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.
109/145
crypto.getCipherInfo(nameOrNid[, options])
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.
110/145
crypto.getCiphers()
Returns: <string[]> An array with the names of the supported cipher algorithms.

crypto.getCiphers() returns cipher algorithm names supported by the current crypto implementation. The list can vary with OpenSSL providers and configuration. A listed cipher is not automatically a safe choice; the mode, key, IV or nonce handling, and authentication requirements matter.

111/145
crypto.getCurves()
Returns: <string[]> An array with the names of the supported elliptic curves.

crypto.getCurves() returns elliptic-curve names available to the current crypto implementation. A name can be used when creating an ECDH instance where supported. Availability does not by itself imply that a curve is appropriate for a particular protocol; peers must use compatible parameters.

112/145
crypto.getDiffieHellman(groupName)
groupName <string> Returns: <DiffieHellmanGroup> Creates a predefined DiffieHellmanGroup key exchange object. The supported groups are listed in the documentation for DiffieHellmanGroup. Example (obtaining a shared secret):
113/145
crypto.getFips()
Returns: <number> 1 if and only if a FIPS compliant crypto provider is currently in use, 0 otherwise. A future semver-major release may change the return type of this API to a <boolean>.

crypto.getFips() reports the FIPS property-query state: 1 when enabled and 0 otherwise. On OpenSSL 3, a value of 1 does not prove that a FIPS provider is loaded, initialized, or validated. Check the provider configuration separately and do not treat the mode flag as application certification.

114/145
crypto.getHashes()
Returns: <string[]> An array of the names of the supported hash algorithms, such as 'RSA-SHA256'. Hash algorithms are also called "digest" algorithms.

crypto.getHashes() returns an array of hash algorithm names supported by the current OpenSSL-backed runtime. Availability can differ between builds and provider configurations. A listed algorithm is not necessarily suitable for security-sensitive uses; choose a current algorithm according to the application’s requirements.

115/145
crypto.getRandomValues(typedArray)
typedArray <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> Returns: <Buffer> | <TypedArray> | <DataView> | <ArrayBuffer> Returns typedArray.
116/145
crypto.hash(algorithm, data[, outputEncoding])
algorithm <string> | <undefined> outputEncoding <string> | <undefined> Encoding used to encode the returned digest. Default: 'hex'. Returns: <string> | <Buffer> Example:
117/145
crypto.hkdf(digest, ikm, salt, info, keylen, callback)
digest <string> The digest algorithm to use. ikm <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> The input keying material. Must be provided but can be zero-length.
118/145
crypto.hkdfSync(digest, ikm, salt, info, keylen)
digest <string> The digest algorithm to use. ikm <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> The input keying material. Must be provided but can be zero-length.
119/145
crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)
password <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> salt <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> iterations <number>
120/145
crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)
password <string> | <Buffer> | <TypedArray> | <DataView> salt <string> | <Buffer> | <TypedArray> | <DataView> iterations <number> keylen <number> digest <string> Returns: <Buffer>
121/145
crypto.privateDecrypt(privateKey, buffer)
lint disable maximum-line-length remark-lint buffer <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> Returns: <Buffer> A new Buffer with the decrypted content. lint enable maximum-line-length remark-lint
122/145
crypto.privateEncrypt(privateKey, buffer)
lint disable maximum-line-length remark-lint buffer <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> Returns: <Buffer> A new Buffer with the encrypted content. lint enable maximum-line-length remark-lint
123/145
crypto.publicDecrypt(key, buffer)
lint disable maximum-line-length remark-lint buffer <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> Returns: <Buffer> A new Buffer with the decrypted content. lint enable maximum-line-length remark-lint
124/145
crypto.publicEncrypt(key, buffer)
lint disable maximum-line-length remark-lint buffer <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> Returns: <Buffer> A new Buffer with the encrypted content. lint enable maximum-line-length remark-lint
125/145
crypto.randomBytes(size[, callback])
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.
126/145
crypto.randomFill(buffer[, offset][, size], callback)
buffer <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> Must be supplied. The size of the provided buffer must not be larger than 2**31 - 1. offset <number> Default: 0 callback <Function> function(err, buf) {}.
127/145
crypto.randomFillSync(buffer[, offset][, size])
buffer <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> Must be supplied. The size of the provided buffer must not be larger than 2**31 - 1. offset <number> Default: 0 Synchronous version of crypto.randomFill().
128/145
crypto.randomInt([min, ]max[, callback])
min <integer> Start of random range (inclusive). Default: 0. max <integer> End of random range (exclusive). callback <Function> function(err, n) {}. The range (max - min) must be less than 248. min and max must be safe integers.
129/145
crypto.randomUUID([options])
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.
130/145
crypto.scrypt(password, salt, keylen[, options], callback)
password <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> salt <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> keylen <number>
131/145
crypto.scryptSync(password, salt, keylen[, options])
password <string> | <Buffer> | <TypedArray> | <DataView> salt <string> | <Buffer> | <TypedArray> | <DataView> keylen <number> Returns: <Buffer>
132/145
crypto.secureHeapUsed()
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.
133/145
crypto.setEngine(engine[, flags])
engine <string> flags <crypto.constants> 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. crypto.constants.ENGINE_METHOD_RSA

crypto.setEngine(engine, flags) loads and selects a legacy OpenSSL engine for selected operation classes. The engine argument can be an identifier or shared-library path. Custom engine support is deprecated with OpenSSL 3; provider-based configuration is preferred for new deployments. This operation changes configuration and does not return an engine object.

134/145
crypto.setFips(bool)
bool <boolean> true to enable FIPS mode. Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available.

crypto.setFips(bool) changes the FIPS property-query state, with true requesting FIPS mode and false disabling it. On OpenSSL 3, this call does not install, load, or validate a FIPS provider. crypto.getFips() reporting 1 alone is not proof of a compliant configuration; provider setup and validation are separate.

135/145
crypto.sign(algorithm, data, key[, callback])
lint disable maximum-line-length remark-lint algorithm <string> | <null> | <undefined> data <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> Returns: <Buffer> if the callback function is not provided.
136/145
crypto.subtle

Type: <SubtleCrypto>

A convenient alias for crypto.webcrypto.subtle.

crypto.subtle is an alias for crypto.webcrypto.subtle, the SubtleCrypto interface of the Web Crypto API. It provides Promise-based methods for operations such as digest, key generation, signing, and encryption where the selected algorithm supports them. Use the correct CryptoKey usages and algorithm parameters.

137/145
crypto.timingSafeEqual

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

138/145
crypto.verify(algorithm, data, key, signature[, callback])
lint disable maximum-line-length remark-lint algorithm <string> | <null> | <undefined> data <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> lint enable maximum-line-length remark-lint
139/145
crypto.webcrypto
Type: <Crypto> An implementation of the Web Crypto API standard. See the Web Crypto API documentation for details.

crypto.webcrypto exposes Node.js’s implementation of the Web Crypto API. Its subtle property provides Promise-based cryptographic operations and its getRandomValues method fills supported typed arrays with random values. It is related to browser Web Crypto, but check runtime support and algorithm parameters before moving code between environments.

140/145
Using strings as inputs to cryptographic APIs

For historical reasons, many cryptographic APIs provided by Node.js accept strings as inputs where the underlying cryptographic algorithm works on byte sequences.

141/145
Legacy streams API (prior to Node.js 0.10)

The Crypto module was added to Node.js before there was the concept of a unified Stream API, and before there were Buffer objects for handling binary data.

142/145
Support for weak or compromised algorithms

The node:crypto module still supports some algorithms which are already compromised and are not recommended for use.

143/145
CCM mode

CCM is one of the supported AEAD algorithms.

144/145
FIPS mode

When using OpenSSL 3, Node.js supports FIPS 140-2 when used with an appropriate OpenSSL 3 provider, such as the FIPS provider from OpenSSL 3 which can be installed by following the instructions in OpenSSL's FIPS README file.

FIPS operation requires a suitable Node.js and OpenSSL configuration with the intended FIPS provider loaded and validated. crypto.setFips(true) changes a default property query on OpenSSL 3; it does not install, load, initialize, or validate the provider. crypto.getFips() returning 1 reports mode state only, not application certification.

145/145