Crypto#

Stability: 2 - Stable

Source Code:lib/crypto.js

Thenode:crypto module provides cryptographic functionality that includes aset of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verifyfunctions.

const { createHmac } =awaitimport('node:crypto');const secret ='abcdefg';const hash =createHmac('sha256', secret)               .update('I love cupcakes')               .digest('hex');console.log(hash);// Prints://   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658econst { createHmac } =require('node:crypto');const secret ='abcdefg';const hash =createHmac('sha256', secret)               .update('I love cupcakes')               .digest('hex');console.log(hash);// Prints://   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e

Determining if crypto support is unavailable#

It is possible for Node.js to be built without including support for thenode:crypto module. In such cases, attempting toimport fromcrypto orcallingrequire('node:crypto') will result in an error being thrown.

When using CommonJS, the error thrown can be caught using try/catch:

let crypto;try {  crypto =require('node:crypto');}catch (err) {console.error('crypto support is disabled!');}

When using the lexical ESMimport keyword, the error can only becaught if a handler forprocess.on('uncaughtException') is registeredbefore any attempt to load the module is made (using, for instance,a preload module).

When using ESM, if there is a chance that the code may be run on a buildof Node.js where crypto support is not enabled, consider using theimport() function instead of the lexicalimport keyword:

let crypto;try {  crypto =awaitimport('node:crypto');}catch (err) {console.error('crypto support is disabled!');}

Class:Certificate#

Added in: v0.11.8

SPKAC is a Certificate Signing Request mechanism originally implemented byNetscape and was specified formally as part of HTML5'skeygen element.

<keygen> is deprecated sinceHTML 5.2 and new projectsshould not use this element anymore.

Thenode:crypto module provides theCertificate class for working with SPKACdata. The most common usage is handling output generated by the HTML5<keygen> element. Node.js usesOpenSSL's SPKAC implementation internally.

Static method:Certificate.exportChallenge(spkac[, encoding])#

History
VersionChanges
v15.0.0

The spkac argument can be an ArrayBuffer. Limited the size of the spkac argument to a maximum of 2**31 - 1 bytes.

v9.0.0

Added in: v9.0.0

const {Certificate } =awaitimport('node:crypto');const spkac =getSpkacSomehow();const challenge =Certificate.exportChallenge(spkac);console.log(challenge.toString('utf8'));// Prints: the challenge as a UTF8 stringconst {Certificate } =require('node:crypto');const spkac =getSpkacSomehow();const challenge =Certificate.exportChallenge(spkac);console.log(challenge.toString('utf8'));// Prints: the challenge as a UTF8 string

Static method:Certificate.exportPublicKey(spkac[, encoding])#

History
VersionChanges
v15.0.0

The spkac argument can be an ArrayBuffer. Limited the size of the spkac argument to a maximum of 2**31 - 1 bytes.

v9.0.0

Added in: v9.0.0

const {Certificate } =awaitimport('node:crypto');const spkac =getSpkacSomehow();const publicKey =Certificate.exportPublicKey(spkac);console.log(publicKey);// Prints: the public key as <Buffer ...>const {Certificate } =require('node:crypto');const spkac =getSpkacSomehow();const publicKey =Certificate.exportPublicKey(spkac);console.log(publicKey);// Prints: the public key as <Buffer ...>

Static method:Certificate.verifySpkac(spkac[, encoding])#

History
VersionChanges
v15.0.0

The spkac argument can be an ArrayBuffer. Added encoding. Limited the size of the spkac argument to a maximum of 2**31 - 1 bytes.

v9.0.0

Added in: v9.0.0

import {Buffer }from'node:buffer';const {Certificate } =awaitimport('node:crypto');const spkac =getSpkacSomehow();console.log(Certificate.verifySpkac(Buffer.from(spkac)));// Prints: true or falseconst {Buffer } =require('node:buffer');const {Certificate } =require('node:crypto');const spkac =getSpkacSomehow();console.log(Certificate.verifySpkac(Buffer.from(spkac)));// Prints: true or false

Legacy API#

Stability: 0 - Deprecated

As a legacy interface, it is possible to create new instances ofthecrypto.Certificate class as illustrated in the examples below.

new crypto.Certificate()#

Instances of theCertificate class can be created using thenew keywordor by callingcrypto.Certificate() as a function:

const {Certificate } =awaitimport('node:crypto');const cert1 =newCertificate();const cert2 =Certificate();const {Certificate } =require('node:crypto');const cert1 =newCertificate();const cert2 =Certificate();
certificate.exportChallenge(spkac[, encoding])#
Added in: v0.11.8
const {Certificate } =awaitimport('node:crypto');const cert =Certificate();const spkac =getSpkacSomehow();const challenge = cert.exportChallenge(spkac);console.log(challenge.toString('utf8'));// Prints: the challenge as a UTF8 stringconst {Certificate } =require('node:crypto');const cert =Certificate();const spkac =getSpkacSomehow();const challenge = cert.exportChallenge(spkac);console.log(challenge.toString('utf8'));// Prints: the challenge as a UTF8 string
certificate.exportPublicKey(spkac[, encoding])#
Added in: v0.11.8
const {Certificate } =awaitimport('node:crypto');const cert =Certificate();const spkac =getSpkacSomehow();const publicKey = cert.exportPublicKey(spkac);console.log(publicKey);// Prints: the public key as <Buffer ...>const {Certificate } =require('node:crypto');const cert =Certificate();const spkac =getSpkacSomehow();const publicKey = cert.exportPublicKey(spkac);console.log(publicKey);// Prints: the public key as <Buffer ...>
certificate.verifySpkac(spkac[, encoding])#
Added in: v0.11.8
import {Buffer }from'node:buffer';const {Certificate } =awaitimport('node:crypto');const cert =Certificate();const spkac =getSpkacSomehow();console.log(cert.verifySpkac(Buffer.from(spkac)));// Prints: true or falseconst {Buffer } =require('node:buffer');const {Certificate } =require('node:crypto');const cert =Certificate();const spkac =getSpkacSomehow();console.log(cert.verifySpkac(Buffer.from(spkac)));// Prints: true or false

Class:Cipheriv#

Added in: v0.1.94

Instances of theCipheriv class are used to encrypt data. The class can beused in one of two ways:

  • As astream that is both readable and writable, where plain unencrypteddata is written to produce encrypted data on the readable side, or
  • Using thecipher.update() andcipher.final() methods to producethe encrypted data.

Thecrypto.createCipheriv() method isused to createCipheriv instances.Cipheriv objects are not to be createddirectly using thenew keyword.

Example: UsingCipheriv objects as streams:

const {  scrypt,  randomFill,  createCipheriv,} =awaitimport('node:crypto');const algorithm ='aes-192-cbc';const password ='Password used to generate key';// First, we'll generate the key. The key length is dependent on the algorithm.// In this case for aes192, it is 24 bytes (192 bits).scrypt(password,'salt',24,(err, key) => {if (err)throw err;// Then, we'll generate a random initialization vectorrandomFill(newUint8Array(16),(err, iv) => {if (err)throw err;// Once we have the key and iv, we can create and use the cipher...const cipher =createCipheriv(algorithm, key, iv);let encrypted ='';    cipher.setEncoding('hex');    cipher.on('data',(chunk) => encrypted += chunk);    cipher.on('end',() =>console.log(encrypted));    cipher.write('some clear text data');    cipher.end();  });});const {  scrypt,  randomFill,  createCipheriv,} =require('node:crypto');const algorithm ='aes-192-cbc';const password ='Password used to generate key';// First, we'll generate the key. The key length is dependent on the algorithm.// In this case for aes192, it is 24 bytes (192 bits).scrypt(password,'salt',24,(err, key) => {if (err)throw err;// Then, we'll generate a random initialization vectorrandomFill(newUint8Array(16),(err, iv) => {if (err)throw err;// Once we have the key and iv, we can create and use the cipher...const cipher =createCipheriv(algorithm, key, iv);let encrypted ='';    cipher.setEncoding('hex');    cipher.on('data',(chunk) => encrypted += chunk);    cipher.on('end',() =>console.log(encrypted));    cipher.write('some clear text data');    cipher.end();  });});

Example: UsingCipheriv and piped streams:

import {  createReadStream,  createWriteStream,}from'node:fs';import {  pipeline,}from'node:stream';const {  scrypt,  randomFill,  createCipheriv,} =awaitimport('node:crypto');const algorithm ='aes-192-cbc';const password ='Password used to generate key';// First, we'll generate the key. The key length is dependent on the algorithm.// In this case for aes192, it is 24 bytes (192 bits).scrypt(password,'salt',24,(err, key) => {if (err)throw err;// Then, we'll generate a random initialization vectorrandomFill(newUint8Array(16),(err, iv) => {if (err)throw err;const cipher =createCipheriv(algorithm, key, iv);const input =createReadStream('test.js');const output =createWriteStream('test.enc');pipeline(input, cipher, output,(err) => {if (err)throw err;    });  });});const {  createReadStream,  createWriteStream,} =require('node:fs');const {  pipeline,} =require('node:stream');const {  scrypt,  randomFill,  createCipheriv,} =require('node:crypto');const algorithm ='aes-192-cbc';const password ='Password used to generate key';// First, we'll generate the key. The key length is dependent on the algorithm.// In this case for aes192, it is 24 bytes (192 bits).scrypt(password,'salt',24,(err, key) => {if (err)throw err;// Then, we'll generate a random initialization vectorrandomFill(newUint8Array(16),(err, iv) => {if (err)throw err;const cipher =createCipheriv(algorithm, key, iv);const input =createReadStream('test.js');const output =createWriteStream('test.enc');pipeline(input, cipher, output,(err) => {if (err)throw err;    });  });});

Example: Using thecipher.update() andcipher.final() methods:

const {  scrypt,  randomFill,  createCipheriv,} =awaitimport('node:crypto');const algorithm ='aes-192-cbc';const password ='Password used to generate key';// First, we'll generate the key. The key length is dependent on the algorithm.// In this case for aes192, it is 24 bytes (192 bits).scrypt(password,'salt',24,(err, key) => {if (err)throw err;// Then, we'll generate a random initialization vectorrandomFill(newUint8Array(16),(err, iv) => {if (err)throw err;const cipher =createCipheriv(algorithm, key, iv);let encrypted = cipher.update('some clear text data','utf8','hex');    encrypted += cipher.final('hex');console.log(encrypted);  });});const {  scrypt,  randomFill,  createCipheriv,} =require('node:crypto');const algorithm ='aes-192-cbc';const password ='Password used to generate key';// First, we'll generate the key. The key length is dependent on the algorithm.// In this case for aes192, it is 24 bytes (192 bits).scrypt(password,'salt',24,(err, key) => {if (err)throw err;// Then, we'll generate a random initialization vectorrandomFill(newUint8Array(16),(err, iv) => {if (err)throw err;const cipher =createCipheriv(algorithm, key, iv);let encrypted = cipher.update('some clear text data','utf8','hex');    encrypted += cipher.final('hex');console.log(encrypted);  });});

cipher.final([outputEncoding])#

Added in: v0.1.94
  • outputEncoding<string> Theencoding of the return value.
  • Returns:<Buffer> |<string> Any remaining enciphered contents.IfoutputEncoding is specified, a string isreturned. If anoutputEncoding is not provided, aBuffer is returned.

Once thecipher.final() method has been called, theCipheriv object can nolonger be used to encrypt data. Attempts to callcipher.final() more thanonce will result in an error being thrown.

cipher.getAuthTag()#

Added in: v1.0.0
  • Returns:<Buffer> When using an authenticated encryption mode (GCM,CCM,OCB, andchacha20-poly1305 are currently supported), thecipher.getAuthTag() method returns aBuffer containing theauthentication tag that has been computed fromthe given data.

Thecipher.getAuthTag() method should only be called after encryption hasbeen completed using thecipher.final() method.

If theauthTagLength option was set during thecipher instance's creation,this function will return exactlyauthTagLength bytes.

cipher.setAAD(buffer[, options])#

Added in: v1.0.0

When using an authenticated encryption mode (GCM,CCM,OCB, andchacha20-poly1305 arecurrently supported), thecipher.setAAD() method sets the value used for theadditional authenticated data (AAD) input parameter.

TheplaintextLength option is optional forGCM andOCB. When usingCCM,theplaintextLength option must be specified and its value must match thelength of the plaintext in bytes. SeeCCM mode.

Thecipher.setAAD() method must be called beforecipher.update().

cipher.setAutoPadding([autoPadding])#

Added in: v0.7.1
  • autoPadding<boolean>Default:true
  • Returns:<Cipheriv> The sameCipheriv instance for method chaining.

When using block encryption algorithms, theCipheriv class will automaticallyadd padding to the input data to the appropriate block size. To disable thedefault padding callcipher.setAutoPadding(false).

WhenautoPadding isfalse, the length of the entire input data must be amultiple of the cipher's block size orcipher.final() will throw an error.Disabling automatic padding is useful for non-standard padding, for instanceusing0x0 instead of PKCS padding.

Thecipher.setAutoPadding() method must be called beforecipher.final().

cipher.update(data[, inputEncoding][, outputEncoding])#

History
VersionChanges
v6.0.0

The defaultinputEncoding changed frombinary toutf8.

v0.1.94

Added in: v0.1.94

Updates the cipher withdata. If theinputEncoding argument is given,thedataargument is a string using the specified encoding. If theinputEncodingargument is not given,data must be aBuffer,TypedArray, orDataView. Ifdata is aBuffer,TypedArray, orDataView, theninputEncoding is ignored.

TheoutputEncoding specifies the output format of the enciphereddata. If theoutputEncodingis specified, a string using the specified encoding is returned. If nooutputEncoding is provided, aBuffer is returned.

Thecipher.update() method can be called multiple times with new data untilcipher.final() is called. Callingcipher.update() aftercipher.final() will result in an error being thrown.

Class:Decipheriv#

Added in: v0.1.94

Instances of theDecipheriv class are used to decrypt data. The class can beused in one of two ways:

  • As astream that is both readable and writable, where plain encrypteddata is written to produce unencrypted data on the readable side, or
  • Using thedecipher.update() anddecipher.final() methods toproduce the unencrypted data.

Thecrypto.createDecipheriv() method isused to createDecipheriv instances.Decipheriv objects are not to be createddirectly using thenew keyword.

Example: UsingDecipheriv objects as streams:

import {Buffer }from'node:buffer';const {  scryptSync,  createDecipheriv,} =awaitimport('node:crypto');const algorithm ='aes-192-cbc';const password ='Password used to generate key';// Key length is dependent on the algorithm. In this case for aes192, it is// 24 bytes (192 bits).// Use the async `crypto.scrypt()` instead.const key =scryptSync(password,'salt',24);// The IV is usually passed along with the ciphertext.const iv =Buffer.alloc(16,0);// Initialization vector.const decipher =createDecipheriv(algorithm, key, iv);let decrypted ='';decipher.on('readable',() => {let chunk;while (null !== (chunk = decipher.read())) {    decrypted += chunk.toString('utf8');  }});decipher.on('end',() => {console.log(decrypted);// Prints: some clear text data});// Encrypted with same algorithm, key and iv.const encrypted ='e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';decipher.write(encrypted,'hex');decipher.end();const {  scryptSync,  createDecipheriv,} =require('node:crypto');const {Buffer } =require('node:buffer');const algorithm ='aes-192-cbc';const password ='Password used to generate key';// Key length is dependent on the algorithm. In this case for aes192, it is// 24 bytes (192 bits).// Use the async `crypto.scrypt()` instead.const key =scryptSync(password,'salt',24);// The IV is usually passed along with the ciphertext.const iv =Buffer.alloc(16,0);// Initialization vector.const decipher =createDecipheriv(algorithm, key, iv);let decrypted ='';decipher.on('readable',() => {let chunk;while (null !== (chunk = decipher.read())) {    decrypted += chunk.toString('utf8');  }});decipher.on('end',() => {console.log(decrypted);// Prints: some clear text data});// Encrypted with same algorithm, key and iv.const encrypted ='e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';decipher.write(encrypted,'hex');decipher.end();

Example: UsingDecipheriv and piped streams:

import {  createReadStream,  createWriteStream,}from'node:fs';import {Buffer }from'node:buffer';const {  scryptSync,  createDecipheriv,} =awaitimport('node:crypto');const algorithm ='aes-192-cbc';const password ='Password used to generate key';// Use the async `crypto.scrypt()` instead.const key =scryptSync(password,'salt',24);// The IV is usually passed along with the ciphertext.const iv =Buffer.alloc(16,0);// Initialization vector.const decipher =createDecipheriv(algorithm, key, iv);const input =createReadStream('test.enc');const output =createWriteStream('test.js');input.pipe(decipher).pipe(output);const {  createReadStream,  createWriteStream,} =require('node:fs');const {  scryptSync,  createDecipheriv,} =require('node:crypto');const {Buffer } =require('node:buffer');const algorithm ='aes-192-cbc';const password ='Password used to generate key';// Use the async `crypto.scrypt()` instead.const key =scryptSync(password,'salt',24);// The IV is usually passed along with the ciphertext.const iv =Buffer.alloc(16,0);// Initialization vector.const decipher =createDecipheriv(algorithm, key, iv);const input =createReadStream('test.enc');const output =createWriteStream('test.js');input.pipe(decipher).pipe(output);

Example: Using thedecipher.update() anddecipher.final() methods:

import {Buffer }from'node:buffer';const {  scryptSync,  createDecipheriv,} =awaitimport('node:crypto');const algorithm ='aes-192-cbc';const password ='Password used to generate key';// Use the async `crypto.scrypt()` instead.const key =scryptSync(password,'salt',24);// The IV is usually passed along with the ciphertext.const iv =Buffer.alloc(16,0);// Initialization vector.const decipher =createDecipheriv(algorithm, key, iv);// Encrypted using same algorithm, key and iv.const encrypted ='e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';let decrypted = decipher.update(encrypted,'hex','utf8');decrypted += decipher.final('utf8');console.log(decrypted);// Prints: some clear text dataconst {  scryptSync,  createDecipheriv,} =require('node:crypto');const {Buffer } =require('node:buffer');const algorithm ='aes-192-cbc';const password ='Password used to generate key';// Use the async `crypto.scrypt()` instead.const key =scryptSync(password,'salt',24);// The IV is usually passed along with the ciphertext.const iv =Buffer.alloc(16,0);// Initialization vector.const decipher =createDecipheriv(algorithm, key, iv);// Encrypted using same algorithm, key and iv.const encrypted ='e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';let decrypted = decipher.update(encrypted,'hex','utf8');decrypted += decipher.final('utf8');console.log(decrypted);// Prints: some clear text data

decipher.final([outputEncoding])#

Added in: v0.1.94
  • outputEncoding<string> Theencoding of the return value.
  • Returns:<Buffer> |<string> Any remaining deciphered contents.IfoutputEncoding is specified, a string isreturned. If anoutputEncoding is not provided, aBuffer is returned.

Once thedecipher.final() method has been called, theDecipheriv object canno longer be used to decrypt data. Attempts to calldecipher.final() morethan once will result in an error being thrown.

decipher.setAAD(buffer[, options])#

History
VersionChanges
v15.0.0

The buffer argument can be a string or ArrayBuffer and is limited to no more than 2 ** 31 - 1 bytes.

v7.2.0

This method now returns a reference todecipher.

v1.0.0

Added in: v1.0.0

When using an authenticated encryption mode (GCM,CCM,OCB, andchacha20-poly1305 arecurrently supported), thedecipher.setAAD() method sets the value used for theadditional authenticated data (AAD) input parameter.

Theoptions argument is optional forGCM. When usingCCM, theplaintextLength option must be specified and its value must match the lengthof the ciphertext in bytes. SeeCCM mode.

Thedecipher.setAAD() method must be called beforedecipher.update().

When passing a string as thebuffer, please considercaveats when using strings as inputs to cryptographic APIs.

decipher.setAuthTag(buffer[, encoding])#

History
VersionChanges
v22.0.0, v20.13.0

Using GCM tag lengths other than 128 bits without specifying theauthTagLength option when creatingdecipher is deprecated.

v15.0.0

The buffer argument can be a string or ArrayBuffer and is limited to no more than 2 ** 31 - 1 bytes.

v11.0.0

This method now throws if the GCM tag length is invalid.

v7.2.0

This method now returns a reference todecipher.

v1.0.0

Added in: v1.0.0

When using an authenticated encryption mode (GCM,CCM,OCB, andchacha20-poly1305 arecurrently supported), thedecipher.setAuthTag() method is used to pass in thereceivedauthentication tag. If no tag is provided, or if the cipher texthas been tampered with,decipher.final() will throw, indicating that thecipher text should be discarded due to failed authentication. If the tag lengthis invalid according toNIST SP 800-38D or does not match the value of theauthTagLength option,decipher.setAuthTag() will throw an error.

Thedecipher.setAuthTag() method must be called beforedecipher.update()forCCM mode or beforedecipher.final() forGCM andOCB modes andchacha20-poly1305.decipher.setAuthTag() can only be called once.

When passing a string as the authentication tag, please considercaveats when using strings as inputs to cryptographic APIs.

decipher.setAutoPadding([autoPadding])#

Added in: v0.7.1

When data has been encrypted without standard block padding, callingdecipher.setAutoPadding(false) will disable automatic padding to preventdecipher.final() from checking for and removing padding.

Turning auto padding off will only work if the input data's length is amultiple of the ciphers block size.

Thedecipher.setAutoPadding() method must be called beforedecipher.final().

decipher.update(data[, inputEncoding][, outputEncoding])#

History
VersionChanges
v6.0.0

The defaultinputEncoding changed frombinary toutf8.

v0.1.94

Added in: v0.1.94

Updates the decipher withdata. If theinputEncoding argument is given,thedataargument is a string using the specified encoding. If theinputEncodingargument is not given,data must be aBuffer. Ifdata is aBuffer theninputEncoding is ignored.

TheoutputEncoding specifies the output format of the enciphereddata. If theoutputEncodingis specified, a string using the specified encoding is returned. If nooutputEncoding is provided, aBuffer is returned.

Thedecipher.update() method can be called multiple times with new data untildecipher.final() is called. Callingdecipher.update() afterdecipher.final() will result in an error being thrown.

Even if the underlying cipher implements authentication, the authenticity andintegrity of the plaintext returned from this function may be uncertain at thistime. For authenticated encryption algorithms, authenticity is generally onlyestablished when the application callsdecipher.final().

Class:DiffieHellman#

Added in: v0.5.0

TheDiffieHellman class is a utility for creating Diffie-Hellman keyexchanges.

Instances of theDiffieHellman class can be created using thecrypto.createDiffieHellman() function.

import assertfrom'node:assert';const {  createDiffieHellman,} =awaitimport('node:crypto');// Generate Alice's keys...const alice =createDiffieHellman(2048);const aliceKey = alice.generateKeys();// Generate Bob's keys...const bob =createDiffieHellman(alice.getPrime(), alice.getGenerator());const bobKey = bob.generateKeys();// Exchange and generate the secret...const aliceSecret = alice.computeSecret(bobKey);const bobSecret = bob.computeSecret(aliceKey);// OKassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));const assert =require('node:assert');const {  createDiffieHellman,} =require('node:crypto');// Generate Alice's keys...const alice =createDiffieHellman(2048);const aliceKey = alice.generateKeys();// Generate Bob's keys...const bob =createDiffieHellman(alice.getPrime(), alice.getGenerator());const bobKey = bob.generateKeys();// Exchange and generate the secret...const aliceSecret = alice.computeSecret(bobKey);const bobSecret = bob.computeSecret(aliceKey);// OKassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));

diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])#

Added in: v0.5.0

Computes the shared secret usingotherPublicKey as the otherparty's public key and returns the computed shared secret. The suppliedkey is interpreted using the specifiedinputEncoding, and secret isencoded using specifiedoutputEncoding.If theinputEncoding is notprovided,otherPublicKey is expected to be aBuffer,TypedArray, orDataView.

IfoutputEncoding is given a string is returned; otherwise, aBuffer is returned.

diffieHellman.generateKeys([encoding])#

Added in: v0.5.0

Generates private and public Diffie-Hellman key values unless they have beengenerated or computed already, and returnsthe public key in the specifiedencoding. This key should betransferred to the other party.Ifencoding is provided a string is returned; otherwise aBuffer is returned.

This function is a thin wrapper aroundDH_generate_key(). In particular,once a private key has been generated or set, calling this function only updatesthe public key but does not generate a new private key.

diffieHellman.getGenerator([encoding])#

Added in: v0.5.0

Returns the Diffie-Hellman generator in the specifiedencoding.Ifencoding is provided a string isreturned; otherwise aBuffer is returned.

diffieHellman.getPrime([encoding])#

Added in: v0.5.0

Returns the Diffie-Hellman prime in the specifiedencoding.Ifencoding is provided a string isreturned; otherwise aBuffer is returned.

diffieHellman.getPrivateKey([encoding])#

Added in: v0.5.0

Returns the Diffie-Hellman private key in the specifiedencoding.Ifencoding is provided astring is returned; otherwise aBuffer is returned.

diffieHellman.getPublicKey([encoding])#

Added in: v0.5.0

Returns the Diffie-Hellman public key in the specifiedencoding.Ifencoding is provided astring is returned; otherwise aBuffer is returned.

diffieHellman.setPrivateKey(privateKey[, encoding])#

Added in: v0.5.0

Sets the Diffie-Hellman private key. If theencoding argument is provided,privateKey is expectedto be a string. If noencoding is provided,privateKey is expectedto be aBuffer,TypedArray, orDataView.

This function does not automatically compute the associated public key. EitherdiffieHellman.setPublicKey() ordiffieHellman.generateKeys() can beused to manually provide the public key or to automatically derive it.

diffieHellman.setPublicKey(publicKey[, encoding])#

Added in: v0.5.0

Sets the Diffie-Hellman public key. If theencoding argument is provided,publicKey is expectedto be a string. If noencoding is provided,publicKey is expectedto be aBuffer,TypedArray, orDataView.

diffieHellman.verifyError#

Added in: v0.11.12

A bit field containing any warnings and/or errors resulting from a checkperformed during initialization of theDiffieHellman object.

The following values are valid for this property (as defined innode:constants module):

  • DH_CHECK_P_NOT_SAFE_PRIME
  • DH_CHECK_P_NOT_PRIME
  • DH_UNABLE_TO_CHECK_GENERATOR
  • DH_NOT_SUITABLE_GENERATOR

Class:DiffieHellmanGroup#

Added in: v0.7.5

TheDiffieHellmanGroup class takes a well-known modp group as its argument.It works the same asDiffieHellman, except that it does not allow changingits keys after creation. In other words, it does not implementsetPublicKey()orsetPrivateKey() methods.

const { createDiffieHellmanGroup } =awaitimport('node:crypto');const dh =createDiffieHellmanGroup('modp16');const { createDiffieHellmanGroup } =require('node:crypto');const dh =createDiffieHellmanGroup('modp16');

The following groups are supported:

The following groups are still supported but deprecated (seeCaveats):

These deprecated groups might be removed in future versions of Node.js.

Class:ECDH#

Added in: v0.11.14

TheECDH class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)key exchanges.

Instances of theECDH class can be created using thecrypto.createECDH() function.

import assertfrom'node:assert';const {  createECDH,} =awaitimport('node:crypto');// Generate Alice's keys...const alice =createECDH('secp521r1');const aliceKey = alice.generateKeys();// Generate Bob's keys...const bob =createECDH('secp521r1');const bobKey = bob.generateKeys();// Exchange and generate the secret...const aliceSecret = alice.computeSecret(bobKey);const bobSecret = bob.computeSecret(aliceKey);assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));// OKconst assert =require('node:assert');const {  createECDH,} =require('node:crypto');// Generate Alice's keys...const alice =createECDH('secp521r1');const aliceKey = alice.generateKeys();// Generate Bob's keys...const bob =createECDH('secp521r1');const bobKey = bob.generateKeys();// Exchange and generate the secret...const aliceSecret = alice.computeSecret(bobKey);const bobSecret = bob.computeSecret(aliceKey);assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));// OK

Static method:ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])#

Added in: v10.0.0

Converts the EC Diffie-Hellman public key specified bykey andcurve to theformat specified byformat. Theformat argument specifies point encodingand can be'compressed','uncompressed' or'hybrid'. The supplied key isinterpreted using the specifiedinputEncoding, and the returned key is encodedusing the specifiedoutputEncoding.

Usecrypto.getCurves() to obtain a list of available curve names.On recent OpenSSL releases,openssl ecparam -list_curves will also displaythe name and description of each available elliptic curve.

Ifformat is not specified the point will be returned in'uncompressed'format.

If theinputEncoding is not provided,key is expected to be aBuffer,TypedArray, orDataView.

Example (uncompressing a key):

const {  createECDH,ECDH,} =awaitimport('node:crypto');const ecdh =createECDH('secp256k1');ecdh.generateKeys();const compressedKey = ecdh.getPublicKey('hex','compressed');const uncompressedKey =ECDH.convertKey(compressedKey,'secp256k1','hex','hex','uncompressed');// The converted key and the uncompressed public key should be the sameconsole.log(uncompressedKey === ecdh.getPublicKey('hex'));const {  createECDH,ECDH,} =require('node:crypto');const ecdh =createECDH('secp256k1');ecdh.generateKeys();const compressedKey = ecdh.getPublicKey('hex','compressed');const uncompressedKey =ECDH.convertKey(compressedKey,'secp256k1','hex','hex','uncompressed');// The converted key and the uncompressed public key should be the sameconsole.log(uncompressedKey === ecdh.getPublicKey('hex'));

ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])#

History
VersionChanges
v10.0.0

Changed error format to better support invalid public key error.

v6.0.0

The defaultinputEncoding changed frombinary toutf8.

v0.11.14

Added in: v0.11.14

Computes the shared secret usingotherPublicKey as the otherparty's public key and returns the computed shared secret. The suppliedkey is interpreted using specifiedinputEncoding, and the returned secretis encoded using the specifiedoutputEncoding.If theinputEncoding is notprovided,otherPublicKey is expected to be aBuffer,TypedArray, orDataView.

IfoutputEncoding is given a string will be returned; otherwise aBuffer is returned.

ecdh.computeSecret will throw anERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY error whenotherPublicKeylies outside of the elliptic curve. SinceotherPublicKey isusually supplied from a remote user over an insecure network,be sure to handle this exception accordingly.

ecdh.generateKeys([encoding[, format]])#

Added in: v0.11.14

Generates private and public EC Diffie-Hellman key values, and returnsthe public key in the specifiedformat andencoding. This key should betransferred to the other party.

Theformat argument specifies point encoding and can be'compressed' or'uncompressed'. Ifformat is not specified, the point will be returned in'uncompressed' format.

Ifencoding is provided a string is returned; otherwise aBufferis returned.

ecdh.getPrivateKey([encoding])#

Added in: v0.11.14

Ifencoding is specified, a string is returned; otherwise aBuffer isreturned.

ecdh.getPublicKey([encoding][, format])#

Added in: v0.11.14

Theformat argument specifies point encoding and can be'compressed' or'uncompressed'. Ifformat is not specified the point will be returned in'uncompressed' format.

Ifencoding is specified, a string is returned; otherwise aBuffer isreturned.

ecdh.setPrivateKey(privateKey[, encoding])#

Added in: v0.11.14

Sets the EC Diffie-Hellman private key.Ifencoding is provided,privateKey is expectedto be a string; otherwiseprivateKey is expected to be aBuffer,TypedArray, orDataView.

IfprivateKey is not valid for the curve specified when theECDH object wascreated, an error is thrown. Upon setting the private key, the associatedpublic point (key) is also generated and set in theECDH object.

ecdh.setPublicKey(publicKey[, encoding])#

Added in: v0.11.14Deprecated since: v5.2.0

Stability: 0 - Deprecated

Sets the EC Diffie-Hellman public key.Ifencoding is providedpublicKey is expected tobe a string; otherwise aBuffer,TypedArray, orDataView is expected.

There is not normally a reason to call this method becauseECDHonly requires a private key and the other party's public key to compute theshared secret. Typically eitherecdh.generateKeys() orecdh.setPrivateKey() will be called. Theecdh.setPrivateKey() methodattempts to generate the public point/key associated with the private key beingset.

Example (obtaining a shared secret):

const {  createECDH,  createHash,} =awaitimport('node:crypto');const alice =createECDH('secp256k1');const bob =createECDH('secp256k1');// This is a shortcut way of specifying one of Alice's previous private// keys. It would be unwise to use such a predictable private key in a real// application.alice.setPrivateKey(createHash('sha256').update('alice','utf8').digest(),);// Bob uses a newly generated cryptographically strong// pseudorandom key pairbob.generateKeys();const aliceSecret = alice.computeSecret(bob.getPublicKey(),null,'hex');const bobSecret = bob.computeSecret(alice.getPublicKey(),null,'hex');// aliceSecret and bobSecret should be the same shared secret valueconsole.log(aliceSecret === bobSecret);const {  createECDH,  createHash,} =require('node:crypto');const alice =createECDH('secp256k1');const bob =createECDH('secp256k1');// This is a shortcut way of specifying one of Alice's previous private// keys. It would be unwise to use such a predictable private key in a real// application.alice.setPrivateKey(createHash('sha256').update('alice','utf8').digest(),);// Bob uses a newly generated cryptographically strong// pseudorandom key pairbob.generateKeys();const aliceSecret = alice.computeSecret(bob.getPublicKey(),null,'hex');const bobSecret = bob.computeSecret(alice.getPublicKey(),null,'hex');// aliceSecret and bobSecret should be the same shared secret valueconsole.log(aliceSecret === bobSecret);

Class:Hash#

Added in: v0.1.92

TheHash class is a utility for creating hash digests of data. It can beused in one of two ways:

  • As astream that is both readable and writable, where data is writtento produce a computed hash digest on the readable side, or
  • Using thehash.update() andhash.digest() methods to produce thecomputed hash.

Thecrypto.createHash() method is used to createHash instances.Hashobjects are not to be created directly using thenew keyword.

Example: UsingHash objects as streams:

const {  createHash,} =awaitimport('node:crypto');const hash =createHash('sha256');hash.on('readable',() => {// Only one element is going to be produced by the// hash stream.const data = hash.read();if (data) {console.log(data.toString('hex'));// Prints://   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50  }});hash.write('some data to hash');hash.end();const {  createHash,} =require('node:crypto');const hash =createHash('sha256');hash.on('readable',() => {// Only one element is going to be produced by the// hash stream.const data = hash.read();if (data) {console.log(data.toString('hex'));// Prints://   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50  }});hash.write('some data to hash');hash.end();

Example: UsingHash and piped streams:

import { createReadStream }from'node:fs';import { stdout }from'node:process';const { createHash } =awaitimport('node:crypto');const hash =createHash('sha256');const input =createReadStream('test.js');input.pipe(hash).setEncoding('hex').pipe(stdout);const { createReadStream } =require('node:fs');const { createHash } =require('node:crypto');const { stdout } =require('node:process');const hash =createHash('sha256');const input =createReadStream('test.js');input.pipe(hash).setEncoding('hex').pipe(stdout);

Example: Using thehash.update() andhash.digest() methods:

const {  createHash,} =awaitimport('node:crypto');const hash =createHash('sha256');hash.update('some data to hash');console.log(hash.digest('hex'));// Prints://   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50const {  createHash,} =require('node:crypto');const hash =createHash('sha256');hash.update('some data to hash');console.log(hash.digest('hex'));// Prints://   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50

hash.copy([options])#

Added in: v13.1.0

Creates a newHash object that contains a deep copy of the internal stateof the currentHash object.

The optionaloptions argument controls stream behavior. For XOF hashfunctions such as'shake256', theoutputLength option can be used tospecify the desired output length in bytes.

An error is thrown when an attempt is made to copy theHash object afteritshash.digest() method has been called.

// Calculate a rolling hash.const {  createHash,} =awaitimport('node:crypto');const hash =createHash('sha256');hash.update('one');console.log(hash.copy().digest('hex'));hash.update('two');console.log(hash.copy().digest('hex'));hash.update('three');console.log(hash.copy().digest('hex'));// Etc.// Calculate a rolling hash.const {  createHash,} =require('node:crypto');const hash =createHash('sha256');hash.update('one');console.log(hash.copy().digest('hex'));hash.update('two');console.log(hash.copy().digest('hex'));hash.update('three');console.log(hash.copy().digest('hex'));// Etc.

hash.digest([encoding])#

Added in: v0.1.92

Calculates the digest of all of the data passed to be hashed (using thehash.update() method).Ifencoding is provided a string will be returned; otherwiseaBuffer is returned.

TheHash object can not be used again afterhash.digest() method has beencalled. Multiple calls will cause an error to be thrown.

hash.update(data[, inputEncoding])#

History
VersionChanges
v6.0.0

The defaultinputEncoding changed frombinary toutf8.

v0.1.92

Added in: v0.1.92

Updates the hash content with the givendata, the encoding of whichis given ininputEncoding.Ifencoding is not provided, and thedata is a string, anencoding of'utf8' is enforced. Ifdata is aBuffer,TypedArray, orDataView, theninputEncoding is ignored.

This can be called many times with new data as it is streamed.

Class:Hmac#

Added in: v0.1.94

TheHmac class is a utility for creating cryptographic HMAC digests. It canbe used in one of two ways:

  • As astream that is both readable and writable, where data is writtento produce a computed HMAC digest on the readable side, or
  • Using thehmac.update() andhmac.digest() methods to produce thecomputed HMAC digest.

Thecrypto.createHmac() method is used to createHmac instances.Hmacobjects are not to be created directly using thenew keyword.

Example: UsingHmac objects as streams:

const {  createHmac,} =awaitimport('node:crypto');const hmac =createHmac('sha256','a secret');hmac.on('readable',() => {// Only one element is going to be produced by the// hash stream.const data = hmac.read();if (data) {console.log(data.toString('hex'));// Prints://   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e  }});hmac.write('some data to hash');hmac.end();const {  createHmac,} =require('node:crypto');const hmac =createHmac('sha256','a secret');hmac.on('readable',() => {// Only one element is going to be produced by the// hash stream.const data = hmac.read();if (data) {console.log(data.toString('hex'));// Prints://   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e  }});hmac.write('some data to hash');hmac.end();

Example: UsingHmac and piped streams:

import { createReadStream }from'node:fs';import { stdout }from'node:process';const {  createHmac,} =awaitimport('node:crypto');const hmac =createHmac('sha256','a secret');const input =createReadStream('test.js');input.pipe(hmac).pipe(stdout);const {  createReadStream,} =require('node:fs');const {  createHmac,} =require('node:crypto');const { stdout } =require('node:process');const hmac =createHmac('sha256','a secret');const input =createReadStream('test.js');input.pipe(hmac).pipe(stdout);

Example: Using thehmac.update() andhmac.digest() methods:

const {  createHmac,} =awaitimport('node:crypto');const hmac =createHmac('sha256','a secret');hmac.update('some data to hash');console.log(hmac.digest('hex'));// Prints://   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77econst {  createHmac,} =require('node:crypto');const hmac =createHmac('sha256','a secret');hmac.update('some data to hash');console.log(hmac.digest('hex'));// Prints://   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e

hmac.digest([encoding])#

Added in: v0.1.94

Calculates the HMAC digest of all of the data passed usinghmac.update().Ifencoding isprovided a string is returned; otherwise aBuffer is returned;

TheHmac object can not be used again afterhmac.digest() has beencalled. Multiple calls tohmac.digest() will result in an error being thrown.

hmac.update(data[, inputEncoding])#

History
VersionChanges
v6.0.0

The defaultinputEncoding changed frombinary toutf8.

v0.1.94

Added in: v0.1.94

Updates theHmac content with the givendata, the encoding of whichis given ininputEncoding.Ifencoding is not provided, and thedata is a string, anencoding of'utf8' is enforced. Ifdata is aBuffer,TypedArray, orDataView, theninputEncoding is ignored.

This can be called many times with new data as it is streamed.

Class:KeyObject#

History
VersionChanges
v14.5.0, v12.19.0

Instances of this class can now be passed to worker threads usingpostMessage.

v11.13.0

This class is now exported.

v11.6.0

Added in: v11.6.0

Node.js uses aKeyObject class to represent a symmetric or asymmetric key,and each kind of key exposes different functions. Thecrypto.createSecretKey(),crypto.createPublicKey() andcrypto.createPrivateKey() methods are used to createKeyObjectinstances.KeyObject objects are not to be created directly using thenewkeyword.

Most applications should consider using the newKeyObject API instead ofpassing keys as strings orBuffers due to improved security features.

KeyObject instances can be passed to other threads viapostMessage().The receiver obtains a clonedKeyObject, and theKeyObject does not need tobe listed in thetransferList argument.

Static method:KeyObject.from(key)#

Added in: v15.0.0

Example: Converting aCryptoKey instance to aKeyObject:

const {KeyObject } =awaitimport('node:crypto');const { subtle } = globalThis.crypto;const key =await subtle.generateKey({name:'HMAC',hash:'SHA-256',length:256,},true, ['sign','verify']);const keyObject =KeyObject.from(key);console.log(keyObject.symmetricKeySize);// Prints: 32 (symmetric key size in bytes)const {KeyObject } =require('node:crypto');const { subtle } = globalThis.crypto;(asyncfunction() {const key =await subtle.generateKey({name:'HMAC',hash:'SHA-256',length:256,  },true, ['sign','verify']);const keyObject =KeyObject.from(key);console.log(keyObject.symmetricKeySize);// Prints: 32 (symmetric key size in bytes)})();

keyObject.asymmetricKeyDetails#

History
VersionChanges
v16.9.0

ExposeRSASSA-PSS-params sequence parameters for RSA-PSS keys.

v15.7.0

Added in: v15.7.0

  • <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 byMGF1 (RSA-PSS).
    • saltLength:<number> Minimal salt length in bytes (RSA-PSS).
    • divisorLength:<number> Size ofq in bits (DSA).
    • namedCurve:<string> Name of the curve (EC).

This property exists only on asymmetric keys. Depending on the type of the key,this object contains information about the key. None of the information obtainedthrough this property can be used to uniquely identify a key or to compromisethe security of the key.

For RSA-PSS keys, if the key material contains aRSASSA-PSS-params sequence,thehashAlgorithm,mgf1HashAlgorithm, andsaltLength properties will beset.

Other key details might be exposed via this API using additional attributes.

keyObject.asymmetricKeyType#

History
VersionChanges
v13.9.0, v12.17.0

Added support for'dh'.

v12.0.0

Added support for'rsa-pss'.

v12.0.0

This property now returnsundefined for KeyObject instances of unrecognized type instead of aborting.

v12.0.0

Added support for'x25519' and'x448'.

v12.0.0

Added support for'ed25519' and'ed448'.

v11.6.0

Added in: v11.6.0

For asymmetric keys, this property represents the type of the key. Supported keytypes 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)
  • 'ed25519' (OID 1.3.101.112)
  • 'ed448' (OID 1.3.101.113)
  • 'dh' (OID 1.2.840.113549.1.3.1)

This property isundefined for unrecognizedKeyObject types and symmetrickeys.

keyObject.equals(otherKeyObject)#

Added in: v17.7.0, v16.15.0

Returnstrue orfalse depending on whether the keys have exactly the sametype, value, and parameters. This method is notconstant time.

keyObject.export([options])#

History
VersionChanges
v15.9.0

Added support for'jwk' format.

v11.6.0

Added in: v11.6.0

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:

  • type:<string> Must be one of'pkcs1' (RSA only) or'spki'.
  • format:<string> Must be'pem','der', or'jwk'.

For private keys, the following encoding options can be used:

  • type:<string> Must be one of'pkcs1' (RSA only),'pkcs8' or'sec1' (EC only).
  • format:<string> Must be'pem','der', or'jwk'.
  • cipher:<string> If specified, the private key will be encrypted withthe givencipher andpassphrase using PKCS#5 v2.0 password basedencryption.
  • passphrase:<string> |<Buffer> The passphrase to use for encryption, seecipher.

The result type depends on the selected encoding format, when PEM theresult is a string, when DER it will be a buffer containing the dataencoded as DER, whenJWK it will be an object.

WhenJWK encoding format was selected, all other encoding options areignored.

PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination ofthecipher andformat options. The PKCS#8type can be used with anyformat to encrypt any key algorithm (RSA, EC, or DH) by specifying acipher. PKCS#1 and SEC1 can only be encrypted by specifying acipherwhen the PEMformat is used. For maximum compatibility, use PKCS#8 forencrypted private keys. Since PKCS#8 defines its ownencryption mechanism, PEM-level encryption is not supported when encryptinga PKCS#8 key. SeeRFC 5208 for PKCS#8 encryption andRFC 1421 forPKCS#1 and SEC1 encryption.

keyObject.symmetricKeySize#

Added in: v11.6.0

For secret keys, this property represents the size of the key in bytes. Thisproperty isundefined for asymmetric keys.

keyObject.toCryptoKey(algorithm, extractable, keyUsages)#

Added in: v23.0.0, v22.10.0

Converts aKeyObject instance to aCryptoKey.

keyObject.type#

Added in: v11.6.0

Depending on the type of thisKeyObject, this property is either'secret' for secret (symmetric) keys,'public' for public (asymmetric) keysor'private' for private (asymmetric) keys.

Class:Sign#

Added in: v0.1.92

TheSign class is a utility for generating signatures. It can be used in oneof two ways:

Thecrypto.createSign() method is used to createSign instances. Theargument is the string name of the hash function to use.Sign objects are notto be created directly using thenew keyword.

Example: UsingSign andVerify objects as streams:

const {  generateKeyPairSync,  createSign,  createVerify,} =awaitimport('node:crypto');const { privateKey, publicKey } =generateKeyPairSync('ec', {namedCurve:'sect239k1',});const sign =createSign('SHA256');sign.write('some data to sign');sign.end();const signature = sign.sign(privateKey,'hex');const verify =createVerify('SHA256');verify.write('some data to sign');verify.end();console.log(verify.verify(publicKey, signature,'hex'));// Prints: trueconst {  generateKeyPairSync,  createSign,  createVerify,} =require('node:crypto');const { privateKey, publicKey } =generateKeyPairSync('ec', {namedCurve:'sect239k1',});const sign =createSign('SHA256');sign.write('some data to sign');sign.end();const signature = sign.sign(privateKey,'hex');const verify =createVerify('SHA256');verify.write('some data to sign');verify.end();console.log(verify.verify(publicKey, signature,'hex'));// Prints: true

Example: Using thesign.update() andverify.update() methods:

const {  generateKeyPairSync,  createSign,  createVerify,} =awaitimport('node:crypto');const { privateKey, publicKey } =generateKeyPairSync('rsa', {modulusLength:2048,});const sign =createSign('SHA256');sign.update('some data to sign');sign.end();const signature = sign.sign(privateKey);const verify =createVerify('SHA256');verify.update('some data to sign');verify.end();console.log(verify.verify(publicKey, signature));// Prints: trueconst {  generateKeyPairSync,  createSign,  createVerify,} =require('node:crypto');const { privateKey, publicKey } =generateKeyPairSync('rsa', {modulusLength:2048,});const sign =createSign('SHA256');sign.update('some data to sign');sign.end();const signature = sign.sign(privateKey);const verify =createVerify('SHA256');verify.update('some data to sign');verify.end();console.log(verify.verify(publicKey, signature));// Prints: true

sign.sign(privateKey[, outputEncoding])#

History
VersionChanges
v15.0.0

The privateKey can also be an ArrayBuffer and CryptoKey.

v13.2.0, v12.16.0

This function now supports IEEE-P1363 DSA and ECDSA signatures.

v12.0.0

This function now supports RSA-PSS keys.

v11.6.0

This function now supports key objects.

v8.0.0

Support for RSASSA-PSS and additional options was added.

v0.1.92

Added in: v0.1.92

Calculates the signature on all the data passed through using eithersign.update() orsign.write().

IfprivateKey is not aKeyObject, this function behaves as ifprivateKey had been passed tocrypto.createPrivateKey(). If it is anobject, the following additional properties can be passed:

  • dsaEncoding<string> For DSA and ECDSA, this option specifies theformat of the generated signature. It can be one of the following:

    • 'der' (default): DER-encoded ASN.1 signature structure encoding(r, s).
    • 'ieee-p1363': Signature formatr || s as proposed in IEEE-P1363.
  • padding<integer> Optional padding value for RSA, one of the following:

    • crypto.constants.RSA_PKCS1_PADDING (default)
    • crypto.constants.RSA_PKCS1_PSS_PADDING

    RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash functionused to sign the message as specified in section 3.1 ofRFC 4055, unlessan MGF1 hash function has been specified as part of the key in compliance withsection 3.3 ofRFC 4055.

  • saltLength<integer> Salt length for when padding isRSA_PKCS1_PSS_PADDING. The special valuecrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digestsize,crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to themaximum permissible value.

IfoutputEncoding is provided a string is returned; otherwise aBufferis returned.

TheSign object can not be again used aftersign.sign() method has beencalled. Multiple calls tosign.sign() will result in an error being thrown.

sign.update(data[, inputEncoding])#

History
VersionChanges
v6.0.0

The defaultinputEncoding changed frombinary toutf8.

v0.1.92

Added in: v0.1.92

Updates theSign content with the givendata, the encoding of whichis given ininputEncoding.Ifencoding is not provided, and thedata is a string, anencoding of'utf8' is enforced. Ifdata is aBuffer,TypedArray, orDataView, theninputEncoding is ignored.

This can be called many times with new data as it is streamed.

Class:Verify#

Added in: v0.1.92

TheVerify class is a utility for verifying signatures. It can be used in oneof two ways:

Thecrypto.createVerify() method is used to createVerify instances.Verify objects are not to be created directly using thenew keyword.

SeeSign for examples.

verify.update(data[, inputEncoding])#

History
VersionChanges
v6.0.0

The defaultinputEncoding changed frombinary toutf8.

v0.1.92

Added in: v0.1.92

Updates theVerify content with the givendata, the encoding of whichis given ininputEncoding.IfinputEncoding is not provided, and thedata is a string, anencoding of'utf8' is enforced. Ifdata is aBuffer,TypedArray, orDataView, theninputEncoding is ignored.

This can be called many times with new data as it is streamed.

verify.verify(object, signature[, signatureEncoding])#

History
VersionChanges
v15.0.0

The object can also be an ArrayBuffer and CryptoKey.

v13.2.0, v12.16.0

This function now supports IEEE-P1363 DSA and ECDSA signatures.

v12.0.0

This function now supports RSA-PSS keys.

v11.7.0

The key can now be a private key.

v8.0.0

Support for RSASSA-PSS and additional options was added.

v0.1.92

Added in: v0.1.92

Verifies the provided data using the givenobject andsignature.

Ifobject is not aKeyObject, this function behaves as ifobject had been passed tocrypto.createPublicKey(). If it is anobject, the following additional properties can be passed:

  • dsaEncoding<string> For DSA and ECDSA, this option specifies theformat of the signature. It can be one of the following:

    • 'der' (default): DER-encoded ASN.1 signature structure encoding(r, s).
    • 'ieee-p1363': Signature formatr || s as proposed in IEEE-P1363.
  • padding<integer> Optional padding value for RSA, one of the following:

    • crypto.constants.RSA_PKCS1_PADDING (default)
    • crypto.constants.RSA_PKCS1_PSS_PADDING

    RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash functionused to verify the message as specified in section 3.1 ofRFC 4055, unlessan MGF1 hash function has been specified as part of the key in compliance withsection 3.3 ofRFC 4055.

  • saltLength<integer> Salt length for when padding isRSA_PKCS1_PSS_PADDING. The special valuecrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digestsize,crypto.constants.RSA_PSS_SALTLEN_AUTO (default) causes it to bedetermined automatically.

Thesignature argument is the previously calculated signature for the data, inthesignatureEncoding.If asignatureEncoding is specified, thesignature is expected to be astring; otherwisesignature is expected to be aBuffer,TypedArray, orDataView.

Theverify object can not be used again afterverify.verify() has beencalled. Multiple calls toverify.verify() will result in an error beingthrown.

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

Class:X509Certificate#

Added in: v15.6.0

Encapsulates an X509 certificate and provides read-only access toits information.

const { X509Certificate } =awaitimport('node:crypto');const x509 =newX509Certificate('{... pem encoded cert ...}');console.log(x509.subject);const { X509Certificate } =require('node:crypto');const x509 =newX509Certificate('{... pem encoded cert ...}');console.log(x509.subject);

new X509Certificate(buffer)#

Added in: v15.6.0

x509.ca#

Added in: v15.6.0
  • Type:<boolean> Will betrue if this is a Certificate Authority (CA)certificate.

x509.checkEmail(email[, options])#

History
VersionChanges
v18.0.0

The subject option now defaults to'default'.

v17.5.0, v16.15.0

The subject option can now be set to'default'.

v17.5.0, v16.14.1

Thewildcards,partialWildcards,multiLabelWildcards, andsingleLabelSubdomains options have been removed since they had no effect.

v15.6.0

Added in: v15.6.0

Checks whether the certificate matches the given email address.

If the'subject' option is undefined or set to'default', the certificatesubject is only considered if the subject alternative name extension either doesnot exist or does not contain any email addresses.

If the'subject' option is set to'always' and if the subject alternativename extension either does not exist or does not contain a matching emailaddress, the certificate subject is considered.

If the'subject' option is set to'never', the certificate subject is neverconsidered, even if the certificate contains no subject alternative names.

x509.checkHost(name[, options])#

History
VersionChanges
v18.0.0

The subject option now defaults to'default'.

v17.5.0, v16.15.0

The subject option can now be set to'default'.

v15.6.0

Added in: v15.6.0

Checks whether the certificate matches the given host name.

If the certificate matches the given host name, the matching subject name isreturned. The returned name might be an exact match (e.g.,foo.example.com)or it might contain wildcards (e.g.,*.example.com). Because host namecomparisons are case-insensitive, the returned subject name might also differfrom the givenname in capitalization.

If the'subject' option is undefined or set to'default', the certificatesubject is only considered if the subject alternative name extension either doesnot exist or does not contain any DNS names. This behavior is consistent withRFC 2818 ("HTTP Over TLS").

If the'subject' option is set to'always' and if the subject alternativename extension either does not exist or does not contain a matching DNS name,the certificate subject is considered.

If the'subject' option is set to'never', the certificate subject is neverconsidered, even if the certificate contains no subject alternative names.

x509.checkIP(ip)#

History
VersionChanges
v17.5.0, v16.14.1

Theoptions argument has been removed since it had no effect.

v15.6.0

Added in: v15.6.0

Checks whether the certificate matches the given IP address (IPv4 or IPv6).

OnlyRFC 5280iPAddress subject alternative names are considered, and theymust match the givenip address exactly. Other subject alternative names aswell as the subject field of the certificate are ignored.

x509.checkIssued(otherCert)#

Added in: v15.6.0

Checks whether this certificate was potentially issued by the givenotherCertby comparing the certificate metadata.

This is useful for pruning a list of possible issuer certificates which have beenselected using a more rudimentary filtering routine, i.e. just based on subjectand issuer names.

Finally, to verify that this certificate's signature was produced by a private keycorresponding tootherCert's public key usex509.verify(publicKey)withotherCert's public key represented as aKeyObjectlike so

if (!x509.verify(otherCert.publicKey)) {thrownewError('otherCert did not issue x509');}

x509.checkPrivateKey(privateKey)#

Added in: v15.6.0

Checks whether the public key for this certificate is consistent withthe given private key.

x509.extKeyUsage#

Added in: v15.6.0

An array detailing the key extended usages for this certificate.

x509.fingerprint#

Added in: v15.6.0

The SHA-1 fingerprint of this certificate.

Because SHA-1 is cryptographically broken and because the security of SHA-1 issignificantly worse than that of algorithms that are commonly used to signcertificates, consider usingx509.fingerprint256 instead.

x509.fingerprint256#

Added in: v15.6.0

The SHA-256 fingerprint of this certificate.

x509.fingerprint512#

Added in: v17.2.0, v16.14.0

The SHA-512 fingerprint of this certificate.

Because computing the SHA-256 fingerprint is usually faster and because it isonly half the size of the SHA-512 fingerprint,x509.fingerprint256 may bea better choice. While SHA-512 presumably provides a higher level of security ingeneral, the security of SHA-256 matches that of most algorithms that arecommonly used to sign certificates.

x509.infoAccess#

History
VersionChanges
v17.3.1, v16.13.2

Parts of this string may be encoded as JSON string literals in response to CVE-2021-44532.

v15.6.0

Added in: v15.6.0

A textual representation of the certificate's authority information accessextension.

This is a line feed separated list of access descriptions. Each line begins withthe access method and the kind of the access location, followed by a colon andthe value associated with the access location.

After the prefix denoting the access method and the kind of the access location,the remainder of each line might be enclosed in quotes to indicate that thevalue is a JSON string literal. For backward compatibility, Node.js only usesJSON string literals within this property when necessary to avoid ambiguity.Third-party code should be prepared to handle both possible entry formats.

x509.issuer#

Added in: v15.6.0

The issuer identification included in this certificate.

x509.issuerCertificate#

Added in: v15.9.0

The issuer certificate orundefined if the issuer certificate is notavailable.

x509.publicKey#

Added in: v15.6.0

The public key<KeyObject> for this certificate.

x509.raw#

Added in: v15.6.0

ABuffer containing the DER encoding of this certificate.

x509.serialNumber#

Added in: v15.6.0

The serial number of this certificate.

Serial numbers are assigned by certificate authorities and do not uniquelyidentify certificates. Consider usingx509.fingerprint256 as a uniqueidentifier instead.

x509.subject#

Added in: v15.6.0

The complete subject of this certificate.

x509.subjectAltName#

History
VersionChanges
v17.3.1, v16.13.2

Parts of this string may be encoded as JSON string literals in response to CVE-2021-44532.

v15.6.0

Added in: v15.6.0

The subject alternative name specified for this certificate.

This is a comma-separated list of subject alternative names. Each entry beginswith a string identifying the kind of the subject alternative name followed bya colon and the value associated with the entry.

Earlier versions of Node.js incorrectly assumed that it is safe to split thisproperty at the two-character sequence', ' (seeCVE-2021-44532). However,both malicious and legitimate certificates can contain subject alternative namesthat include this sequence when represented as a string.

After the prefix denoting the type of the entry, the remainder of each entrymight be enclosed in quotes to indicate that the value is a JSON string literal.For backward compatibility, Node.js only uses JSON string literals within thisproperty when necessary to avoid ambiguity. Third-party code should be preparedto handle both possible entry formats.

x509.toJSON()#

Added in: v15.6.0

There is no standard JSON encoding for X509 certificates. ThetoJSON() method returns a string containing the PEM encodedcertificate.

x509.toLegacyObject()#

Added in: v15.6.0

Returns information about this certificate using the legacycertificate object encoding.

x509.toString()#

Added in: v15.6.0

Returns the PEM-encoded certificate.

x509.validFrom#

Added in: v15.6.0

The date/time from which this certificate is valid.

x509.validFromDate#

Added in: v23.0.0, v22.10.0

The date/time from which this certificate is valid, encapsulated in aDate object.

x509.validTo#

Added in: v15.6.0

The date/time until which this certificate is valid.

x509.validToDate#

Added in: v23.0.0, v22.10.0

The date/time until which this certificate is valid, encapsulated in aDate object.

x509.verify(publicKey)#

Added in: v15.6.0

Verifies that this certificate was signed by the given public key.Does not perform any other validation checks on the certificate.

node:crypto module methods and properties#

crypto.checkPrime(candidate[, options], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v15.8.0

Added in: v15.8.0

  • candidate<ArrayBuffer> |<SharedArrayBuffer> |<TypedArray> |<Buffer> |<DataView> |<bigint>A possible prime encoded as a sequence of big endian octets of arbitrarylength.
  • options<Object>
    • checks<number> The number of Miller-Rabin probabilistic primalityiterations to perform. When the value is0 (zero), a number of checksis used that yields a false positive rate of at most 2-64 forrandom input. Care must be used when selecting a number of checks. Referto the OpenSSL documentation for theBN_is_prime_ex functionnchecksoptions for more details.Default:0
  • callback<Function>
    • err<Error> Set to an<Error> object if an error occurred during check.
    • result<boolean>true if the candidate is a prime with an errorprobability less than0.25 ** options.checks.

Checks the primality of thecandidate.

crypto.checkPrimeSync(candidate[, options])#

Added in: v15.8.0
  • candidate<ArrayBuffer> |<SharedArrayBuffer> |<TypedArray> |<Buffer> |<DataView> |<bigint>A possible prime encoded as a sequence of big endian octets of arbitrarylength.
  • options<Object>
    • checks<number> The number of Miller-Rabin probabilistic primalityiterations to perform. When the value is0 (zero), a number of checksis used that yields a false positive rate of at most 2-64 forrandom input. Care must be used when selecting a number of checks. Referto the OpenSSL documentation for theBN_is_prime_ex functionnchecksoptions for more details.Default:0
  • Returns:<boolean>true if the candidate is a prime with an errorprobability less than0.25 ** options.checks.

Checks the primality of thecandidate.

crypto.constants#

Added in: v6.3.0

An object containing commonly used constants for crypto and security relatedoperations. The specific constants currently defined are described inCrypto constants.

crypto.createCipheriv(algorithm, key, iv[, options])#

History
VersionChanges
v17.9.0, v16.17.0

TheauthTagLength option is now optional when using thechacha20-poly1305 cipher and defaults to 16 bytes.

v15.0.0

The password and iv arguments can be an ArrayBuffer and are each limited to a maximum of 2 ** 31 - 1 bytes.

v11.6.0

Thekey argument can now be aKeyObject.

v11.2.0, v10.17.0

The cipherchacha20-poly1305 (the IETF variant of ChaCha20-Poly1305) is now supported.

v10.10.0

Ciphers in OCB mode are now supported.

v10.2.0

TheauthTagLength option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes.

v9.9.0

Theiv parameter may now benull for ciphers which do not need an initialization vector.

v0.1.94

Added in: v0.1.94

Creates and returns aCipheriv object, with the givenalgorithm,key andinitialization vector (iv).

Theoptions argument controls stream behavior and is optional except when acipher in CCM or OCB mode (e.g.'aes-128-ccm') is used. In that case, theauthTagLength option is required and specifies the length of theauthentication tag in bytes, seeCCM mode. In GCM mode, theauthTagLengthoption is not required but can be used to set the length of the authenticationtag that will be returned bygetAuthTag() and defaults to 16 bytes.Forchacha20-poly1305, theauthTagLength option defaults to 16 bytes.

Thealgorithm is dependent on OpenSSL, examples are'aes192', etc. Onrecent OpenSSL releases,openssl list -cipher-algorithms willdisplay the available cipher algorithms.

Thekey is the raw key used by thealgorithm andiv is aninitialization vector. Both arguments must be'utf8' encoded strings,Buffers,TypedArray, orDataViews. Thekey may optionally beaKeyObject of typesecret. If the cipher does not needan initialization vector,iv may benull.

When passing strings forkey oriv, please considercaveats when using strings as inputs to cryptographic APIs.

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

crypto.createDecipheriv(algorithm, key, iv[, options])#

History
VersionChanges
v17.9.0, v16.17.0

TheauthTagLength option is now optional when using thechacha20-poly1305 cipher and defaults to 16 bytes.

v11.6.0

Thekey argument can now be aKeyObject.

v11.2.0, v10.17.0

The cipherchacha20-poly1305 (the IETF variant of ChaCha20-Poly1305) is now supported.

v10.10.0

Ciphers in OCB mode are now supported.

v10.2.0

TheauthTagLength option can now be used to restrict accepted GCM authentication tag lengths.

v9.9.0

Theiv parameter may now benull for ciphers which do not need an initialization vector.

v0.1.94

Added in: v0.1.94

Creates and returns aDecipheriv object that uses the givenalgorithm,keyand initialization vector (iv).

Theoptions argument controls stream behavior and is optional except when acipher in CCM or OCB mode (e.g.'aes-128-ccm') is used. In that case, theauthTagLength option is required and specifies the length of theauthentication tag in bytes, seeCCM mode.For AES-GCM andchacha20-poly1305, theauthTagLength option defaults to 16bytes and must be set to a different value if a different length is used.

Thealgorithm is dependent on OpenSSL, examples are'aes192', etc. Onrecent OpenSSL releases,openssl list -cipher-algorithms willdisplay the available cipher algorithms.

Thekey is the raw key used by thealgorithm andiv is aninitialization vector. Both arguments must be'utf8' encoded strings,Buffers,TypedArray, orDataViews. Thekey may optionally beaKeyObject of typesecret. If the cipher does not needan initialization vector,iv may benull.

When passing strings forkey oriv, please considercaveats when using strings as inputs to cryptographic APIs.

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

crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])#

History
VersionChanges
v8.0.0

Theprime argument can be anyTypedArray orDataView now.

v8.0.0

Theprime argument can be aUint8Array now.

v6.0.0

The default for the encoding parameters changed frombinary toutf8.

v0.11.12

Added in: v0.11.12

Creates aDiffieHellman key exchange object using the suppliedprime and anoptional specificgenerator.

Thegenerator argument can be a number, string, orBuffer. Ifgenerator is not specified, the value2 is used.

IfprimeEncoding is specified,prime is expected to be a string; otherwiseaBuffer,TypedArray, orDataView is expected.

IfgeneratorEncoding is specified,generator is expected to be a string;otherwise a number,Buffer,TypedArray, orDataView is expected.

crypto.createDiffieHellman(primeLength[, generator])#

Added in: v0.5.0

Creates aDiffieHellman key exchange object and generates a prime ofprimeLength bits using an optional specific numericgenerator.Ifgenerator is not specified, the value2 is used.

crypto.createDiffieHellmanGroup(name)#

Added in: v0.9.3

An alias forcrypto.getDiffieHellman()

crypto.createECDH(curveName)#

Added in: v0.11.14

Creates an Elliptic Curve Diffie-Hellman (ECDH) key exchange object using apredefined curve specified by thecurveName string. Usecrypto.getCurves() to obtain a list of available curve names. On recentOpenSSL releases,openssl ecparam -list_curves will also display the nameand description of each available elliptic curve.

crypto.createHash(algorithm[, options])#

History
VersionChanges
v12.8.0

TheoutputLength option was added for XOF hash functions.

v0.1.92

Added in: v0.1.92

Creates and returns aHash object that can be used to generate hash digestsusing the givenalgorithm. Optionaloptions argument controls streambehavior. For XOF hash functions such as'shake256', theoutputLength optioncan be used to specify the desired output length in bytes.

Thealgorithm is dependent on the available algorithms supported by theversion of OpenSSL on the platform. Examples are'sha256','sha512', etc.On recent releases of OpenSSL,openssl list -digest-algorithms willdisplay the available digest algorithms.

Example: generating the sha256 sum of a file

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

crypto.createHmac(algorithm, key[, options])#

History
VersionChanges
v15.0.0

The key can also be an ArrayBuffer or CryptoKey. The encoding option was added. The key cannot contain more than 2 ** 32 - 1 bytes.

v11.6.0

Thekey argument can now be aKeyObject.

v0.1.94

Added in: v0.1.94

Creates and returns anHmac object that uses the givenalgorithm andkey.Optionaloptions argument controls stream behavior.

Thealgorithm is dependent on the available algorithms supported by theversion of OpenSSL on the platform. Examples are'sha256','sha512', etc.On recent releases of OpenSSL,openssl list -digest-algorithms willdisplay the available digest algorithms.

Thekey is the HMAC key used to generate the cryptographic HMAC hash. If it isaKeyObject, its type must besecret. If it is a string, please considercaveats when using strings as inputs to cryptographic APIs. If it wasobtained from a cryptographically secure source of entropy, such ascrypto.randomBytes() orcrypto.generateKey(), its length should notexceed the block size ofalgorithm (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,} =awaitimport('node:crypto');const filename = argv[2];const hmac =createHmac('sha256','a secret');const input =createReadStream(filename);input.on('readable',() => {// Only one element is going to be produced by the// hash stream.const data = input.read();if (data)    hmac.update(data);else {console.log(`${hmac.digest('hex')}${filename}`);  }});const {  createReadStream,} =require('node:fs');const {  createHmac,} =require('node:crypto');const { argv } =require('node:process');const filename = argv[2];const hmac =createHmac('sha256','a secret');const input =createReadStream(filename);input.on('readable',() => {// Only one element is going to be produced by the// hash stream.const data = input.read();if (data)    hmac.update(data);else {console.log(`${hmac.digest('hex')}${filename}`);  }});

crypto.createPrivateKey(key)#

History
VersionChanges
v15.12.0

The key can also be a JWK object.

v15.0.0

The key can also be an ArrayBuffer. The encoding option was added. The key cannot contain more than 2 ** 32 - 1 bytes.

v11.6.0

Added in: v11.6.0

Creates and returns a new key object containing a private key. Ifkey is astring orBuffer,format is assumed to be'pem'; otherwise,keymust be an object with the properties described above.

If the private key is encrypted, apassphrase must be specified. The lengthof the passphrase is limited to 1024 bytes.

crypto.createPublicKey(key)#

History
VersionChanges
v15.12.0

The key can also be a JWK object.

v15.0.0

The key can also be an ArrayBuffer. The encoding option was added. The key cannot contain more than 2 ** 32 - 1 bytes.

v11.13.0

Thekey argument can now be aKeyObject with typeprivate.

v11.7.0

Thekey argument can now be a private key.

v11.6.0

Added in: v11.6.0

Creates and returns a new key object containing a public key. Ifkey is astring orBuffer,format is assumed to be'pem'; ifkey is aKeyObjectwith 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 bepassed instead of a public key. In that case, this function behaves as ifcrypto.createPrivateKey() had been called, except that the type of thereturnedKeyObject will be'public' and that the private key cannot beextracted from the returnedKeyObject. Similarly, if aKeyObject with type'private' is given, a newKeyObject with type'public' will be returnedand it will be impossible to extract the private key from the returned object.

crypto.createSecretKey(key[, encoding])#

History
VersionChanges
v18.8.0, v16.18.0

The key can now be zero-length.

v15.0.0

The key can also be an ArrayBuffer or string. The encoding argument was added. The key cannot contain more than 2 ** 32 - 1 bytes.

v11.6.0

Added in: v11.6.0

Creates and returns a new key object containing a secret key for symmetricencryption orHmac.

crypto.createSign(algorithm[, options])#

Added in: v0.1.92

Creates and returns aSign object that uses the givenalgorithm. Usecrypto.getHashes() to obtain the names of the available digest algorithms.Optionaloptions argument controls thestream.Writable behavior.

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

crypto.createVerify(algorithm[, options])#

Added in: v0.1.92

Creates and returns aVerify object that uses the given algorithm.Usecrypto.getHashes() to obtain an array of names of the availablesigning algorithms. Optionaloptions argument controls thestream.Writable behavior.

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

crypto.diffieHellman(options[, callback])#

History
VersionChanges
v23.11.0

Optional callback argument added.

v13.9.0, v12.17.0

Added in: v13.9.0, v12.17.0

Computes the Diffie-Hellman secret based on aprivateKey and apublicKey.Both keys must have the sameasymmetricKeyType, which must be one of'dh'(for Diffie-Hellman),'ec','x448', or'x25519' (for ECDH).

If thecallback function is provided this function uses libuv's threadpool.

crypto.fips#

Added in: v6.0.0Deprecated since: v10.0.0

Stability: 0 - Deprecated

Property for checking and controlling whether a FIPS compliant crypto provideris currently in use. Setting to true requires a FIPS build of Node.js.

This property is deprecated. Please usecrypto.setFips() andcrypto.getFips() instead.

crypto.generateKey(type, options, callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v15.0.0

Added in: v15.0.0

  • type:<string> The intended use of the generated secret key. Currentlyaccepted values are'hmac' and'aes'.
  • options:<Object>
    • length:<number> The bit length of the key to generate. This must be avalue greater than 0.
      • Iftype is'hmac', the minimum is 8, and the maximum length is231-1. If the value is not a multiple of 8, the generatedkey will be truncated toMath.floor(length / 8).
      • Iftype is'aes', the length must be one of128,192, or256.
  • callback:<Function>

Asynchronously generates a new random secret key of the givenlength. Thetype will determine which validations will be performed on thelength.

const {  generateKey,} =awaitimport('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 theunderlying hash function. Seecrypto.createHmac() for more information.

crypto.generateKeyPair(type, options, callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v16.10.0

Add ability to defineRSASSA-PSS-params sequence parameters for RSA-PSS keys pairs.

v13.9.0, v12.17.0

Add support for Diffie-Hellman.

v12.0.0

Add support for RSA-PSS key pairs.

v12.0.0

Add ability to generate X25519 and X448 key pairs.

v12.0.0

Add ability to generate Ed25519 and Ed448 key pairs.

v11.6.0

ThegenerateKeyPair andgenerateKeyPairSync functions now produce key objects if no encoding was specified.

v10.12.0

Added in: v10.12.0

Generates a new asymmetric key pair of the giventype. RSA, RSA-PSS, DSA, EC,Ed25519, Ed448, X25519, X448, and DH are currently supported.

If apublicKeyEncoding orprivateKeyEncoding was specified, this functionbehaves as ifkeyObject.export() had been called on its result. Otherwise,the respective part of the key is returned as aKeyObject.

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

const {  generateKeyPair,} =awaitimport('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 witherr set toundefined andpublicKey /privateKey representing the generated key pair.

If this method is invoked as itsutil.promisify()ed version, it returnsaPromise for anObject withpublicKey andprivateKey properties.

crypto.generateKeyPairSync(type, options)#

History
VersionChanges
v16.10.0

Add ability to defineRSASSA-PSS-params sequence parameters for RSA-PSS keys pairs.

v13.9.0, v12.17.0

Add support for Diffie-Hellman.

v12.0.0

Add support for RSA-PSS key pairs.

v12.0.0

Add ability to generate X25519 and X448 key pairs.

v12.0.0

Add ability to generate Ed25519 and Ed448 key pairs.

v11.6.0

ThegenerateKeyPair andgenerateKeyPairSync functions now produce key objects if no encoding was specified.

v10.12.0

Added in: v10.12.0

Generates a new asymmetric key pair of the giventype. RSA, RSA-PSS, DSA, EC,Ed25519, Ed448, X25519, X448, and DH are currently supported.

If apublicKeyEncoding orprivateKeyEncoding was specified, this functionbehaves as ifkeyObject.export() had been called on its result. Otherwise,the respective part of the key is returned as aKeyObject.

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

const {  generateKeyPairSync,} =awaitimport('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, otherwiseit will be a buffer containing the data encoded as DER.

crypto.generateKeySync(type, options)#

Added in: v15.0.0
  • type:<string> The intended use of the generated secret key. Currentlyaccepted values are'hmac' and'aes'.
  • options:<Object>
    • length:<number> The bit length of the key to generate.
      • Iftype is'hmac', the minimum is 8, and the maximum length is231-1. If the value is not a multiple of 8, the generatedkey will be truncated toMath.floor(length / 8).
      • Iftype is'aes', the length must be one of128,192, or256.
  • Returns:<KeyObject>

Synchronously generates a new random secret key of the givenlength. Thetype will determine which validations will be performed on thelength.

const {  generateKeySync,} =awaitimport('node:crypto');const key =generateKeySync('hmac', {length:512 });console.log(key.export().toString('hex'));// e89..........41econst {  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 theunderlying hash function. Seecrypto.createHmac() for more information.

crypto.generatePrime(size[, options], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v15.8.0

Added in: v15.8.0

Generates a pseudorandom prime ofsize bits.

Ifoptions.safe istrue, the prime will be a safe prime -- that is,(prime - 1) / 2 will also be a prime.

Theoptions.add andoptions.rem parameters can be used to enforce additionalrequirements, e.g., for Diffie-Hellman:

  • Ifoptions.add andoptions.rem are both set, the prime will satisfy thecondition thatprime % add = rem.
  • If onlyoptions.add is set andoptions.safe is nottrue, the prime willsatisfy the condition thatprime % add = 1.
  • If onlyoptions.add is set andoptions.safe is set totrue, the primewill instead satisfy the condition thatprime % add = 3. This is necessarybecauseprime % add = 1 foroptions.add > 2 would contradict the conditionenforced byoptions.safe.
  • options.rem is ignored ifoptions.add is not given.

Bothoptions.add andoptions.rem must be encoded as big-endian sequencesif given as anArrayBuffer,SharedArrayBuffer,TypedArray,Buffer, orDataView.

By default, the prime is encoded as a big-endian sequence of octetsin an<ArrayBuffer>. If thebigint option istrue, then a<bigint>is provided.

Thesize of the prime will have a direct impact on how long it takes togenerate the prime. The larger the size, the longer it will take. Becausewe use OpenSSL'sBN_generate_prime_ex function, which provides onlyminimal control over our ability to interrupt the generation process,it is not recommended to generate overly large primes, as doing so may makethe process unresponsive.

crypto.generatePrimeSync(size[, options])#

Added in: v15.8.0

Generates a pseudorandom prime ofsize bits.

Ifoptions.safe istrue, the prime will be a safe prime -- that is,(prime - 1) / 2 will also be a prime.

Theoptions.add andoptions.rem parameters can be used to enforce additionalrequirements, e.g., for Diffie-Hellman:

  • Ifoptions.add andoptions.rem are both set, the prime will satisfy thecondition thatprime % add = rem.
  • If onlyoptions.add is set andoptions.safe is nottrue, the prime willsatisfy the condition thatprime % add = 1.
  • If onlyoptions.add is set andoptions.safe is set totrue, the primewill instead satisfy the condition thatprime % add = 3. This is necessarybecauseprime % add = 1 foroptions.add > 2 would contradict the conditionenforced byoptions.safe.
  • options.rem is ignored ifoptions.add is not given.

Bothoptions.add andoptions.rem must be encoded as big-endian sequencesif given as anArrayBuffer,SharedArrayBuffer,TypedArray,Buffer, orDataView.

By default, the prime is encoded as a big-endian sequence of octetsin an<ArrayBuffer>. If thebigint option istrue, then a<bigint>is provided.

Thesize of the prime will have a direct impact on how long it takes togenerate the prime. The larger the size, the longer it will take. Becausewe use OpenSSL'sBN_generate_prime_ex function, which provides onlyminimal control over our ability to interrupt the generation process,it is not recommended to generate overly large primes, as doing so may makethe process unresponsive.

crypto.getCipherInfo(nameOrNid[, options])#

Added in: v15.0.0
  • nameOrNid:<string> |<number> The name or nid of the cipher to query.
  • options:<Object>
  • Returns:<Object>
    • name<string> The name of the cipher
    • nid<number> The nid of the cipher
    • blockSize<number> The block size of the cipher in bytes. This propertyis omitted whenmode is'stream'.
    • ivLength<number> The expected or default initialization vector length inbytes. This property is omitted if the cipher does not use an initializationvector.
    • keyLength<number> The expected or default key length in bytes.
    • mode<string> The cipher mode. One of'cbc','ccm','cfb','ctr','ecb','gcm','ocb','ofb','stream','wrap','xts'.

Returns information about a given cipher.

Some ciphers accept variable length keys and initialization vectors. By default,thecrypto.getCipherInfo() method will return the default values for theseciphers. To test if a given key length or iv length is acceptable for givencipher, use thekeyLength andivLength options. If the given values areunacceptable,undefined will be returned.

crypto.getCiphers()#

Added in: v0.9.3
  • Returns:<string[]> An array with the names of the supported cipheralgorithms.
const {  getCiphers,} =awaitimport('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()#

Added in: v2.3.0
  • Returns:<string[]> An array with the names of the supported elliptic curves.
const {  getCurves,} =awaitimport('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)#

Added in: v0.7.5

Creates a predefinedDiffieHellmanGroup key exchange object. Thesupported groups are listed in the documentation forDiffieHellmanGroup.

The returned object mimics the interface of objects created bycrypto.createDiffieHellman(), but will not allow changingthe keys (withdiffieHellman.setPublicKey(), for example). Theadvantage of using this method is that the parties do not have togenerate nor exchange a group modulus beforehand, saving both processorand communication time.

Example (obtaining a shared secret):

const {  getDiffieHellman,} =awaitimport('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()#

Added in: v10.0.0
  • Returns:<number>1 if and only if a FIPS compliant crypto provider iscurrently in use,0 otherwise. A future semver-major release may changethe return type of this API to a<boolean>.

crypto.getHashes()#

Added in: v0.9.3
  • Returns:<string[]> An array of the names of the supported hash algorithms,such as'RSA-SHA256'. Hash algorithms are also called "digest" algorithms.
const {  getHashes,} =awaitimport('node:crypto');console.log(getHashes());// ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]const {  getHashes,} =require('node:crypto');console.log(getHashes());// ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]

crypto.getRandomValues(typedArray)#

Added in: v17.4.0

A convenient alias forcrypto.webcrypto.getRandomValues(). Thisimplementation is not compliant with the Web Crypto spec, to writeweb-compatible code usecrypto.webcrypto.getRandomValues() instead.

crypto.hash(algorithm, data[, options])#

History
VersionChanges
v24.4.0

TheoutputLength option was added for XOF hash functions.

v21.7.0, v20.12.0

Added in: v21.7.0, v20.12.0

Stability: 1.2 - Release candidate

  • algorithm<string> |<undefined>
  • data<string> |<Buffer> |<TypedArray> |<DataView> Whendata is astring, it will be encoded as UTF-8 before being hashed. If a differentinput encoding is desired for a string input, user could encode the stringinto aTypedArray using eitherTextEncoder orBuffer.from() and passingthe encodedTypedArray into this API instead.
  • options<Object> |<string>
    • outputEncoding<string>Encoding used to encode thereturned digest.Default:'hex'.
    • outputLength<number> For XOF hash functions such as 'shake256',the outputLength option can be used to specify the desired output length in bytes.
  • Returns:<string> |<Buffer>

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

Thealgorithm is dependent on the available algorithms supported by theversion of OpenSSL on the platform. Examples are'sha256','sha512', etc.On recent releases of OpenSSL,openssl list -digest-algorithms willdisplay the available digest algorithms.

Ifoptions is a string, then it specifies theoutputEncoding.

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';// 10b3493287f831e81a438811a1ffba01f8cec4b7console.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 cryptofrom'node:crypto';import {Buffer }from'node:buffer';// Hashing a string and return the result as a hex-encoded string.const string ='Node.js';// 10b3493287f831e81a438811a1ffba01f8cec4b7console.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)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v18.8.0, v16.18.0

The input keying material can now be zero-length.

v15.0.0

Added in: v15.0.0

HKDF is a simple key derivation function defined in RFC 5869. The givenikm,salt andinfo are used with thedigest to derive a key ofkeylen bytes.

The suppliedcallback function is called with two arguments:err andderivedKey. If an errors occurs while deriving the key,err will be set;otherwiseerr will benull. The successfully generatedderivedKey willbe passed to the callback as an<ArrayBuffer>. An error will be thrown if anyof the input arguments specify invalid values or types.

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

crypto.hkdfSync(digest, ikm, salt, info, keylen)#

History
VersionChanges
v18.8.0, v16.18.0

The input keying material can now be zero-length.

v15.0.0

Added in: v15.0.0

Provides a synchronous HKDF key derivation function as defined in RFC 5869. Thegivenikm,salt andinfo are used with thedigest to derive a key ofkeylen bytes.

The successfully generatedderivedKey will be returned as an<ArrayBuffer>.

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

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

crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v15.0.0

The password and salt arguments can also be ArrayBuffer instances.

v14.0.0

Theiterations parameter is now restricted to positive values. Earlier releases treated other values as one.

v8.0.0

Thedigest parameter is always required now.

v6.0.0

Calling this function without passing thedigest parameter is deprecated now and will emit a warning.

v6.0.0

The default encoding forpassword if it is a string changed frombinary toutf8.

v0.5.5

Added in: v0.5.5

Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)implementation. A selected HMAC digest algorithm specified bydigest isapplied to derive a key of the requested byte length (keylen) from thepassword,salt anditerations.

The suppliedcallback function is called with two arguments:err andderivedKey. If an error occurs while deriving the key,err will be set;otherwiseerr will benull. By default, the successfully generatedderivedKey will be passed to the callback as aBuffer. An error will bethrown if any of the input arguments specify invalid values or types.

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

Thesalt should be as unique as possible. It is recommended that a salt israndom and at least 16 bytes long. SeeNIST SP 800-132 for details.

When passing strings forpassword orsalt, please considercaveats when using strings as inputs to cryptographic APIs.

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

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

This API uses libuv's threadpool, which can have surprising andnegative performance implications for some applications; see theUV_THREADPOOL_SIZE documentation for more information.

crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)#

History
VersionChanges
v14.0.0

Theiterations parameter is now restricted to positive values. Earlier releases treated other values as one.

v6.0.0

Calling this function without passing thedigest parameter is deprecated now and will emit a warning.

v6.0.0

The default encoding forpassword if it is a string changed frombinary toutf8.

v0.9.3

Added in: v0.9.3

Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)implementation. A selected HMAC digest algorithm specified bydigest isapplied to derive a key of the requested byte length (keylen) from thepassword,salt anditerations.

If an error occurs anError will be thrown, otherwise the derived key will bereturned as aBuffer.

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

Thesalt should be as unique as possible. It is recommended that a salt israndom and at least 16 bytes long. SeeNIST SP 800-132 for details.

When passing strings forpassword orsalt, please considercaveats when using strings as inputs to cryptographic APIs.

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

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

crypto.privateDecrypt(privateKey, buffer)#

History
VersionChanges
v21.6.2, v20.11.1, v18.19.1

TheRSA_PKCS1_PADDING padding was disabled unless the OpenSSL build supports implicit rejection.

v15.0.0

Added string, ArrayBuffer, and CryptoKey as allowable key types. The oaepLabel can be an ArrayBuffer. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes.

v12.11.0

TheoaepLabel option was added.

v12.9.0

TheoaepHash option was added.

v11.6.0

This function now supports key objects.

v0.11.14

Added in: v0.11.14

Decryptsbuffer withprivateKey.buffer was previously encrypted usingthe corresponding public key, for example usingcrypto.publicEncrypt().

IfprivateKey is not aKeyObject, this function behaves as ifprivateKey had been passed tocrypto.createPrivateKey(). If it is anobject, thepadding property can be passed. Otherwise, this function usesRSA_PKCS1_OAEP_PADDING.

Usingcrypto.constants.RSA_PKCS1_PADDING incrypto.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 useRSA_PKCS1_PADDING will fail.

crypto.privateEncrypt(privateKey, buffer)#

History
VersionChanges
v15.0.0

Added string, ArrayBuffer, and CryptoKey as allowable key types. The passphrase can be an ArrayBuffer. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes.

v11.6.0

This function now supports key objects.

v1.1.0

Added in: v1.1.0

Encryptsbuffer withprivateKey. The returned data can be decrypted usingthe corresponding public key, for example usingcrypto.publicDecrypt().

IfprivateKey is not aKeyObject, this function behaves as ifprivateKey had been passed tocrypto.createPrivateKey(). If it is anobject, thepadding property can be passed. Otherwise, this function usesRSA_PKCS1_PADDING.

crypto.publicDecrypt(key, buffer)#

History
VersionChanges
v15.0.0

Added string, ArrayBuffer, and CryptoKey as allowable key types. The passphrase can be an ArrayBuffer. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes.

v11.6.0

This function now supports key objects.

v1.1.0

Added in: v1.1.0

Decryptsbuffer withkey.buffer was previously encrypted usingthe corresponding private key, for example usingcrypto.privateEncrypt().

Ifkey is not aKeyObject, this function behaves as ifkey had been passed tocrypto.createPublicKey(). If it is anobject, thepadding property can be passed. Otherwise, this function usesRSA_PKCS1_PADDING.

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

crypto.publicEncrypt(key, buffer)#

History
VersionChanges
v15.0.0

Added string, ArrayBuffer, and CryptoKey as allowable key types. The oaepLabel and passphrase can be ArrayBuffers. The buffer can be a string or ArrayBuffer. All types that accept buffers are limited to a maximum of 2 ** 31 - 1 bytes.

v12.11.0

TheoaepLabel option was added.

v12.9.0

TheoaepHash option was added.

v11.6.0

This function now supports key objects.

v0.11.14

Added in: v0.11.14

Encrypts the content ofbuffer withkey and returns a newBuffer with encrypted content. The returned data can be decrypted usingthe corresponding private key, for example usingcrypto.privateDecrypt().

Ifkey is not aKeyObject, this function behaves as ifkey had been passed tocrypto.createPublicKey(). If it is anobject, thepadding property can be passed. Otherwise, this function usesRSA_PKCS1_OAEP_PADDING.

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

crypto.randomBytes(size[, callback])#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v9.0.0

Passingnull as thecallback argument now throwsERR_INVALID_CALLBACK.

v0.5.8

Added in: v0.5.8

Generates cryptographically strong pseudorandom data. Thesize argumentis a number indicating the number of bytes to generate.

If acallback function is provided, the bytes are generated asynchronouslyand thecallback function is invoked with two arguments:err andbuf.If an error occurs,err will be anError object; otherwise it isnull. Thebuf argument is aBuffer containing the generated bytes.

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

If thecallback function is not provided, the random bytes are generatedsynchronously and returned as aBuffer. An error will be thrown ifthere is a problem generating the bytes.

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

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

This API uses libuv's threadpool, which can have surprising andnegative performance implications for some applications; see theUV_THREADPOOL_SIZE documentation for more information.

The asynchronous version ofcrypto.randomBytes() is carried out in a singlethreadpool request. To minimize threadpool task length variation, partitionlargerandomBytes requests when doing so as part of fulfilling a clientrequest.

crypto.randomFill(buffer[, offset][, size], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v9.0.0

Thebuffer argument may be anyTypedArray orDataView.

v7.10.0, v6.13.0

Added in: v7.10.0, v6.13.0

This function is similar tocrypto.randomBytes() but requires the firstargument to be aBuffer that will be filled. It alsorequires that a callback is passed in.

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

import {Buffer }from'node:buffer';const { randomFill } =awaitimport('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'));});

AnyArrayBuffer,TypedArray, orDataView instance may be passed asbuffer.

While this includes instances ofFloat32Array andFloat64Array, thisfunction should not be used to generate random floating-point numbers. Theresult may contain+Infinity,-Infinity, andNaN, and even if the arraycontains finite numbers only, they are not drawn from a uniform randomdistribution and have no meaningful lower or upper bounds.

import {Buffer }from'node:buffer';const { randomFill } =awaitimport('node:crypto');const a =newUint32Array(10);randomFill(a,(err, buf) => {if (err)throw err;console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)    .toString('hex'));});const b =newDataView(newArrayBuffer(10));randomFill(b,(err, buf) => {if (err)throw err;console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)    .toString('hex'));});const c =newArrayBuffer(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 =newUint32Array(10);randomFill(a,(err, buf) => {if (err)throw err;console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)    .toString('hex'));});const b =newDataView(newArrayBuffer(10));randomFill(b,(err, buf) => {if (err)throw err;console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)    .toString('hex'));});const c =newArrayBuffer(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 andnegative performance implications for some applications; see theUV_THREADPOOL_SIZE documentation for more information.

The asynchronous version ofcrypto.randomFill() is carried out in a singlethreadpool request. To minimize threadpool task length variation, partitionlargerandomFill requests when doing so as part of fulfilling a clientrequest.

crypto.randomFillSync(buffer[, offset][, size])#

History
VersionChanges
v9.0.0

Thebuffer argument may be anyTypedArray orDataView.

v7.10.0, v6.13.0

Added in: v7.10.0, v6.13.0

Synchronous version ofcrypto.randomFill().

import {Buffer }from'node:buffer';const { randomFillSync } =awaitimport('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'));

AnyArrayBuffer,TypedArray orDataView instance may be passed asbuffer.

import {Buffer }from'node:buffer';const { randomFillSync } =awaitimport('node:crypto');const a =newUint32Array(10);console.log(Buffer.from(randomFillSync(a).buffer,                        a.byteOffset, a.byteLength).toString('hex'));const b =newDataView(newArrayBuffer(10));console.log(Buffer.from(randomFillSync(b).buffer,                        b.byteOffset, b.byteLength).toString('hex'));const c =newArrayBuffer(10);console.log(Buffer.from(randomFillSync(c)).toString('hex'));const { randomFillSync } =require('node:crypto');const {Buffer } =require('node:buffer');const a =newUint32Array(10);console.log(Buffer.from(randomFillSync(a).buffer,                        a.byteOffset, a.byteLength).toString('hex'));const b =newDataView(newArrayBuffer(10));console.log(Buffer.from(randomFillSync(b).buffer,                        b.byteOffset, b.byteLength).toString('hex'));const c =newArrayBuffer(10);console.log(Buffer.from(randomFillSync(c)).toString('hex'));

crypto.randomInt([min, ]max[, callback])#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v14.10.0, v12.19.0

Added in: v14.10.0, v12.19.0

  • min<integer> Start of random range (inclusive).Default:0.
  • max<integer> End of random range (exclusive).
  • callback<Function>function(err, n) {}.

Return a random integern such thatmin <= n < max. Thisimplementation avoidsmodulo bias.

The range (max - min) must be less than 248.min andmax mustbesafe integers.

If thecallback function is not provided, the random integer isgenerated synchronously.

// Asynchronousconst {  randomInt,} =awaitimport('node:crypto');randomInt(3,(err, n) => {if (err)throw err;console.log(`Random number chosen from (0, 1, 2):${n}`);});// Asynchronousconst {  randomInt,} =require('node:crypto');randomInt(3,(err, n) => {if (err)throw err;console.log(`Random number chosen from (0, 1, 2):${n}`);});
// Synchronousconst {  randomInt,} =awaitimport('node:crypto');const n =randomInt(3);console.log(`Random number chosen from (0, 1, 2):${n}`);// Synchronousconst {  randomInt,} =require('node:crypto');const n =randomInt(3);console.log(`Random number chosen from (0, 1, 2):${n}`);
// With `min` argumentconst {  randomInt,} =awaitimport('node:crypto');const n =randomInt(1,7);console.log(`The dice rolled:${n}`);// With `min` argumentconst {  randomInt,} =require('node:crypto');const n =randomInt(1,7);console.log(`The dice rolled:${n}`);

crypto.randomUUID([options])#

Added in: v15.6.0, v14.17.0
  • options<Object>
    • disableEntropyCache<boolean> By default, to improve performance,Node.js generates and caches enoughrandom data to generate up to 128 random UUIDs. To generate a UUIDwithout using the cache, setdisableEntropyCache totrue.Default:false.
  • Returns:<string>

Generates a randomRFC 4122 version 4 UUID. The UUID is generated using acryptographic pseudorandom number generator.

crypto.scrypt(password, salt, keylen[, options], callback)#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v15.0.0

The password and salt arguments can also be ArrayBuffer instances.

v12.8.0, v10.17.0

Themaxmem value can now be any safe integer.

v10.9.0

Thecost,blockSize andparallelization option names have been added.

v10.5.0

Added in: v10.5.0

Provides an asynchronousscrypt implementation. Scrypt is a password-basedkey derivation function that is designed to be expensive computationally andmemory-wise in order to make brute-force attacks unrewarding.

Thesalt should be as unique as possible. It is recommended that a salt israndom and at least 16 bytes long. SeeNIST SP 800-132 for details.

When passing strings forpassword orsalt, please considercaveats when using strings as inputs to cryptographic APIs.

Thecallback function is called with two arguments:err andderivedKey.err is an exception object when key derivation fails, otherwiseerr isnull.derivedKey is passed to the callback as aBuffer.

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

const {  scrypt,} =awaitimport('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])#

History
VersionChanges
v12.8.0, v10.17.0

Themaxmem value can now be any safe integer.

v10.9.0

Thecost,blockSize andparallelization option names have been added.

v10.5.0

Added in: v10.5.0

Provides a synchronousscrypt implementation. Scrypt is a password-basedkey derivation function that is designed to be expensive computationally andmemory-wise in order to make brute-force attacks unrewarding.

Thesalt should be as unique as possible. It is recommended that a salt israndom and at least 16 bytes long. SeeNIST SP 800-132 for details.

When passing strings forpassword orsalt, please considercaveats when using strings as inputs to cryptographic APIs.

An exception is thrown when key derivation fails, otherwise the derived key isreturned as aBuffer.

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

const {  scryptSync,} =awaitimport('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()#

Added in: v15.6.0
  • Returns:<Object>
    • total<number> The total allocated secure heap size as specifiedusing the--secure-heap=n command-line flag.
    • min<number> The minimum allocation from the secure heap asspecified using the--secure-heap-min command-line flag.
    • used<number> The total number of bytes currently allocated fromthe secure heap.
    • utilization<number> The calculated ratio ofused tototalallocated bytes.

crypto.setEngine(engine[, flags])#

History
VersionChanges
v22.4.0, v20.16.0

Custom engine support in OpenSSL 3 is deprecated.

v0.11.11

Added in: v0.11.11

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

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

The optionalflags argument usesENGINE_METHOD_ALL by default. Theflagsis a bit field taking one of or a mix of the following flags (defined incrypto.constants):

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

crypto.setFips(bool)#

Added in: v10.0.0

Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.Throws an error if FIPS mode is not available.

crypto.sign(algorithm, data, key[, callback])#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v15.12.0

Optional callback argument added.

v13.2.0, v12.16.0

This function now supports IEEE-P1363 DSA and ECDSA signatures.

v12.0.0

Added in: v12.0.0

Calculates and returns the signature fordata using the given private key andalgorithm. Ifalgorithm isnull orundefined, then the algorithm isdependent upon the key type (especially Ed25519 and Ed448).

Ifkey is not aKeyObject, this function behaves as ifkey had beenpassed tocrypto.createPrivateKey(). If it is an object, the followingadditional properties can be passed:

  • dsaEncoding<string> For DSA and ECDSA, this option specifies theformat of the generated signature. It can be one of the following:

    • 'der' (default): DER-encoded ASN.1 signature structure encoding(r, s).
    • 'ieee-p1363': Signature formatr || s as proposed in IEEE-P1363.
  • padding<integer> Optional padding value for RSA, one of the following:

    • crypto.constants.RSA_PKCS1_PADDING (default)
    • crypto.constants.RSA_PKCS1_PSS_PADDING

    RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash functionused to sign the message as specified in section 3.1 ofRFC 4055.

  • saltLength<integer> Salt length for when padding isRSA_PKCS1_PSS_PADDING. The special valuecrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digestsize,crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to themaximum permissible value.

If thecallback function is provided this function uses libuv's threadpool.

crypto.subtle#

Added in: v17.4.0

A convenient alias forcrypto.webcrypto.subtle.

crypto.timingSafeEqual(a, b)#

History
VersionChanges
v15.0.0

The a and b arguments can also be ArrayBuffer.

v6.6.0

Added in: v6.6.0

This function compares the underlying bytes that represent the givenArrayBuffer,TypedArray, orDataView instances using a constant-timealgorithm.

This function does not leak timing information thatwould allow an attacker to guess one of the values. This is suitable forcomparing HMAC digests or secret values like authentication cookies orcapability urls.

a andb must both beBuffers,TypedArrays, orDataViews, and theymust have the same byte length. An error is thrown ifa andb havedifferent byte lengths.

If at least one ofa andb is aTypedArray with more than one byte perentry, such asUint16Array, the result will be computed using the platformbyte order.

When both of the inputs areFloat32Arrays orFloat64Arrays, this function might return unexpected results due to IEEE 754encoding of floating-point numbers. In particular, neitherx === y norObject.is(x, y) implies that the byte representations of two floating-pointnumbersx andy are equal.

Use ofcrypto.timingSafeEqual does not guarantee that thesurrounding codeis timing-safe. Care should be taken to ensure that the surrounding code doesnot introduce timing vulnerabilities.

crypto.verify(algorithm, data, key, signature[, callback])#

History
VersionChanges
v18.0.0

Passing an invalid callback to thecallback argument now throwsERR_INVALID_ARG_TYPE instead ofERR_INVALID_CALLBACK.

v15.12.0

Optional callback argument added.

v15.0.0

The data, key, and signature arguments can also be ArrayBuffer.

v13.2.0, v12.16.0

This function now supports IEEE-P1363 DSA and ECDSA signatures.

v12.0.0

Added in: v12.0.0

Verifies the given signature fordata using the given key and algorithm. Ifalgorithm isnull orundefined, then the algorithm is dependent upon thekey type (especially Ed25519 and Ed448).

Ifkey is not aKeyObject, this function behaves as ifkey had beenpassed tocrypto.createPublicKey(). If it is an object, the followingadditional properties can be passed:

  • dsaEncoding<string> For DSA and ECDSA, this option specifies theformat of the signature. It can be one of the following:

    • 'der' (default): DER-encoded ASN.1 signature structure encoding(r, s).
    • 'ieee-p1363': Signature formatr || s as proposed in IEEE-P1363.
  • padding<integer> Optional padding value for RSA, one of the following:

    • crypto.constants.RSA_PKCS1_PADDING (default)
    • crypto.constants.RSA_PKCS1_PSS_PADDING

    RSA_PKCS1_PSS_PADDING will use MGF1 with the same hash functionused to sign the message as specified in section 3.1 ofRFC 4055.

  • saltLength<integer> Salt length for when padding isRSA_PKCS1_PSS_PADDING. The special valuecrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digestsize,crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to themaximum permissible value.

Thesignature argument is the previously calculated signature for thedata.

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

If thecallback function is provided this function uses libuv's threadpool.

crypto.webcrypto#

Added in: v15.0.0

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

See theWeb Crypto API documentation for details.

Notes#

Using strings as inputs to cryptographic APIs#

For historical reasons, many cryptographic APIs provided by Node.js acceptstrings as inputs where the underlying cryptographic algorithm works on bytesequences. These instances include plaintexts, ciphertexts, symmetric keys,initialization vectors, passphrases, salts, authentication tags,and additional authenticated data.

When passing strings to cryptographic APIs, consider the following factors.

  • Not all byte sequences are valid UTF-8 strings. Therefore, when a bytesequence of lengthn is derived from a string, its entropy is generallylower than the entropy of a random or pseudorandomn byte sequence.For example, no UTF-8 string will result in the byte sequencec0 af. Secretkeys should almost exclusively be random or pseudorandom byte sequences.

  • Similarly, when converting random or pseudorandom byte sequences to UTF-8strings, subsequences that do not represent valid code points may be replacedby the Unicode replacement character (U+FFFD). The byte representation ofthe resulting Unicode string may, therefore, not be equal to the byte sequencethat the string was created from.

    const original = [0xc0,0xaf];const bytesAsString =Buffer.from(original).toString('utf8');const stringAsBytes =Buffer.from(bytesAsString,'utf8');console.log(stringAsBytes);// Prints '<Buffer ef bf bd ef bf bd>'.

    The outputs of ciphers, hash functions, signature algorithms, and keyderivation functions are pseudorandom byte sequences and should not beused as Unicode strings.

  • When strings are obtained from user input, some Unicode characters can berepresented in multiple equivalent ways that result in different bytesequences. For example, when passing a user passphrase to a key derivationfunction, such as PBKDF2 or scrypt, the result of the key derivation functiondepends on whether the string uses composed or decomposed characters. Node.jsdoes not normalize character representations. Developers should consider usingString.prototype.normalize() on user inputs before passing them tocryptographic APIs.

Legacy streams API (prior to Node.js 0.10)#

The Crypto module was added to Node.js before there was the concept of aunified Stream API, and before there wereBuffer objects for handlingbinary data. As such, manycrypto classes have methods nottypically found on other Node.js classes that implement thestreamsAPI (e.g.update(),final(), ordigest()). Also, many methods acceptedand returned'latin1' encoded strings by default rather thanBuffers. Thisdefault was changed after Node.js v0.8 to useBuffer objects by defaultinstead.

Support for weak or compromised algorithms#

Thenode:crypto module still supports some algorithms which are alreadycompromised and are not recommended for use. The API also allowsthe use of ciphers and hashes with a small key size that are too weak for safeuse.

Users should take full responsibility for selecting the cryptoalgorithm and key size according to their security requirements.

Based on the recommendations ofNIST SP 800-131A:

  • MD5 and SHA-1 are no longer acceptable where collision resistance isrequired such as digital signatures.
  • The key used with RSA, DSA, and DH algorithms is recommended to haveat least 2048 bits and that of the curve of ECDSA and ECDH at least224 bits, to be safe to use for several years.
  • The DH groups ofmodp1,modp2 andmodp5 have a key sizesmaller than 2048 bits and are not recommended.

See the reference for other recommendations and details.

Some algorithms that have known weaknesses and are of little relevance inpractice are only available through thelegacy provider, which is notenabled by default.

CCM mode#

CCM is one of the supportedAEAD algorithms. Applications which use thismode must adhere to certain restrictions when using the cipher API:

  • The authentication tag length must be specified during cipher creation bysetting theauthTagLength option and must be one of 4, 6, 8, 10, 12, 14 or16 bytes.
  • The length of the initialization vector (nonce)N must be between 7 and 13bytes (7 ≤ N ≤ 13).
  • The length of the plaintext is limited to2 ** (8 * (15 - N)) bytes.
  • When decrypting, the authentication tag must be set viasetAuthTag() beforecallingupdate().Otherwise, decryption will fail andfinal() will throw an error incompliance with section 2.6 ofRFC 3610.
  • Using stream methods such aswrite(data),end(data) orpipe() in CCMmode might fail as CCM cannot handle more than one chunk of data per instance.
  • When passing additional authenticated data (AAD), the length of the actualmessage in bytes must be passed tosetAAD() via theplaintextLengthoption.Many crypto libraries include the authentication tag in the ciphertext,which means that they produce ciphertexts of the lengthplaintextLength + authTagLength. Node.js does not include the authenticationtag, so the ciphertext length is alwaysplaintextLength.This is not necessary if no AAD is used.
  • As CCM processes the whole message at once,update() must be called exactlyonce.
  • Even though callingupdate() is sufficient to encrypt/decrypt the message,applicationsmust callfinal() to compute or verify theauthentication tag.
import {Buffer }from'node:buffer';const {  createCipheriv,  createDecipheriv,  randomBytes,} =awaitimport('node:crypto');const key ='keykeykeykeykeykeykeykey';const nonce =randomBytes(12);const aad =Buffer.from('0123456789','hex');const cipher =createCipheriv('aes-192-ccm', key, nonce, {authTagLength:16,});const plaintext ='Hello world';cipher.setAAD(aad, {plaintextLength:Buffer.byteLength(plaintext),});const ciphertext = cipher.update(plaintext,'utf8');cipher.final();const tag = cipher.getAuthTag();// Now transmit { ciphertext, nonce, tag }.const decipher =createDecipheriv('aes-192-ccm', key, nonce, {authTagLength:16,});decipher.setAuthTag(tag);decipher.setAAD(aad, {plaintextLength: ciphertext.length,});const receivedPlaintext = decipher.update(ciphertext,null,'utf8');try {  decipher.final();}catch (err) {thrownewError('Authentication failed!', {cause: err });}console.log(receivedPlaintext);const {Buffer } =require('node:buffer');const {  createCipheriv,  createDecipheriv,  randomBytes,} =require('node:crypto');const key ='keykeykeykeykeykeykeykey';const nonce =randomBytes(12);const aad =Buffer.from('0123456789','hex');const cipher =createCipheriv('aes-192-ccm', key, nonce, {authTagLength:16,});const plaintext ='Hello world';cipher.setAAD(aad, {plaintextLength:Buffer.byteLength(plaintext),});const ciphertext = cipher.update(plaintext,'utf8');cipher.final();const tag = cipher.getAuthTag();// Now transmit { ciphertext, nonce, tag }.const decipher =createDecipheriv('aes-192-ccm', key, nonce, {authTagLength:16,});decipher.setAuthTag(tag);decipher.setAAD(aad, {plaintextLength: ciphertext.length,});const receivedPlaintext = decipher.update(ciphertext,null,'utf8');try {  decipher.final();}catch (err) {thrownewError('Authentication failed!', {cause: err });}console.log(receivedPlaintext);

FIPS mode#

When using OpenSSL 3, Node.js supports FIPS 140-2 when used with an appropriateOpenSSL 3 provider, such as theFIPS provider from OpenSSL 3 which can beinstalled by following the instructions inOpenSSL's FIPS README file.

For FIPS support in Node.js you will need:

  • A correctly installed OpenSSL 3 FIPS provider.
  • An OpenSSL 3FIPS module configuration file.
  • An OpenSSL 3 configuration file that references the FIPS moduleconfiguration file.

Node.js will need to be configured with an OpenSSL configuration file thatpoints to the FIPS provider. An example configuration file looks like this:

nodejs_conf = nodejs_init.include /<absolute path>/fipsmodule.cnf[nodejs_init]providers = provider_sect[provider_sect]default = default_sect# The fips section name should match the section name inside the# included fipsmodule.cnf.fips = fips_sect[default_sect]activate = 1

wherefipsmodule.cnf is the FIPS module configuration file generated from theFIPS provider installation step:

openssl fipsinstall

Set theOPENSSL_CONF environment variable to point toyour configuration file andOPENSSL_MODULES to the location of the FIPSprovider dynamic library. e.g.

export OPENSSL_CONF=/<path to configuration file>/nodejs.cnfexport OPENSSL_MODULES=/<path to openssl lib>/ossl-modules

FIPS mode can then be enabled in Node.js either by:

  • Starting Node.js with--enable-fips or--force-fips command line flags.
  • Programmatically callingcrypto.setFips(true).

Optionally FIPS mode can be enabled in Node.js via the OpenSSL configurationfile. e.g.

nodejs_conf = nodejs_init.include /<absolute path>/fipsmodule.cnf[nodejs_init]providers = provider_sectalg_section = algorithm_sect[provider_sect]default = default_sect# The fips section name should match the section name inside the# included fipsmodule.cnf.fips = fips_sect[default_sect]activate = 1[algorithm_sect]default_properties = fips=yes

Crypto constants#

The following constants exported bycrypto.constants apply to various uses ofthenode:crypto,node:tls, andnode:https modules and are generallyspecific to OpenSSL.

OpenSSL options#

See thelist of SSL OP Flags for details.

ConstantDescription
SSL_OP_ALLApplies multiple bug workarounds within OpenSSL. Seehttps://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html for detail.
SSL_OP_ALLOW_NO_DHE_KEXInstructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3
SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATIONAllows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. Seehttps://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html.
SSL_OP_CIPHER_SERVER_PREFERENCEAttempts to use the server's preferences instead of the client's when selecting a cipher. Behavior depends on protocol version. Seehttps://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html.
SSL_OP_CISCO_ANYCONNECTInstructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER.
SSL_OP_COOKIE_EXCHANGEInstructs OpenSSL to turn on cookie exchange.
SSL_OP_CRYPTOPRO_TLSEXT_BUGInstructs OpenSSL to add server-hello extension from an early version of the cryptopro draft.
SSL_OP_DONT_INSERT_EMPTY_FRAGMENTSInstructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d.
SSL_OP_LEGACY_SERVER_CONNECTAllows initial connection to servers that do not support RI.
SSL_OP_NO_COMPRESSIONInstructs OpenSSL to disable support for SSL/TLS compression.
SSL_OP_NO_ENCRYPT_THEN_MACInstructs OpenSSL to disable encrypt-then-MAC.
SSL_OP_NO_QUERY_MTU
SSL_OP_NO_RENEGOTIATIONInstructs OpenSSL to disable renegotiation.
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATIONInstructs OpenSSL to always start a new session when performing renegotiation.
SSL_OP_NO_SSLv2Instructs OpenSSL to turn off SSL v2
SSL_OP_NO_SSLv3Instructs OpenSSL to turn off SSL v3
SSL_OP_NO_TICKETInstructs OpenSSL to disable use of RFC4507bis tickets.
SSL_OP_NO_TLSv1Instructs OpenSSL to turn off TLS v1
SSL_OP_NO_TLSv1_1Instructs OpenSSL to turn off TLS v1.1
SSL_OP_NO_TLSv1_2Instructs OpenSSL to turn off TLS v1.2
SSL_OP_NO_TLSv1_3Instructs OpenSSL to turn off TLS v1.3
SSL_OP_PRIORITIZE_CHACHAInstructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect ifSSL_OP_CIPHER_SERVER_PREFERENCE is not enabled.
SSL_OP_TLS_ROLLBACK_BUGInstructs OpenSSL to disable version rollback attack detection.

OpenSSL engine constants#

ConstantDescription
ENGINE_METHOD_RSALimit engine usage to RSA
ENGINE_METHOD_DSALimit engine usage to DSA
ENGINE_METHOD_DHLimit engine usage to DH
ENGINE_METHOD_RANDLimit engine usage to RAND
ENGINE_METHOD_ECLimit engine usage to EC
ENGINE_METHOD_CIPHERSLimit engine usage to CIPHERS
ENGINE_METHOD_DIGESTSLimit engine usage to DIGESTS
ENGINE_METHOD_PKEY_METHSLimit engine usage to PKEY_METHS
ENGINE_METHOD_PKEY_ASN1_METHSLimit engine usage to PKEY_ASN1_METHS
ENGINE_METHOD_ALL
ENGINE_METHOD_NONE

Other OpenSSL constants#

ConstantDescription
DH_CHECK_P_NOT_SAFE_PRIME
DH_CHECK_P_NOT_PRIME
DH_UNABLE_TO_CHECK_GENERATOR
DH_NOT_SUITABLE_GENERATOR
RSA_PKCS1_PADDING
RSA_SSLV23_PADDING
RSA_NO_PADDING
RSA_PKCS1_OAEP_PADDING
RSA_X931_PADDING
RSA_PKCS1_PSS_PADDING
RSA_PSS_SALTLEN_DIGESTSets the salt length forRSA_PKCS1_PSS_PADDING to the digest size when signing or verifying.
RSA_PSS_SALTLEN_MAX_SIGNSets the salt length forRSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data.
RSA_PSS_SALTLEN_AUTOCauses the salt length forRSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature.
POINT_CONVERSION_COMPRESSED
POINT_CONVERSION_UNCOMPRESSED
POINT_CONVERSION_HYBRID

Node.js crypto constants#

ConstantDescription
defaultCoreCipherListSpecifies the built-in default cipher list used by Node.js.
defaultCipherListSpecifies the active default cipher list used by the current Node.js process.