{ "type": "module", "source": "doc/api/crypto.md", "modules": [ { "textRaw": "Crypto", "name": "crypto", "introduced_in": "v0.3.6", "stability": 2, "stabilityText": "Stable", "desc": "

Source Code: lib/crypto.js

\n

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

\n
const { createHmac } = await import('crypto');\n\nconst secret = 'abcdefg';\nconst hash = createHmac('sha256', secret)\n               .update('I love cupcakes')\n               .digest('hex');\nconsole.log(hash);\n// Prints:\n//   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e\n
\n
const crypto = require('crypto');\n\nconst secret = 'abcdefg';\nconst hash = crypto.createHmac('sha256', secret)\n                   .update('I love cupcakes')\n                   .digest('hex');\nconsole.log(hash);\n// Prints:\n//   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e\n
", "modules": [ { "textRaw": "Determining if crypto support is unavailable", "name": "determining_if_crypto_support_is_unavailable", "desc": "

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

\n

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

\n
let crypto;\ntry {\n  crypto = require('crypto');\n} catch (err) {\n  console.log('crypto support is disabled!');\n}\n
\n

When using the lexical ESM import keyword, the error can only be\ncaught if a handler for process.on('uncaughtException') is registered\nbefore any attempt to load the module is made -- using, for instance,\na preload module.

\n

When using ESM, if there is a chance that the code may be run on a build\nof Node.js where crypto support is not enabled, consider using the\nimport() function instead of the lexical import keyword:

\n
let crypto;\ntry {\n  crypto = await import('crypto');\n} catch (err) {\n  console.log('crypto support is disabled!');\n}\n
", "type": "module", "displayName": "Determining if crypto support is unavailable" }, { "textRaw": "`crypto` module methods and properties", "name": "`crypto`_module_methods_and_properties", "properties": [ { "textRaw": "`constants` Returns: {Object} An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in [Crypto constants][].", "type": "Object", "name": "return", "meta": { "added": [ "v6.3.0" ], "changes": [] }, "desc": "An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in [Crypto constants][]." }, { "textRaw": "`crypto.DEFAULT_ENCODING`", "name": "DEFAULT_ENCODING", "meta": { "added": [ "v0.9.3" ], "deprecated": [ "v10.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated", "desc": "

The default encoding to use for functions that can take either strings\nor buffers. The default value is 'buffer', which makes methods\ndefault to Buffer objects.

\n

The crypto.DEFAULT_ENCODING mechanism is provided for backward compatibility\nwith legacy programs that expect 'latin1' to be the default encoding.

\n

New applications should expect the default to be 'buffer'.

\n

This property is deprecated.

" }, { "textRaw": "`crypto.fips`", "name": "fips", "meta": { "added": [ "v6.0.0" ], "deprecated": [ "v10.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated", "desc": "

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

\n

This property is deprecated. Please use crypto.setFips() and\ncrypto.getFips() instead.

" }, { "textRaw": "`crypto.webcrypto`", "name": "webcrypto", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "desc": "

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

\n

See the Web Crypto API documentation for details.

" } ], "methods": [ { "textRaw": "`crypto.checkPrime(candidate[, options, [callback]])`", "type": "method", "name": "checkPrime", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`candidate` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint} A possible prime encoded as a sequence of big endian octets of arbitrary length.", "name": "candidate", "type": "ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint", "desc": "A possible prime encoded as a sequence of big endian octets of arbitrary length." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`checks` {number} The number of Miller-Rabin probabilistic primality iterations to perform. When the value is `0` (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. Care must be used when selecting a number of checks. Refer to the OpenSSL documentation for the [`BN_is_prime_ex`][] function `nchecks` options for more details. **Default:** `0`", "name": "checks", "type": "number", "default": "`0`", "desc": "The number of Miller-Rabin probabilistic primality iterations to perform. When the value is `0` (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. Care must be used when selecting a number of checks. Refer to the OpenSSL documentation for the [`BN_is_prime_ex`][] function `nchecks` options for more details." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error} Set to an {Error} object if an error occurred during check.", "name": "err", "type": "Error", "desc": "Set to an {Error} object if an error occurred during check." }, { "textRaw": "`result` {boolean} `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`.", "name": "result", "type": "boolean", "desc": "`true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`." } ] } ] } ], "desc": "

Checks the primality of the candidate.

" }, { "textRaw": "`crypto.checkPrimeSync(candidate[, options])`", "type": "method", "name": "checkPrimeSync", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`.", "name": "return", "type": "boolean", "desc": "`true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`." }, "params": [ { "textRaw": "`candidate` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint} A possible prime encoded as a sequence of big endian octets of arbitrary length.", "name": "candidate", "type": "ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint", "desc": "A possible prime encoded as a sequence of big endian octets of arbitrary length." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`checks` {number} The number of Miller-Rabin probabilistic primality iterations to perform. When the value is `0` (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. Care must be used when selecting a number of checks. Refer to the OpenSSL documentation for the [`BN_is_prime_ex`][] function `nchecks` options for more details. **Default:** `0`", "name": "checks", "type": "number", "default": "`0`", "desc": "The number of Miller-Rabin probabilistic primality iterations to perform. When the value is `0` (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input. Care must be used when selecting a number of checks. Refer to the OpenSSL documentation for the [`BN_is_prime_ex`][] function `nchecks` options for more details." } ] } ] } ], "desc": "

Checks the primality of the candidate.

" }, { "textRaw": "`crypto.createCipher(algorithm, password[, options])`", "type": "method", "name": "createCipher", "meta": { "added": [ "v0.1.94" ], "deprecated": [ "v10.0.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The password argument can be an ArrayBuffer and is limited to a maximum of 2 ** 31 - 1 bytes." }, { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/21447", "description": "Ciphers in OCB mode are now supported." }, { "version": "v10.2.0", "pr-url": "https://github.com/nodejs/node/pull/20235", "description": "The `authTagLength` option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes." } ] }, "stability": 0, "stabilityText": "Deprecated: Use [`crypto.createCipheriv()`][] instead.", "signatures": [ { "return": { "textRaw": "Returns: {Cipher}", "name": "return", "type": "Cipher" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`password` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "password", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]" } ] } ], "desc": "

Creates and returns a Cipher object that uses the given algorithm and\npassword.

\n

The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength\noption is not required but can be used to set the length of the authentication\ntag that will be returned by getAuthTag() and defaults to 16 bytes.

\n

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms\n(openssl list-cipher-algorithms for older versions of OpenSSL) will\ndisplay the available cipher algorithms.

\n

The password is used to derive the cipher key and initialization vector (IV).\nThe value must be either a 'latin1' encoded string, a Buffer, a\nTypedArray, or a DataView.

\n

The implementation of crypto.createCipher() derives keys using the OpenSSL\nfunction EVP_BytesToKey with the digest algorithm set to MD5, one\niteration, and no salt. The lack of salt allows dictionary attacks as the same\npassword always creates the same key. The low iteration count and\nnon-cryptographically secure hash algorithm allow passwords to be tested very\nrapidly.

\n

In line with OpenSSL's recommendation to use a more modern algorithm instead of\nEVP_BytesToKey it is recommended that developers derive a key and IV on\ntheir own using crypto.scrypt() and to use crypto.createCipheriv()\nto create the Cipher object. Users should not use ciphers with counter mode\n(e.g. CTR, GCM, or CCM) in crypto.createCipher(). A warning is emitted when\nthey are used in order to avoid the risk of IV reuse that causes\nvulnerabilities. For the case when IV is reused in GCM, see Nonce-Disrespecting\nAdversaries for details.

" }, { "textRaw": "`crypto.createCipheriv(algorithm, key, iv[, options])`", "type": "method", "name": "createCipheriv", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The password and iv arguments can be an ArrayBuffer and are each limited to a maximum of 2 ** 31 - 1 bytes." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "The `key` argument can now be a `KeyObject`." }, { "version": [ "v11.2.0", "v10.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/24081", "description": "The cipher `chacha20-poly1305` is now supported." }, { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/21447", "description": "Ciphers in OCB mode are now supported." }, { "version": "v10.2.0", "pr-url": "https://github.com/nodejs/node/pull/20235", "description": "The `authTagLength` option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes." }, { "version": "v9.9.0", "pr-url": "https://github.com/nodejs/node/pull/18644", "description": "The `iv` parameter may now be `null` for ciphers which do not need an initialization vector." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Cipher}", "name": "return", "type": "Cipher" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}", "name": "key", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey" }, { "textRaw": "`iv` {string|ArrayBuffer|Buffer|TypedArray|DataView|null}", "name": "iv", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView|null" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]" } ] } ], "desc": "

Creates and returns a Cipher object, with the given algorithm, key and\ninitialization vector (iv).

\n

The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength\noption is not required but can be used to set the length of the authentication\ntag that will be returned by getAuthTag() and defaults to 16 bytes.

\n

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms\n(openssl list-cipher-algorithms for older versions of OpenSSL) will\ndisplay the available cipher algorithms.

\n

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

\n

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

\n

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

" }, { "textRaw": "`crypto.createDecipher(algorithm, password[, options])`", "type": "method", "name": "createDecipher", "meta": { "added": [ "v0.1.94" ], "deprecated": [ "v10.0.0" ], "changes": [ { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/21447", "description": "Ciphers in OCB mode are now supported." } ] }, "stability": 0, "stabilityText": "Deprecated: Use [`crypto.createDecipheriv()`][] instead.", "signatures": [ { "return": { "textRaw": "Returns: {Decipher}", "name": "return", "type": "Decipher" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`password` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "password", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]" } ] } ], "desc": "

Creates and returns a Decipher object that uses the given algorithm and\npassword (key).

\n

The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode.

\n

The implementation of crypto.createDecipher() derives keys using the OpenSSL\nfunction EVP_BytesToKey with the digest algorithm set to MD5, one\niteration, and no salt. The lack of salt allows dictionary attacks as the same\npassword always creates the same key. The low iteration count and\nnon-cryptographically secure hash algorithm allow passwords to be tested very\nrapidly.

\n

In line with OpenSSL's recommendation to use a more modern algorithm instead of\nEVP_BytesToKey it is recommended that developers derive a key and IV on\ntheir own using crypto.scrypt() and to use crypto.createDecipheriv()\nto create the Decipher object.

" }, { "textRaw": "`crypto.createDecipheriv(algorithm, key, iv[, options])`", "type": "method", "name": "createDecipheriv", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "The `key` argument can now be a `KeyObject`." }, { "version": [ "v11.2.0", "v10.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/24081", "description": "The cipher `chacha20-poly1305` is now supported." }, { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/21447", "description": "Ciphers in OCB mode are now supported." }, { "version": "v10.2.0", "pr-url": "https://github.com/nodejs/node/pull/20039", "description": "The `authTagLength` option can now be used to restrict accepted GCM authentication tag lengths." }, { "version": "v9.9.0", "pr-url": "https://github.com/nodejs/node/pull/18644", "description": "The `iv` parameter may now be `null` for ciphers which do not need an initialization vector." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Decipher}", "name": "return", "type": "Decipher" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}", "name": "key", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey" }, { "textRaw": "`iv` {string|ArrayBuffer|Buffer|TypedArray|DataView|null}", "name": "iv", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView|null" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]" } ] } ], "desc": "

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

\n

The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. 'aes-128-ccm'). In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength\noption is not required but can be used to restrict accepted authentication tags\nto those with the specified length.

\n

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms\n(openssl list-cipher-algorithms for older versions of OpenSSL) will\ndisplay the available cipher algorithms.

\n

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

\n

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

\n

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

" }, { "textRaw": "`crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])`", "type": "method", "name": "createDiffieHellman", "meta": { "added": [ "v0.11.12" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/12223", "description": "The `prime` argument can be any `TypedArray` or `DataView` now." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11983", "description": "The `prime` argument can be a `Uint8Array` now." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default for the encoding parameters changed from `binary` to `utf8`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {DiffieHellman}", "name": "return", "type": "DiffieHellman" }, "params": [ { "textRaw": "`prime` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "prime", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`primeEncoding` {string} The [encoding][] of the `prime` string.", "name": "primeEncoding", "type": "string", "desc": "The [encoding][] of the `prime` string." }, { "textRaw": "`generator` {number|string|ArrayBuffer|Buffer|TypedArray|DataView} **Default:** `2`", "name": "generator", "type": "number|string|ArrayBuffer|Buffer|TypedArray|DataView", "default": "`2`" }, { "textRaw": "`generatorEncoding` {string} The [encoding][] of the `generator` string.", "name": "generatorEncoding", "type": "string", "desc": "The [encoding][] of the `generator` string." } ] } ], "desc": "

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

\n

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

\n

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

\n

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

" }, { "textRaw": "`crypto.createDiffieHellman(primeLength[, generator])`", "type": "method", "name": "createDiffieHellman", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {DiffieHellman}", "name": "return", "type": "DiffieHellman" }, "params": [ { "textRaw": "`primeLength` {number}", "name": "primeLength", "type": "number" }, { "textRaw": "`generator` {number} **Default:** `2`", "name": "generator", "type": "number", "default": "`2`" } ] } ], "desc": "

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

" }, { "textRaw": "`crypto.createDiffieHellmanGroup(name)`", "type": "method", "name": "createDiffieHellmanGroup", "meta": { "added": [ "v0.9.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {DiffieHellmanGroup}", "name": "return", "type": "DiffieHellmanGroup" }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" } ] } ], "desc": "

An alias for crypto.getDiffieHellman()

" }, { "textRaw": "`crypto.createECDH(curveName)`", "type": "method", "name": "createECDH", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {ECDH}", "name": "return", "type": "ECDH" }, "params": [ { "textRaw": "`curveName` {string}", "name": "curveName", "type": "string" } ] } ], "desc": "

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

" }, { "textRaw": "`crypto.createHash(algorithm[, options])`", "type": "method", "name": "createHash", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v12.8.0", "pr-url": "https://github.com/nodejs/node/pull/28805", "description": "The `outputLength` option was added for XOF hash functions." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Hash}", "name": "return", "type": "Hash" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]" } ] } ], "desc": "

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

\n

The algorithm is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc.\nOn recent releases of OpenSSL, openssl list -digest-algorithms\n(openssl list-message-digest-algorithms for older versions of OpenSSL) will\ndisplay the available digest algorithms.

\n

Example: generating the sha256 sum of a file

\n
import {\n  createReadStream\n} from 'fs';\nimport { argv } from 'process';\nconst {\n  createHash\n} = await import('crypto');\n\nconst filename = argv[2];\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream(filename);\ninput.on('readable', () => {\n  // Only one element is going to be produced by the\n  // hash stream.\n  const data = input.read();\n  if (data)\n    hash.update(data);\n  else {\n    console.log(`${hash.digest('hex')} ${filename}`);\n  }\n});\n
\n
const {\n  createReadStream,\n} = require('fs');\nconst {\n  createHash,\n} = require('crypto');\nconst { argv } = require('process');\n\nconst filename = argv[2];\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream(filename);\ninput.on('readable', () => {\n  // Only one element is going to be produced by the\n  // hash stream.\n  const data = input.read();\n  if (data)\n    hash.update(data);\n  else {\n    console.log(`${hash.digest('hex')} ${filename}`);\n  }\n});\n
" }, { "textRaw": "`crypto.createHmac(algorithm, key[, options])`", "type": "method", "name": "createHmac", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The key can also be an ArrayBuffer or CryptoKey. The encoding option was added. The key cannot contain more than 2 ** 32 - 1 bytes." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "The `key` argument can now be a `KeyObject`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Hmac}", "name": "return", "type": "Hmac" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}", "name": "key", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]", "options": [ { "textRaw": "`encoding` {string} The string encoding to use when `key` is a string.", "name": "encoding", "type": "string", "desc": "The string encoding to use when `key` is a string." } ] } ] } ], "desc": "

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

\n

The algorithm is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc.\nOn recent releases of OpenSSL, openssl list -digest-algorithms\n(openssl list-message-digest-algorithms for older versions of OpenSSL) will\ndisplay the available digest algorithms.

\n

The key is the HMAC key used to generate the cryptographic HMAC hash. If it is\na KeyObject, its type must be secret.

\n

Example: generating the sha256 HMAC of a file

\n
import {\n  createReadStream\n} from 'fs';\nimport { argv } from 'process';\nconst {\n  createHmac\n} = await import('crypto');\n\nconst filename = argv[2];\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream(filename);\ninput.on('readable', () => {\n  // Only one element is going to be produced by the\n  // hash stream.\n  const data = input.read();\n  if (data)\n    hmac.update(data);\n  else {\n    console.log(`${hmac.digest('hex')} ${filename}`);\n  }\n});\n
\n
const {\n  createReadStream,\n} = require('fs');\nconst {\n  createHmac,\n} = require('crypto');\nconst { argv } = require('process');\n\nconst filename = argv[2];\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream(filename);\ninput.on('readable', () => {\n  // Only one element is going to be produced by the\n  // hash stream.\n  const data = input.read();\n  if (data)\n    hmac.update(data);\n  else {\n    console.log(`${hmac.digest('hex')} ${filename}`);\n  }\n});\n
" }, { "textRaw": "`crypto.createPrivateKey(key)`", "type": "method", "name": "createPrivateKey", "meta": { "added": [ "v11.6.0" ], "changes": [ { "version": "v15.12.0", "pr-url": "https://github.com/nodejs/node/pull/37254", "description": "The key can also be a JWK object." }, { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The key can also be an ArrayBuffer. The encoding option was added. The key cannot contain more than 2 ** 32 - 1 bytes." } ] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

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

\n

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

" }, { "textRaw": "`crypto.createPublicKey(key)`", "type": "method", "name": "createPublicKey", "meta": { "added": [ "v11.6.0" ], "changes": [ { "version": "v15.12.0", "pr-url": "https://github.com/nodejs/node/pull/37254", "description": "The key can also be a JWK object." }, { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The key can also be an ArrayBuffer. The encoding option was added. The key cannot contain more than 2 ** 32 - 1 bytes." }, { "version": "v11.13.0", "pr-url": "https://github.com/nodejs/node/pull/26278", "description": "The `key` argument can now be a `KeyObject` with type `private`." }, { "version": "v11.7.0", "pr-url": "https://github.com/nodejs/node/pull/25217", "description": "The `key` argument can now be a private key." } ] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

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

\n

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

\n

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

" }, { "textRaw": "`crypto.createSecretKey(key[, encoding])`", "type": "method", "name": "createSecretKey", "meta": { "added": [ "v11.6.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The key can also be an ArrayBuffer or string. The encoding argument was added. The key cannot contain more than 2 ** 32 - 1 bytes." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {KeyObject}", "name": "return", "type": "KeyObject" }, "params": [ { "textRaw": "`key` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "key", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The string encoding when `key` is a string.", "name": "encoding", "type": "string", "desc": "The string encoding when `key` is a string." } ] } ], "desc": "

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

" }, { "textRaw": "`crypto.createSign(algorithm[, options])`", "type": "method", "name": "createSign", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Sign}", "name": "return", "type": "Sign" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`options` {Object} [`stream.Writable` options][]", "name": "options", "type": "Object", "desc": "[`stream.Writable` options][]" } ] } ], "desc": "

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

\n

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

" }, { "textRaw": "`crypto.createVerify(algorithm[, options])`", "type": "method", "name": "createVerify", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Verify}", "name": "return", "type": "Verify" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`options` {Object} [`stream.Writable` options][]", "name": "options", "type": "Object", "desc": "[`stream.Writable` options][]" } ] } ], "desc": "

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

\n

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

" }, { "textRaw": "`crypto.diffieHellman(options)`", "type": "method", "name": "diffieHellman", "meta": { "added": [ "v13.9.0", "v12.17.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "params": [ { "textRaw": "`options`: {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`privateKey`: {KeyObject}", "name": "privateKey", "type": "KeyObject" }, { "textRaw": "`publicKey`: {KeyObject}", "name": "publicKey", "type": "KeyObject" } ] } ] } ], "desc": "

Computes the Diffie-Hellman secret based on a privateKey and a publicKey.\nBoth keys must have the same asymmetricKeyType, which must be one of 'dh'\n(for Diffie-Hellman), 'ec' (for ECDH), 'x448', or 'x25519' (for ECDH-ES).

" }, { "textRaw": "`crypto.generateKey(type, options, callback)`", "type": "method", "name": "generateKey", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`type`: {string} The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`.", "name": "type", "type": "string", "desc": "The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`." }, { "textRaw": "`options`: {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`length`: {number} The bit length of the key to generate. This must be a value greater than 0.", "name": "length", "type": "number", "desc": "The bit length of the key to generate. This must be a value greater than 0.", "options": [ { "textRaw": "If `type` is `'hmac'`, the minimum is 1, and the maximum length is 231-1. If the value is not a multiple of 8, the generated key will be truncated to `Math.floor(length / 8)`.", "name": "If", "desc": "`type` is `'hmac'`, the minimum is 1, and the maximum length is 231-1. If the value is not a multiple of 8, the generated key will be truncated to `Math.floor(length / 8)`." }, { "textRaw": "If `type` is `'aes'`, the length must be one of `128`, `192`, or `256`.", "name": "If", "desc": "`type` is `'aes'`, the length must be one of `128`, `192`, or `256`." } ] } ] }, { "textRaw": "`callback`: {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err`: {Error}", "name": "err", "type": "Error" }, { "textRaw": "`key`: {KeyObject}", "name": "key", "type": "KeyObject" } ] } ] } ], "desc": "

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

\n
const {\n  generateKey\n} = await import('crypto');\n\ngenerateKey('hmac', { length: 64 }, (err, key) => {\n  if (err) throw err;\n  console.log(key.export().toString('hex'));  // 46e..........620\n});\n
\n
const {\n  generateKey,\n} = require('crypto');\n\ngenerateKey('hmac', { length: 64 }, (err, key) => {\n  if (err) throw err;\n  console.log(key.export().toString('hex'));  // 46e..........620\n});\n
" }, { "textRaw": "`crypto.generateKeyPair(type, options, callback)`", "type": "method", "name": "generateKeyPair", "meta": { "added": [ "v10.12.0" ], "changes": [ { "version": [ "v13.9.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/31178", "description": "Add support for Diffie-Hellman." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26774", "description": "Add ability to generate X25519 and X448 key pairs." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26554", "description": "Add ability to generate Ed25519 and Ed448 key pairs." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "The `generateKeyPair` and `generateKeyPairSync` functions now produce key objects if no encoding was specified." } ] }, "signatures": [ { "params": [ { "textRaw": "`type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.", "name": "type", "type": "string", "desc": "Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`." }, { "textRaw": "`options`: {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`modulusLength`: {number} Key size in bits (RSA, DSA).", "name": "modulusLength", "type": "number", "desc": "Key size in bits (RSA, DSA)." }, { "textRaw": "`publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.", "name": "publicExponent", "type": "number", "default": "`0x10001`", "desc": "Public exponent (RSA)." }, { "textRaw": "`divisorLength`: {number} Size of `q` in bits (DSA).", "name": "divisorLength", "type": "number", "desc": "Size of `q` in bits (DSA)." }, { "textRaw": "`namedCurve`: {string} Name of the curve to use (EC).", "name": "namedCurve", "type": "string", "desc": "Name of the curve to use (EC)." }, { "textRaw": "`prime`: {Buffer} The prime parameter (DH).", "name": "prime", "type": "Buffer", "desc": "The prime parameter (DH)." }, { "textRaw": "`primeLength`: {number} Prime length in bits (DH).", "name": "primeLength", "type": "number", "desc": "Prime length in bits (DH)." }, { "textRaw": "`generator`: {number} Custom generator (DH). **Default:** `2`.", "name": "generator", "type": "number", "default": "`2`", "desc": "Custom generator (DH)." }, { "textRaw": "`groupName`: {string} Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][].", "name": "groupName", "type": "string", "desc": "Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][]." }, { "textRaw": "`publicKeyEncoding`: {Object} See [`keyObject.export()`][].", "name": "publicKeyEncoding", "type": "Object", "desc": "See [`keyObject.export()`][]." }, { "textRaw": "`privateKeyEncoding`: {Object} See [`keyObject.export()`][].", "name": "privateKeyEncoding", "type": "Object", "desc": "See [`keyObject.export()`][]." } ] }, { "textRaw": "`callback`: {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err`: {Error}", "name": "err", "type": "Error" }, { "textRaw": "`publicKey`: {string | Buffer | KeyObject}", "name": "publicKey", "type": "string | Buffer | KeyObject" }, { "textRaw": "`privateKey`: {string | Buffer | KeyObject}", "name": "privateKey", "type": "string | Buffer | KeyObject" } ] } ] } ], "desc": "

Generates a new asymmetric key pair of the given type. RSA, DSA, EC, Ed25519,\nEd448, X25519, X448, and DH are currently supported.

\n

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

\n

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

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

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

\n

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

" }, { "textRaw": "`crypto.generateKeyPairSync(type, options)`", "type": "method", "name": "generateKeyPairSync", "meta": { "added": [ "v10.12.0" ], "changes": [ { "version": [ "v13.9.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/31178", "description": "Add support for Diffie-Hellman." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26554", "description": "Add ability to generate Ed25519 and Ed448 key pairs." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "The `generateKeyPair` and `generateKeyPairSync` functions now produce key objects if no encoding was specified." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`publicKey`: {string | Buffer | KeyObject}", "name": "publicKey", "type": "string | Buffer | KeyObject" }, { "textRaw": "`privateKey`: {string | Buffer | KeyObject}", "name": "privateKey", "type": "string | Buffer | KeyObject" } ] }, "params": [ { "textRaw": "`type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.", "name": "type", "type": "string", "desc": "Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`." }, { "textRaw": "`options`: {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`modulusLength`: {number} Key size in bits (RSA, DSA).", "name": "modulusLength", "type": "number", "desc": "Key size in bits (RSA, DSA)." }, { "textRaw": "`publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.", "name": "publicExponent", "type": "number", "default": "`0x10001`", "desc": "Public exponent (RSA)." }, { "textRaw": "`divisorLength`: {number} Size of `q` in bits (DSA).", "name": "divisorLength", "type": "number", "desc": "Size of `q` in bits (DSA)." }, { "textRaw": "`namedCurve`: {string} Name of the curve to use (EC).", "name": "namedCurve", "type": "string", "desc": "Name of the curve to use (EC)." }, { "textRaw": "`prime`: {Buffer} The prime parameter (DH).", "name": "prime", "type": "Buffer", "desc": "The prime parameter (DH)." }, { "textRaw": "`primeLength`: {number} Prime length in bits (DH).", "name": "primeLength", "type": "number", "desc": "Prime length in bits (DH)." }, { "textRaw": "`generator`: {number} Custom generator (DH). **Default:** `2`.", "name": "generator", "type": "number", "default": "`2`", "desc": "Custom generator (DH)." }, { "textRaw": "`groupName`: {string} Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][].", "name": "groupName", "type": "string", "desc": "Diffie-Hellman group name (DH). See [`crypto.getDiffieHellman()`][]." }, { "textRaw": "`publicKeyEncoding`: {Object} See [`keyObject.export()`][].", "name": "publicKeyEncoding", "type": "Object", "desc": "See [`keyObject.export()`][]." }, { "textRaw": "`privateKeyEncoding`: {Object} See [`keyObject.export()`][].", "name": "privateKeyEncoding", "type": "Object", "desc": "See [`keyObject.export()`][]." } ] } ] } ], "desc": "

Generates a new asymmetric key pair of the given type. RSA, DSA, EC, Ed25519,\nEd448, X25519, X448, and DH are currently supported.

\n

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

\n

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

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

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

" }, { "textRaw": "`crypto.generateKeySync(type, options)`", "type": "method", "name": "generateKeySync", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {KeyObject}", "name": "return", "type": "KeyObject" }, "params": [ { "textRaw": "`type`: {string} The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`.", "name": "type", "type": "string", "desc": "The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`." }, { "textRaw": "`options`: {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`length`: {number} The bit length of the key to generate.", "name": "length", "type": "number", "desc": "The bit length of the key to generate.", "options": [ { "textRaw": "If `type` is `'hmac'`, the minimum is 1, and the maximum length is 231-1. If the value is not a multiple of 8, the generated key will be truncated to `Math.floor(length / 8)`.", "name": "If", "desc": "`type` is `'hmac'`, the minimum is 1, and the maximum length is 231-1. If the value is not a multiple of 8, the generated key will be truncated to `Math.floor(length / 8)`." }, { "textRaw": "If `type` is `'aes'`, the length must be one of `128`, `192`, or `256`.", "name": "If", "desc": "`type` is `'aes'`, the length must be one of `128`, `192`, or `256`." } ] } ] } ] } ], "desc": "

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

\n
const {\n  generateKeySync\n} = await import('crypto');\n\nconst key = generateKeySync('hmac', 64);\nconsole.log(key.export().toString('hex'));  // e89..........41e\n
\n
const {\n  generateKeySync,\n} = require('crypto');\n\nconst key = generateKeySync('hmac', 64);\nconsole.log(key.export().toString('hex'));  // e89..........41e\n
" }, { "textRaw": "`crypto.generatePrime(size[, options[, callback]])`", "type": "method", "name": "generatePrime", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`size` {number} The size (in bits) of the prime to generate.", "name": "size", "type": "number", "desc": "The size (in bits) of the prime to generate." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`add` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint}", "name": "add", "type": "ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint" }, { "textRaw": "`rem` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint}", "name": "rem", "type": "ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint" }, { "textRaw": "`safe` {boolean} **Default:** `false`.", "name": "safe", "type": "boolean", "default": "`false`" }, { "textRaw": "`bigint` {boolean} When `true`, the generated prime is returned as a `bigint`.", "name": "bigint", "type": "boolean", "desc": "When `true`, the generated prime is returned as a `bigint`." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`prime` {ArrayBuffer|bigint}", "name": "prime", "type": "ArrayBuffer|bigint" } ] } ] } ], "desc": "

Generates a pseudorandom prime of size bits.

\n

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

\n

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

\n\n

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

\n

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

" }, { "textRaw": "`crypto.generatePrimeSync(size[, options])`", "type": "method", "name": "generatePrimeSync", "meta": { "added": [ "v15.8.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {ArrayBuffer|bigint}", "name": "return", "type": "ArrayBuffer|bigint" }, "params": [ { "textRaw": "`size` {number} The size (in bits) of the prime to generate.", "name": "size", "type": "number", "desc": "The size (in bits) of the prime to generate." }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`add` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint}", "name": "add", "type": "ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint" }, { "textRaw": "`rem` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint}", "name": "rem", "type": "ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint" }, { "textRaw": "`safe` {boolean} **Default:** `false`.", "name": "safe", "type": "boolean", "default": "`false`" }, { "textRaw": "`bigint` {boolean} When `true`, the generated prime is returned as a `bigint`.", "name": "bigint", "type": "boolean", "desc": "When `true`, the generated prime is returned as a `bigint`." } ] } ] } ], "desc": "

Generates a pseudorandom prime of size bits.

\n

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

\n

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

\n\n

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

\n

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

" }, { "textRaw": "`crypto.getCipherInfo(nameOrNid[, options])`", "type": "method", "name": "getCipherInfo", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`name` {string} The name of the cipher", "name": "name", "type": "string", "desc": "The name of the cipher" }, { "textRaw": "`nid` {number} The nid of the cipher", "name": "nid", "type": "number", "desc": "The nid of the cipher" }, { "textRaw": "`blockSize` {number} The block size of the cipher in bytes. This property is omitted when `mode` is `'stream'`.", "name": "blockSize", "type": "number", "desc": "The block size of the cipher in bytes. This property is omitted when `mode` is `'stream'`." }, { "textRaw": "`ivLength` {number} The expected or default initialization vector length in bytes. This property is omitted if the cipher does not use an initialization vector.", "name": "ivLength", "type": "number", "desc": "The expected or default initialization vector length in bytes. This property is omitted if the cipher does not use an initialization vector." }, { "textRaw": "`keyLength` {number} The expected or default key length in bytes.", "name": "keyLength", "type": "number", "desc": "The expected or default key length in bytes." }, { "textRaw": "`mode` {string} The cipher mode. One of `'cbc'`, `'ccm'`, `'cfb'`, `'ctr'`, `'ecb'`, `'gcm'`, `'ocb'`, `'ofb'`, `'stream'`, `'wrap'`, `'xts'`.", "name": "mode", "type": "string", "desc": "The cipher mode. One of `'cbc'`, `'ccm'`, `'cfb'`, `'ctr'`, `'ecb'`, `'gcm'`, `'ocb'`, `'ofb'`, `'stream'`, `'wrap'`, `'xts'`." } ] }, "params": [ { "textRaw": "`nameOrNid`: {string|number} The name or nid of the cipher to query.", "name": "nameOrNid", "type": "string|number", "desc": "The name or nid of the cipher to query." }, { "textRaw": "`options`: {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`keyLength`: {number} A test key length.", "name": "keyLength", "type": "number", "desc": "A test key length." }, { "textRaw": "`ivLength`: {number} A test IV length.", "name": "ivLength", "type": "number", "desc": "A test IV length." } ] } ] } ], "desc": "

Returns information about a given cipher.

\n

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

" }, { "textRaw": "`crypto.getCiphers()`", "type": "method", "name": "getCiphers", "meta": { "added": [ "v0.9.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]} An array with the names of the supported cipher algorithms.", "name": "return", "type": "string[]", "desc": "An array with the names of the supported cipher algorithms." }, "params": [] } ], "desc": "
const {\n  getCiphers\n} = await import('crypto');\n\nconsole.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]\n
\n
const {\n  getCiphers,\n} = require('crypto');\n\nconsole.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]\n
" }, { "textRaw": "`crypto.getCurves()`", "type": "method", "name": "getCurves", "meta": { "added": [ "v2.3.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]} An array with the names of the supported elliptic curves.", "name": "return", "type": "string[]", "desc": "An array with the names of the supported elliptic curves." }, "params": [] } ], "desc": "
const {\n  getCurves\n} = await import('crypto');\n\nconsole.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n
\n
const {\n  getCurves,\n} = require('crypto');\n\nconsole.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n
" }, { "textRaw": "`crypto.getDiffieHellman(groupName)`", "type": "method", "name": "getDiffieHellman", "meta": { "added": [ "v0.7.5" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {DiffieHellmanGroup}", "name": "return", "type": "DiffieHellmanGroup" }, "params": [ { "textRaw": "`groupName` {string}", "name": "groupName", "type": "string" } ] } ], "desc": "

Creates a predefined DiffieHellmanGroup key exchange object. The\nsupported groups are: 'modp1', 'modp2', 'modp5' (defined in\nRFC 2412, but see Caveats) and 'modp14', 'modp15',\n'modp16', 'modp17', 'modp18' (defined in RFC 3526). The\nreturned object mimics the interface of objects created by\ncrypto.createDiffieHellman(), but will not allow changing\nthe keys (with diffieHellman.setPublicKey(), for example). The\nadvantage of using this method is that the parties do not have to\ngenerate nor exchange a group modulus beforehand, saving both processor\nand communication time.

\n

Example (obtaining a shared secret):

\n
const {\n  getDiffieHellman\n} = await import('crypto');\nconst alice = getDiffieHellman('modp14');\nconst bob = getDiffieHellman('modp14');\n\nalice.generateKeys();\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n/* aliceSecret and bobSecret should be the same */\nconsole.log(aliceSecret === bobSecret);\n
\n
const {\n  getDiffieHellman,\n} = require('crypto');\n\nconst alice = getDiffieHellman('modp14');\nconst bob = getDiffieHellman('modp14');\n\nalice.generateKeys();\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n/* aliceSecret and bobSecret should be the same */\nconsole.log(aliceSecret === bobSecret);\n
" }, { "textRaw": "`crypto.getFips()`", "type": "method", "name": "getFips", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {number} `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}.", "name": "return", "type": "number", "desc": "`1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}." }, "params": [] } ] }, { "textRaw": "`crypto.getHashes()`", "type": "method", "name": "getHashes", "meta": { "added": [ "v0.9.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]} An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called \"digest\" algorithms.", "name": "return", "type": "string[]", "desc": "An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called \"digest\" algorithms." }, "params": [] } ], "desc": "
const {\n  getHashes\n} = await import('crypto');\n\nconsole.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n
\n
const {\n  getHashes,\n} = require('crypto');\n\nconsole.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n
" }, { "textRaw": "`crypto.hkdf(digest, ikm, salt, info, keylen, callback)`", "type": "method", "name": "hkdf", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`digest` {string} The digest algorithm to use.", "name": "digest", "type": "string", "desc": "The digest algorithm to use." }, { "textRaw": "`ikm` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject} The input keying material. It must be at least one byte in length.", "name": "ikm", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject", "desc": "The input keying material. It must be at least one byte in length." }, { "textRaw": "`salt` {string|ArrayBuffer|Buffer|TypedArray|DataView} The salt value. Must be provided but can be zero-length.", "name": "salt", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView", "desc": "The salt value. Must be provided but can be zero-length." }, { "textRaw": "`info` {string|ArrayBuffer|Buffer|TypedArray|DataView} Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.", "name": "info", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView", "desc": "Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes." }, { "textRaw": "`keylen` {number} The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` generates 64-byte hashes, making the maximum HKDF output 16320 bytes).", "name": "keylen", "type": "number", "desc": "The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` generates 64-byte hashes, making the maximum HKDF output 16320 bytes)." }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`derivedKey` {ArrayBuffer}", "name": "derivedKey", "type": "ArrayBuffer" } ] } ] } ], "desc": "

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

\n

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

\n
import { Buffer } from 'buffer';\nconst {\n  hkdf\n} = await import('crypto');\n\nhkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {\n  if (err) throw err;\n  console.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'\n});\n
\n
const {\n  hkdf,\n} = require('crypto');\nconst { Buffer } = require('buffer');\n\nhkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {\n  if (err) throw err;\n  console.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'\n});\n
" }, { "textRaw": "`crypto.hkdfSync(digest, ikm, salt, info, keylen)`", "type": "method", "name": "hkdfSync", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {ArrayBuffer}", "name": "return", "type": "ArrayBuffer" }, "params": [ { "textRaw": "`digest` {string} The digest algorithm to use.", "name": "digest", "type": "string", "desc": "The digest algorithm to use." }, { "textRaw": "`ikm` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject} The input keying material. It must be at least one byte in length.", "name": "ikm", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject", "desc": "The input keying material. It must be at least one byte in length." }, { "textRaw": "`salt` {string|ArrayBuffer|Buffer|TypedArray|DataView} The salt value. Must be provided but can be zero-length.", "name": "salt", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView", "desc": "The salt value. Must be provided but can be zero-length." }, { "textRaw": "`info` {string|ArrayBuffer|Buffer|TypedArray|DataView} Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.", "name": "info", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView", "desc": "Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes." }, { "textRaw": "`keylen` {number} The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` generates 64-byte hashes, making the maximum HKDF output 16320 bytes).", "name": "keylen", "type": "number", "desc": "The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` generates 64-byte hashes, making the maximum HKDF output 16320 bytes)." } ] } ], "desc": "

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

\n

The successfully generated derivedKey will be returned as an <ArrayBuffer>.

\n

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

\n
import { Buffer } from 'buffer';\nconst {\n  hkdfSync\n} = await import('crypto');\n\nconst derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);\nconsole.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'\n
\n
const {\n  hkdfSync,\n} = require('crypto');\nconst { Buffer } = require('buffer');\n\nconst derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);\nconsole.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'\n
" }, { "textRaw": "`crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)`", "type": "method", "name": "pbkdf2", "meta": { "added": [ "v0.5.5" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The password and salt arguments can also be ArrayBuffer instances." }, { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/30578", "description": "The `iterations` parameter is now restricted to positive values. Earlier releases treated other values as one." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11305", "description": "The `digest` parameter is always required now." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/4047", "description": "Calling this function without passing the `digest` parameter is deprecated now and will emit a warning." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default encoding for `password` if it is a string changed from `binary` to `utf8`." } ] }, "signatures": [ { "params": [ { "textRaw": "`password` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "password", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`salt` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "salt", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`iterations` {number}", "name": "iterations", "type": "number" }, { "textRaw": "`keylen` {number}", "name": "keylen", "type": "number" }, { "textRaw": "`digest` {string}", "name": "digest", "type": "string" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`derivedKey` {Buffer}", "name": "derivedKey", "type": "Buffer" } ] } ] } ], "desc": "

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

\n

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

\n

If digest is null, 'sha1' will be used. This behavior is deprecated,\nplease specify a digest explicitly.

\n

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

\n

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

\n

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

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

The crypto.DEFAULT_ENCODING property can be used to change the way the\nderivedKey is passed to the callback. This property, however, has been\ndeprecated and use should be avoided.

\n
import crypto from 'crypto';\ncrypto.DEFAULT_ENCODING = 'hex';\ncrypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey);  // '3745e48...aa39b34'\n});\n
\n
const crypto = require('crypto');\ncrypto.DEFAULT_ENCODING = 'hex';\ncrypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey);  // '3745e48...aa39b34'\n});\n
\n

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

\n

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

" }, { "textRaw": "`crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)`", "type": "method", "name": "pbkdf2Sync", "meta": { "added": [ "v0.9.3" ], "changes": [ { "version": "v14.0.0", "pr-url": "https://github.com/nodejs/node/pull/30578", "description": "The `iterations` parameter is now restricted to positive values. Earlier releases treated other values as one." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/4047", "description": "Calling this function without passing the `digest` parameter is deprecated now and will emit a warning." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default encoding for `password` if it is a string changed from `binary` to `utf8`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "params": [ { "textRaw": "`password` {string|Buffer|TypedArray|DataView}", "name": "password", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`salt` {string|Buffer|TypedArray|DataView}", "name": "salt", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`iterations` {number}", "name": "iterations", "type": "number" }, { "textRaw": "`keylen` {number}", "name": "keylen", "type": "number" }, { "textRaw": "`digest` {string}", "name": "digest", "type": "string" } ] } ], "desc": "

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

\n

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

\n

If digest is null, 'sha1' will be used. This behavior is deprecated,\nplease specify a digest explicitly.

\n

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

\n

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

\n

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

\n
const {\n  pbkdf2Sync\n} = await import('crypto');\n\nconst key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');\nconsole.log(key.toString('hex'));  // '3745e48...08d59ae'\n
\n
const {\n  pbkdf2Sync,\n} = require('crypto');\n\nconst key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');\nconsole.log(key.toString('hex'));  // '3745e48...08d59ae'\n
\n

The crypto.DEFAULT_ENCODING property may be used to change the way the\nderivedKey is returned. This property, however, is deprecated and use\nshould be avoided.

\n
import crypto from 'crypto';\ncrypto.DEFAULT_ENCODING = 'hex';\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');\nconsole.log(key);  // '3745e48...aa39b34'\n
\n
const crypto = require('crypto');\ncrypto.DEFAULT_ENCODING = 'hex';\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');\nconsole.log(key);  // '3745e48...aa39b34'\n
\n

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

" }, { "textRaw": "`crypto.privateDecrypt(privateKey, buffer)`", "type": "method", "name": "privateDecrypt", "meta": { "added": [ "v0.11.14" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "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." }, { "version": "v12.11.0", "pr-url": "https://github.com/nodejs/node/pull/29489", "description": "The `oaepLabel` option was added." }, { "version": "v12.9.0", "pr-url": "https://github.com/nodejs/node/pull/28335", "description": "The `oaepHash` option was added." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "This function now supports key objects." } ] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

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

\n

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

" }, { "textRaw": "`crypto.privateEncrypt(privateKey, buffer)`", "type": "method", "name": "privateEncrypt", "meta": { "added": [ "v1.1.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "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." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "This function now supports key objects." } ] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

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

\n

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

" }, { "textRaw": "`crypto.publicDecrypt(key, buffer)`", "type": "method", "name": "publicDecrypt", "meta": { "added": [ "v1.1.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "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." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "This function now supports key objects." } ] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

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

\n

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

\n

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

" }, { "textRaw": "`crypto.publicEncrypt(key, buffer)`", "type": "method", "name": "publicEncrypt", "meta": { "added": [ "v0.11.14" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "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." }, { "version": "v12.11.0", "pr-url": "https://github.com/nodejs/node/pull/29489", "description": "The `oaepLabel` option was added." }, { "version": "v12.9.0", "pr-url": "https://github.com/nodejs/node/pull/28335", "description": "The `oaepHash` option was added." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "This function now supports key objects." } ] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

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

\n

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

\n

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

" }, { "textRaw": "`crypto.randomBytes(size[, callback])`", "type": "method", "name": "randomBytes", "meta": { "added": [ "v0.5.8" ], "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/16454", "description": "Passing `null` as the `callback` argument now throws `ERR_INVALID_CALLBACK`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} if the `callback` function is not provided.", "name": "return", "type": "Buffer", "desc": "if the `callback` function is not provided." }, "params": [ { "textRaw": "`size` {number} The number of bytes to generate. The `size` must not be larger than `2**31 - 1`.", "name": "size", "type": "number", "desc": "The number of bytes to generate. The `size` must not be larger than `2**31 - 1`." }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`buf` {Buffer}", "name": "buf", "type": "Buffer" } ] } ] } ], "desc": "

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

\n

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

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

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

\n
// Synchronous\nconst {\n  randomBytes\n} = await import('crypto');\n\nconst buf = randomBytes(256);\nconsole.log(\n  `${buf.length} bytes of random data: ${buf.toString('hex')}`);\n
\n
// Synchronous\nconst {\n  randomBytes,\n} = require('crypto');\n\nconst buf = randomBytes(256);\nconsole.log(\n  `${buf.length} bytes of random data: ${buf.toString('hex')}`);\n
\n

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

\n

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

\n

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

" }, { "textRaw": "`crypto.randomFillSync(buffer[, offset][, size])`", "type": "method", "name": "randomFillSync", "meta": { "added": [ "v7.10.0", "v6.13.0" ], "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15231", "description": "The `buffer` argument may be any `TypedArray` or `DataView`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {ArrayBuffer|Buffer|TypedArray|DataView} The object passed as `buffer` argument.", "name": "return", "type": "ArrayBuffer|Buffer|TypedArray|DataView", "desc": "The object passed as `buffer` argument." }, "params": [ { "textRaw": "`buffer` {ArrayBuffer|Buffer|TypedArray|DataView} Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`.", "name": "buffer", "type": "ArrayBuffer|Buffer|TypedArray|DataView", "desc": "Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`." }, { "textRaw": "`offset` {number} **Default:** `0`", "name": "offset", "type": "number", "default": "`0`" }, { "textRaw": "`size` {number} **Default:** `buffer.length - offset`. The `size` must not be larger than `2**31 - 1`.", "name": "size", "type": "number", "default": "`buffer.length - offset`. The `size` must not be larger than `2**31 - 1`" } ] } ], "desc": "

Synchronous version of crypto.randomFill().

\n
import { Buffer } from 'buffer';\nconst { randomFillSync } = await import('crypto');\n\nconst buf = Buffer.alloc(10);\nconsole.log(randomFillSync(buf).toString('hex'));\n\nrandomFillSync(buf, 5);\nconsole.log(buf.toString('hex'));\n\n// The above is equivalent to the following:\nrandomFillSync(buf, 5, 5);\nconsole.log(buf.toString('hex'));\n
\n
const { randomFillSync } = require('crypto');\nconst { Buffer } = require('buffer');\n\nconst buf = Buffer.alloc(10);\nconsole.log(randomFillSync(buf).toString('hex'));\n\nrandomFillSync(buf, 5);\nconsole.log(buf.toString('hex'));\n\n// The above is equivalent to the following:\nrandomFillSync(buf, 5, 5);\nconsole.log(buf.toString('hex'));\n
\n

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

\n
import { Buffer } from 'buffer';\nconst { randomFillSync } = await import('crypto');\n\nconst a = new Uint32Array(10);\nconsole.log(Buffer.from(randomFillSync(a).buffer,\n                        a.byteOffset, a.byteLength).toString('hex'));\n\nconst b = new DataView(new ArrayBuffer(10));\nconsole.log(Buffer.from(randomFillSync(b).buffer,\n                        b.byteOffset, b.byteLength).toString('hex'));\n\nconst c = new ArrayBuffer(10);\nconsole.log(Buffer.from(randomFillSync(c)).toString('hex'));\n
\n
const { randomFillSync } = require('crypto');\nconst { Buffer } = require('buffer');\n\nconst a = new Uint32Array(10);\nconsole.log(Buffer.from(randomFillSync(a).buffer,\n                        a.byteOffset, a.byteLength).toString('hex'));\n\nconst b = new DataView(new ArrayBuffer(10));\nconsole.log(Buffer.from(randomFillSync(b).buffer,\n                        b.byteOffset, b.byteLength).toString('hex'));\n\nconst c = new ArrayBuffer(10);\nconsole.log(Buffer.from(randomFillSync(c)).toString('hex'));\n
" }, { "textRaw": "`crypto.randomFill(buffer[, offset][, size], callback)`", "type": "method", "name": "randomFill", "meta": { "added": [ "v7.10.0", "v6.13.0" ], "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15231", "description": "The `buffer` argument may be any `TypedArray` or `DataView`." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {ArrayBuffer|Buffer|TypedArray|DataView} Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`.", "name": "buffer", "type": "ArrayBuffer|Buffer|TypedArray|DataView", "desc": "Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`." }, { "textRaw": "`offset` {number} **Default:** `0`", "name": "offset", "type": "number", "default": "`0`" }, { "textRaw": "`size` {number} **Default:** `buffer.length - offset`. The `size` must not be larger than `2**31 - 1`.", "name": "size", "type": "number", "default": "`buffer.length - offset`. The `size` must not be larger than `2**31 - 1`" }, { "textRaw": "`callback` {Function} `function(err, buf) {}`.", "name": "callback", "type": "Function", "desc": "`function(err, buf) {}`." } ] } ], "desc": "

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

\n

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

\n
import { Buffer } from 'buffer';\nconst { randomFill } = await import('crypto');\n\nconst buf = Buffer.alloc(10);\nrandomFill(buf, (err, buf) => {\n  if (err) throw err;\n  console.log(buf.toString('hex'));\n});\n\nrandomFill(buf, 5, (err, buf) => {\n  if (err) throw err;\n  console.log(buf.toString('hex'));\n});\n\n// The above is equivalent to the following:\nrandomFill(buf, 5, 5, (err, buf) => {\n  if (err) throw err;\n  console.log(buf.toString('hex'));\n});\n
\n
const { randomFill } = require('crypto');\nconst { Buffer } = require('buffer');\n\nconst buf = Buffer.alloc(10);\nrandomFill(buf, (err, buf) => {\n  if (err) throw err;\n  console.log(buf.toString('hex'));\n});\n\nrandomFill(buf, 5, (err, buf) => {\n  if (err) throw err;\n  console.log(buf.toString('hex'));\n});\n\n// The above is equivalent to the following:\nrandomFill(buf, 5, 5, (err, buf) => {\n  if (err) throw err;\n  console.log(buf.toString('hex'));\n});\n
\n

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

\n

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

\n
import { Buffer } from 'buffer';\nconst { randomFill } = await import('crypto');\n\nconst a = new Uint32Array(10);\nrandomFill(a, (err, buf) => {\n  if (err) throw err;\n  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n    .toString('hex'));\n});\n\nconst b = new DataView(new ArrayBuffer(10));\nrandomFill(b, (err, buf) => {\n  if (err) throw err;\n  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n    .toString('hex'));\n});\n\nconst c = new ArrayBuffer(10);\nrandomFill(c, (err, buf) => {\n  if (err) throw err;\n  console.log(Buffer.from(buf).toString('hex'));\n});\n
\n
const { randomFill } = require('crypto');\nconst { Buffer } = require('buffer');\n\nconst a = new Uint32Array(10);\nrandomFill(a, (err, buf) => {\n  if (err) throw err;\n  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n    .toString('hex'));\n});\n\nconst b = new DataView(new ArrayBuffer(10));\nrandomFill(b, (err, buf) => {\n  if (err) throw err;\n  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n    .toString('hex'));\n});\n\nconst c = new ArrayBuffer(10);\nrandomFill(c, (err, buf) => {\n  if (err) throw err;\n  console.log(Buffer.from(buf).toString('hex'));\n});\n
\n

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

\n

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

" }, { "textRaw": "`crypto.randomInt([min, ]max[, callback])`", "type": "method", "name": "randomInt", "meta": { "added": [ "v14.10.0", "v12.19.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`min` {integer} Start of random range (inclusive). **Default:** `0`.", "name": "min", "type": "integer", "default": "`0`", "desc": "Start of random range (inclusive)." }, { "textRaw": "`max` {integer} End of random range (exclusive).", "name": "max", "type": "integer", "desc": "End of random range (exclusive)." }, { "textRaw": "`callback` {Function} `function(err, n) {}`.", "name": "callback", "type": "Function", "desc": "`function(err, n) {}`." } ] } ], "desc": "

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

\n

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

\n

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

\n
// Asynchronous\nconst {\n  randomInt\n} = await import('crypto');\n\nrandomInt(3, (err, n) => {\n  if (err) throw err;\n  console.log(`Random number chosen from (0, 1, 2): ${n}`);\n});\n
\n
// Asynchronous\nconst {\n  randomInt,\n} = require('crypto');\n\nrandomInt(3, (err, n) => {\n  if (err) throw err;\n  console.log(`Random number chosen from (0, 1, 2): ${n}`);\n});\n
\n
// Synchronous\nconst {\n  randomInt\n} = await import('crypto');\n\nconst n = randomInt(3);\nconsole.log(`Random number chosen from (0, 1, 2): ${n}`);\n
\n
// Synchronous\nconst {\n  randomInt,\n} = require('crypto');\n\nconst n = randomInt(3);\nconsole.log(`Random number chosen from (0, 1, 2): ${n}`);\n
\n
// With `min` argument\nconst {\n  randomInt\n} = await import('crypto');\n\nconst n = randomInt(1, 7);\nconsole.log(`The dice rolled: ${n}`);\n
\n
// With `min` argument\nconst {\n  randomInt,\n} = require('crypto');\n\nconst n = randomInt(1, 7);\nconsole.log(`The dice rolled: ${n}`);\n
" }, { "textRaw": "`crypto.randomUUID([options])`", "type": "method", "name": "randomUUID", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string}", "name": "return", "type": "string" }, "params": [ { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`disableEntropyCache` {boolean} By default, to improve performance, Node.js generates and caches enough random data to generate up to 128 random UUIDs. To generate a UUID without using the cache, set `disableEntropyCache` to `true`. **Default:** `false`.", "name": "disableEntropyCache", "type": "boolean", "default": "`false`", "desc": "By default, to improve performance, Node.js generates and caches enough random data to generate up to 128 random UUIDs. To generate a UUID without using the cache, set `disableEntropyCache` to `true`." } ] } ] } ], "desc": "

Generates a random RFC 4122 Version 4 UUID. The UUID is generated using a\ncryptographic pseudorandom number generator.

" }, { "textRaw": "`crypto.scrypt(password, salt, keylen[, options], callback)`", "type": "method", "name": "scrypt", "meta": { "added": [ "v10.5.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The password and salt arguments can also be ArrayBuffer instances." }, { "version": [ "v12.8.0", "v10.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/28799", "description": "The `maxmem` value can now be any safe integer." }, { "version": "v10.9.0", "pr-url": "https://github.com/nodejs/node/pull/21525", "description": "The `cost`, `blockSize` and `parallelization` option names have been added." } ] }, "signatures": [ { "params": [ { "textRaw": "`password` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "password", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`salt` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "salt", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`keylen` {number}", "name": "keylen", "type": "number" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`cost` {number} CPU/memory cost parameter. Must be a power of two greater than one. **Default:** `16384`.", "name": "cost", "type": "number", "default": "`16384`", "desc": "CPU/memory cost parameter. Must be a power of two greater than one." }, { "textRaw": "`blockSize` {number} Block size parameter. **Default:** `8`.", "name": "blockSize", "type": "number", "default": "`8`", "desc": "Block size parameter." }, { "textRaw": "`parallelization` {number} Parallelization parameter. **Default:** `1`.", "name": "parallelization", "type": "number", "default": "`1`", "desc": "Parallelization parameter." }, { "textRaw": "`N` {number} Alias for `cost`. Only one of both may be specified.", "name": "N", "type": "number", "desc": "Alias for `cost`. Only one of both may be specified." }, { "textRaw": "`r` {number} Alias for `blockSize`. Only one of both may be specified.", "name": "r", "type": "number", "desc": "Alias for `blockSize`. Only one of both may be specified." }, { "textRaw": "`p` {number} Alias for `parallelization`. Only one of both may be specified.", "name": "p", "type": "number", "desc": "Alias for `parallelization`. Only one of both may be specified." }, { "textRaw": "`maxmem` {number} Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.", "name": "maxmem", "type": "number", "default": "`32 * 1024 * 1024`", "desc": "Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`." } ] }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`derivedKey` {Buffer}", "name": "derivedKey", "type": "Buffer" } ] } ] } ], "desc": "

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

\n

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

\n

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

\n

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

\n

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

\n
const {\n  scrypt\n} = await import('crypto');\n\n// Using the factory defaults.\nscrypt('password', 'salt', 64, (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'\n});\n// Using a custom N parameter. Must be a power of two.\nscrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey.toString('hex'));  // '3745e48...aa39b34'\n});\n
\n
const {\n  scrypt,\n} = require('crypto');\n\n// Using the factory defaults.\nscrypt('password', 'salt', 64, (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'\n});\n// Using a custom N parameter. Must be a power of two.\nscrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {\n  if (err) throw err;\n  console.log(derivedKey.toString('hex'));  // '3745e48...aa39b34'\n});\n
" }, { "textRaw": "`crypto.scryptSync(password, salt, keylen[, options])`", "type": "method", "name": "scryptSync", "meta": { "added": [ "v10.5.0" ], "changes": [ { "version": [ "v12.8.0", "v10.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/28799", "description": "The `maxmem` value can now be any safe integer." }, { "version": "v10.9.0", "pr-url": "https://github.com/nodejs/node/pull/21525", "description": "The `cost`, `blockSize` and `parallelization` option names have been added." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "params": [ { "textRaw": "`password` {string|Buffer|TypedArray|DataView}", "name": "password", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`salt` {string|Buffer|TypedArray|DataView}", "name": "salt", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`keylen` {number}", "name": "keylen", "type": "number" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`cost` {number} CPU/memory cost parameter. Must be a power of two greater than one. **Default:** `16384`.", "name": "cost", "type": "number", "default": "`16384`", "desc": "CPU/memory cost parameter. Must be a power of two greater than one." }, { "textRaw": "`blockSize` {number} Block size parameter. **Default:** `8`.", "name": "blockSize", "type": "number", "default": "`8`", "desc": "Block size parameter." }, { "textRaw": "`parallelization` {number} Parallelization parameter. **Default:** `1`.", "name": "parallelization", "type": "number", "default": "`1`", "desc": "Parallelization parameter." }, { "textRaw": "`N` {number} Alias for `cost`. Only one of both may be specified.", "name": "N", "type": "number", "desc": "Alias for `cost`. Only one of both may be specified." }, { "textRaw": "`r` {number} Alias for `blockSize`. Only one of both may be specified.", "name": "r", "type": "number", "desc": "Alias for `blockSize`. Only one of both may be specified." }, { "textRaw": "`p` {number} Alias for `parallelization`. Only one of both may be specified.", "name": "p", "type": "number", "desc": "Alias for `parallelization`. Only one of both may be specified." }, { "textRaw": "`maxmem` {number} Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.", "name": "maxmem", "type": "number", "default": "`32 * 1024 * 1024`", "desc": "Memory upper bound. It is an error when (approximately) `128 * N * r > maxmem`." } ] } ] } ], "desc": "

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

\n

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

\n

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

\n

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

\n

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

\n
const {\n  scryptSync\n} = await import('crypto');\n// Using the factory defaults.\n\nconst key1 = scryptSync('password', 'salt', 64);\nconsole.log(key1.toString('hex'));  // '3745e48...08d59ae'\n// Using a custom N parameter. Must be a power of two.\nconst key2 = scryptSync('password', 'salt', 64, { N: 1024 });\nconsole.log(key2.toString('hex'));  // '3745e48...aa39b34'\n
\n
const {\n  scryptSync,\n} = require('crypto');\n// Using the factory defaults.\n\nconst key1 = scryptSync('password', 'salt', 64);\nconsole.log(key1.toString('hex'));  // '3745e48...08d59ae'\n// Using a custom N parameter. Must be a power of two.\nconst key2 = scryptSync('password', 'salt', 64, { N: 1024 });\nconsole.log(key2.toString('hex'));  // '3745e48...aa39b34'\n
" }, { "textRaw": "`crypto.secureHeapUsed()`", "type": "method", "name": "secureHeapUsed", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`total` {number} The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag.", "name": "total", "type": "number", "desc": "The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag." }, { "textRaw": "`min` {number} The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag.", "name": "min", "type": "number", "desc": "The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag." }, { "textRaw": "`used` {number} The total number of bytes currently allocated from the secure heap.", "name": "used", "type": "number", "desc": "The total number of bytes currently allocated from the secure heap." }, { "textRaw": "`utilization` {number} The calculated ratio of `used` to `total` allocated bytes.", "name": "utilization", "type": "number", "desc": "The calculated ratio of `used` to `total` allocated bytes." } ] }, "params": [] } ] }, { "textRaw": "`crypto.setEngine(engine[, flags])`", "type": "method", "name": "setEngine", "meta": { "added": [ "v0.11.11" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`engine` {string}", "name": "engine", "type": "string" }, { "textRaw": "`flags` {crypto.constants} **Default:** `crypto.constants.ENGINE_METHOD_ALL`", "name": "flags", "type": "crypto.constants", "default": "`crypto.constants.ENGINE_METHOD_ALL`" } ] } ], "desc": "

Load and set the engine for some or all OpenSSL functions (selected by flags).

\n

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

\n

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

\n\n

The flags below are deprecated in OpenSSL-1.1.0.

\n" }, { "textRaw": "`crypto.setFips(bool)`", "type": "method", "name": "setFips", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`bool` {boolean} `true` to enable FIPS mode.", "name": "bool", "type": "boolean", "desc": "`true` to enable FIPS mode." } ] } ], "desc": "

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

" }, { "textRaw": "`crypto.sign(algorithm, data, key[, callback])`", "type": "method", "name": "sign", "meta": { "added": [ "v12.0.0" ], "changes": [ { "version": "v15.12.0", "pr-url": "https://github.com/nodejs/node/pull/37500", "description": "Optional callback argument added." }, { "version": [ "v13.2.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/29292", "description": "This function now supports IEEE-P1363 DSA and ECDSA signatures." } ] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

Calculates and returns the signature for data using the given private key and\nalgorithm. If algorithm is null or undefined, then the algorithm is\ndependent upon the key type (especially Ed25519 and Ed448).

\n

If key is not a KeyObject, this function behaves as if key had been\npassed to crypto.createPrivateKey(). If it is an object, the following\nadditional properties can be passed:

\n\n

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

" }, { "textRaw": "`crypto.timingSafeEqual(a, b)`", "type": "method", "name": "timingSafeEqual", "meta": { "added": [ "v6.6.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The a and b arguments can also be ArrayBuffer." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`a` {ArrayBuffer|Buffer|TypedArray|DataView}", "name": "a", "type": "ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`b` {ArrayBuffer|Buffer|TypedArray|DataView}", "name": "b", "type": "ArrayBuffer|Buffer|TypedArray|DataView" } ] } ], "desc": "

This function is based on a constant-time algorithm.\nReturns true if a is equal to b, without leaking timing information that\nwould allow an attacker to guess one of the values. This is suitable for\ncomparing HMAC digests or secret values like authentication cookies or\ncapability urls.

\n

a and b must both be Buffers, TypedArrays, or DataViews, and they\nmust have the same byte length.

\n

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

\n

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

" }, { "textRaw": "`crypto.verify(algorithm, data, key, signature[, callback])`", "type": "method", "name": "verify", "meta": { "added": [ "v12.0.0" ], "changes": [ { "version": "v15.12.0", "pr-url": "https://github.com/nodejs/node/pull/37500", "description": "Optional callback argument added." }, { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The data, key, and signature arguments can also be ArrayBuffer." }, { "version": [ "v13.2.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/29292", "description": "This function now supports IEEE-P1363 DSA and ECDSA signatures." } ] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

Verifies the given signature for data using the given key and algorithm. If\nalgorithm is null or undefined, then the algorithm is dependent upon the\nkey type (especially Ed25519 and Ed448).

\n

If key is not a KeyObject, this function behaves as if key had been\npassed to crypto.createPublicKey(). If it is an object, the following\nadditional properties can be passed:

\n\n

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

\n

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

\n

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

" } ], "type": "module", "displayName": "`crypto` module methods and properties" }, { "textRaw": "Notes", "name": "notes", "modules": [ { "textRaw": "Using strings as inputs to cryptographic APIs", "name": "using_strings_as_inputs_to_cryptographic_apis", "desc": "

For historical reasons, many cryptographic APIs provided by Node.js accept\nstrings as inputs where the underlying cryptographic algorithm works on byte\nsequences. These instances include plaintexts, ciphertexts, symmetric keys,\ninitialization vectors, passphrases, salts, authentication tags,\nand additional authenticated data.

\n

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

\n", "type": "module", "displayName": "Using strings as inputs to cryptographic APIs" }, { "textRaw": "Legacy streams API (prior to Node.js 0.10)", "name": "legacy_streams_api_(prior_to_node.js_0.10)", "desc": "

The Crypto module was added to Node.js before there was the concept of a\nunified Stream API, and before there were Buffer objects for handling\nbinary data. As such, the many of the crypto defined classes have methods not\ntypically found on other Node.js classes that implement the streams\nAPI (e.g. update(), final(), or digest()). Also, many methods accepted\nand returned 'latin1' encoded strings by default rather than Buffers. This\ndefault was changed after Node.js v0.8 to use Buffer objects by default\ninstead.

", "type": "module", "displayName": "Legacy streams API (prior to Node.js 0.10)" }, { "textRaw": "Recent ECDH changes", "name": "recent_ecdh_changes", "desc": "

Usage of ECDH with non-dynamically generated key pairs has been simplified.\nNow, ecdh.setPrivateKey() can be called with a preselected private key\nand the associated public point (key) will be computed and stored in the object.\nThis allows code to only store and provide the private part of the EC key pair.\necdh.setPrivateKey() now also validates that the private key is valid for\nthe selected curve.

\n

The ecdh.setPublicKey() method is now deprecated as its inclusion in the\nAPI is not useful. Either a previously stored private key should be set, which\nautomatically generates the associated public key, or ecdh.generateKeys()\nshould be called. The main drawback of using ecdh.setPublicKey() is that\nit can be used to put the ECDH key pair into an inconsistent state.

", "type": "module", "displayName": "Recent ECDH changes" }, { "textRaw": "Support for weak or compromised algorithms", "name": "support_for_weak_or_compromised_algorithms", "desc": "

The crypto module still supports some algorithms which are already\ncompromised and are not currently recommended for use. The API also allows\nthe use of ciphers and hashes with a small key size that are too weak for safe\nuse.

\n

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

\n

Based on the recommendations of NIST SP 800-131A:

\n\n

See the reference for other recommendations and details.

", "type": "module", "displayName": "Support for weak or compromised algorithms" }, { "textRaw": "CCM mode", "name": "ccm_mode", "desc": "

CCM is one of the supported AEAD algorithms. Applications which use this\nmode must adhere to certain restrictions when using the cipher API:

\n\n
import { Buffer } from 'buffer';\nconst {\n  createCipheriv,\n  createDecipheriv,\n  randomBytes\n} = await import('crypto');\n\nconst key = 'keykeykeykeykeykeykeykey';\nconst nonce = randomBytes(12);\n\nconst aad = Buffer.from('0123456789', 'hex');\n\nconst cipher = createCipheriv('aes-192-ccm', key, nonce, {\n  authTagLength: 16\n});\nconst plaintext = 'Hello world';\ncipher.setAAD(aad, {\n  plaintextLength: Buffer.byteLength(plaintext)\n});\nconst ciphertext = cipher.update(plaintext, 'utf8');\ncipher.final();\nconst tag = cipher.getAuthTag();\n\n// Now transmit { ciphertext, nonce, tag }.\n\nconst decipher = createDecipheriv('aes-192-ccm', key, nonce, {\n  authTagLength: 16\n});\ndecipher.setAuthTag(tag);\ndecipher.setAAD(aad, {\n  plaintextLength: ciphertext.length\n});\nconst receivedPlaintext = decipher.update(ciphertext, null, 'utf8');\n\ntry {\n  decipher.final();\n} catch (err) {\n  console.error('Authentication failed!');\n  return;\n}\n\nconsole.log(receivedPlaintext);\n
\n
const {\n  createCipheriv,\n  createDecipheriv,\n  randomBytes,\n} = require('crypto');\nconst { Buffer } = require('buffer');\n\nconst key = 'keykeykeykeykeykeykeykey';\nconst nonce = randomBytes(12);\n\nconst aad = Buffer.from('0123456789', 'hex');\n\nconst cipher = createCipheriv('aes-192-ccm', key, nonce, {\n  authTagLength: 16\n});\nconst plaintext = 'Hello world';\ncipher.setAAD(aad, {\n  plaintextLength: Buffer.byteLength(plaintext)\n});\nconst ciphertext = cipher.update(plaintext, 'utf8');\ncipher.final();\nconst tag = cipher.getAuthTag();\n\n// Now transmit { ciphertext, nonce, tag }.\n\nconst decipher = createDecipheriv('aes-192-ccm', key, nonce, {\n  authTagLength: 16\n});\ndecipher.setAuthTag(tag);\ndecipher.setAAD(aad, {\n  plaintextLength: ciphertext.length\n});\nconst receivedPlaintext = decipher.update(ciphertext, null, 'utf8');\n\ntry {\n  decipher.final();\n} catch (err) {\n  console.error('Authentication failed!');\n  return;\n}\n\nconsole.log(receivedPlaintext);\n
", "type": "module", "displayName": "CCM mode" } ], "type": "module", "displayName": "Notes" }, { "textRaw": "Crypto constants", "name": "crypto_constants", "desc": "

The following constants exported by crypto.constants apply to various uses of\nthe crypto, tls, and https modules and are generally specific to OpenSSL.

", "modules": [ { "textRaw": "OpenSSL options", "name": "openssl_options", "desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
SSL_OP_ALLApplies multiple bug workarounds within OpenSSL. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html\n for detail.
SSL_OP_ALLOW_NO_DHE_KEXInstructs OpenSSL to allow a non-[EC]DHE-based key exchange mode\n for TLS v1.3
SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATIONAllows legacy insecure renegotiation between OpenSSL and unpatched\n clients or servers. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
SSL_OP_CIPHER_SERVER_PREFERENCEAttempts to use the server's preferences instead of the client's when\n selecting a cipher. Behavior depends on protocol version. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html.
SSL_OP_CISCO_ANYCONNECTInstructs OpenSSL to use Cisco's \"speshul\" version 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\n of the cryptopro draft.
SSL_OP_DONT_INSERT_EMPTY_FRAGMENTSInstructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability\n workaround added in OpenSSL 0.9.6d.
SSL_OP_EPHEMERAL_RSAInstructs OpenSSL to always use the tmp_rsa key when performing RSA\n operations.
SSL_OP_LEGACY_SERVER_CONNECTAllows initial connection to servers that do not support RI.
SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
SSL_OP_MICROSOFT_SESS_ID_BUG
SSL_OP_MSIE_SSLV2_RSA_PADDINGInstructs OpenSSL to disable the workaround for a man-in-the-middle\n protocol-version vulnerability in the SSL 2.0 server implementation.
SSL_OP_NETSCAPE_CA_DN_BUG
SSL_OP_NETSCAPE_CHALLENGE_BUG
SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
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\n 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_PKCS1_CHECK_1
SSL_OP_PKCS1_CHECK_2
SSL_OP_PRIORITIZE_CHACHAInstructs OpenSSL server to prioritize ChaCha20Poly1305\n when client does.\n This option has no effect if\n SSL_OP_CIPHER_SERVER_PREFERENCE\n is not enabled.
SSL_OP_SINGLE_DH_USEInstructs OpenSSL to always create a new key when using\n temporary/ephemeral DH parameters.
SSL_OP_SINGLE_ECDH_USEInstructs OpenSSL to always create a new key when using\n temporary/ephemeral ECDH parameters.
SSL_OP_SSLEAY_080_CLIENT_DH_BUG
SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
SSL_OP_TLS_BLOCK_PADDING_BUG
SSL_OP_TLS_D5_BUG
SSL_OP_TLS_ROLLBACK_BUGInstructs OpenSSL to disable version rollback attack detection.
", "type": "module", "displayName": "OpenSSL options" }, { "textRaw": "OpenSSL engine constants", "name": "openssl_engine_constants", "desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
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_METHDS
ENGINE_METHOD_PKEY_ASN1_METHSLimit engine usage to PKEY_ASN1_METHS
ENGINE_METHOD_ALL
ENGINE_METHOD_NONE
", "type": "module", "displayName": "OpenSSL engine constants" }, { "textRaw": "Other OpenSSL constants", "name": "other_openssl_constants", "desc": "

See the list of SSL OP Flags for details.

\n\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
DH_CHECK_P_NOT_SAFE_PRIME
DH_CHECK_P_NOT_PRIME
DH_UNABLE_TO_CHECK_GENERATOR
DH_NOT_SUITABLE_GENERATOR
ALPN_ENABLED
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 for RSA_PKCS1_PSS_PADDING to the\n digest size when signing or verifying.
RSA_PSS_SALTLEN_MAX_SIGNSets the salt length for RSA_PKCS1_PSS_PADDING to the\n maximum permissible value when signing data.
RSA_PSS_SALTLEN_AUTOCauses the salt length for RSA_PKCS1_PSS_PADDING to be\n determined automatically when verifying a signature.
POINT_CONVERSION_COMPRESSED
POINT_CONVERSION_UNCOMPRESSED
POINT_CONVERSION_HYBRID
", "type": "module", "displayName": "Other OpenSSL constants" }, { "textRaw": "Node.js crypto constants", "name": "node.js_crypto_constants", "desc": "\n \n \n \n \n \n \n \n \n \n \n \n \n
ConstantDescription
defaultCoreCipherListSpecifies the built-in default cipher list used by Node.js.
defaultCipherListSpecifies the active default cipher list used by the current Node.js\n process.
", "type": "module", "displayName": "Node.js crypto constants" } ], "type": "module", "displayName": "Crypto constants" } ], "classes": [ { "textRaw": "Class: `Certificate`", "type": "class", "name": "Certificate", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "desc": "

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

\n

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

\n

The crypto module provides the Certificate class for working with SPKAC\ndata. The most common usage is handling output generated by the HTML5\n<keygen> element. Node.js uses OpenSSL's SPKAC implementation internally.

", "classMethods": [ { "textRaw": "Static method: `Certificate.exportChallenge(spkac[, encoding])`", "type": "classMethod", "name": "exportChallenge", "meta": { "added": [ "v9.0.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The spkac argument can be an ArrayBuffer. Limited the size of the spkac argument to a maximum of 2**31 - 1 bytes." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} The challenge component of the `spkac` data structure, which includes a public key and a challenge.", "name": "return", "type": "Buffer", "desc": "The challenge component of the `spkac` data structure, which includes a public key and a challenge." }, "params": [ { "textRaw": "`spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "spkac", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `spkac` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `spkac` string." } ] } ], "desc": "
const { Certificate } = await import('crypto');\nconst spkac = getSpkacSomehow();\nconst challenge = Certificate.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
\n
const { Certificate } = require('crypto');\nconst spkac = getSpkacSomehow();\nconst challenge = Certificate.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
" }, { "textRaw": "Static method: `Certificate.exportPublicKey(spkac[, encoding])`", "type": "classMethod", "name": "exportPublicKey", "meta": { "added": [ "v9.0.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The spkac argument can be an ArrayBuffer. Limited the size of the spkac argument to a maximum of 2**31 - 1 bytes." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} The public key component of the `spkac` data structure, which includes a public key and a challenge.", "name": "return", "type": "Buffer", "desc": "The public key component of the `spkac` data structure, which includes a public key and a challenge." }, "params": [ { "textRaw": "`spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "spkac", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `spkac` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `spkac` string." } ] } ], "desc": "
const { Certificate } = await import('crypto');\nconst spkac = getSpkacSomehow();\nconst publicKey = Certificate.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
\n
const { Certificate } = require('crypto');\nconst spkac = getSpkacSomehow();\nconst publicKey = Certificate.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
" }, { "textRaw": "Static method: `Certificate.verifySpkac(spkac[, encoding])`", "type": "classMethod", "name": "verifySpkac", "meta": { "added": [ "v9.0.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The spkac argument can be an ArrayBuffer. Added encoding. Limited the size of the spkac argument to a maximum of 2**31 - 1 bytes." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `true` if the given `spkac` data structure is valid, `false` otherwise.", "name": "return", "type": "boolean", "desc": "`true` if the given `spkac` data structure is valid, `false` otherwise." }, "params": [ { "textRaw": "`spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "spkac", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `spkac` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `spkac` string." } ] } ], "desc": "
import { Buffer } from 'buffer';\nconst { Certificate } = await import('crypto');\n\nconst spkac = getSpkacSomehow();\nconsole.log(Certificate.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
\n
const { Certificate } = require('crypto');\nconst { Buffer } = require('buffer');\n\nconst spkac = getSpkacSomehow();\nconsole.log(Certificate.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
" } ], "modules": [ { "textRaw": "Legacy API", "name": "legacy_api", "stability": 0, "stabilityText": "Deprecated", "desc": "

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

", "ctors": [ { "textRaw": "`new crypto.Certificate()`", "type": "ctor", "name": "crypto.Certificate", "signatures": [ { "params": [] } ], "desc": "

Instances of the Certificate class can be created using the new keyword\nor by calling crypto.Certificate() as a function:

\n
const { Certificate } = await import('crypto');\n\nconst cert1 = new Certificate();\nconst cert2 = Certificate();\n
\n
const { Certificate } = require('crypto');\n\nconst cert1 = new Certificate();\nconst cert2 = Certificate();\n
" } ], "methods": [ { "textRaw": "`certificate.exportChallenge(spkac[, encoding])`", "type": "method", "name": "exportChallenge", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} The challenge component of the `spkac` data structure, which includes a public key and a challenge.", "name": "return", "type": "Buffer", "desc": "The challenge component of the `spkac` data structure, which includes a public key and a challenge." }, "params": [ { "textRaw": "`spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "spkac", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `spkac` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `spkac` string." } ] } ], "desc": "
const { Certificate } = await import('crypto');\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconst challenge = cert.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
\n
const { Certificate } = require('crypto');\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconst challenge = cert.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
" }, { "textRaw": "`certificate.exportPublicKey(spkac[, encoding])`", "type": "method", "name": "exportPublicKey", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} The public key component of the `spkac` data structure, which includes a public key and a challenge.", "name": "return", "type": "Buffer", "desc": "The public key component of the `spkac` data structure, which includes a public key and a challenge." }, "params": [ { "textRaw": "`spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "spkac", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `spkac` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `spkac` string." } ] } ], "desc": "
const { Certificate } = await import('crypto');\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconst publicKey = cert.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
\n
const { Certificate } = require('crypto');\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconst publicKey = cert.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
" }, { "textRaw": "`certificate.verifySpkac(spkac[, encoding])`", "type": "method", "name": "verifySpkac", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `true` if the given `spkac` data structure is valid, `false` otherwise.", "name": "return", "type": "boolean", "desc": "`true` if the given `spkac` data structure is valid, `false` otherwise." }, "params": [ { "textRaw": "`spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "spkac", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `spkac` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `spkac` string." } ] } ], "desc": "
import { Buffer } from 'buffer';\nconst { Certificate } = await import('crypto');\n\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
\n
const { Certificate } = require('crypto');\nconst { Buffer } = require('buffer');\n\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
" } ], "type": "module", "displayName": "Legacy API" } ] }, { "textRaw": "Class: `Cipher`", "type": "class", "name": "Cipher", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "desc": "\n

Instances of the Cipher class are used to encrypt data. The class can be\nused in one of two ways:

\n\n

The crypto.createCipher() or crypto.createCipheriv() methods are\nused to create Cipher instances. Cipher objects are not to be created\ndirectly using the new keyword.

\n

Example: Using Cipher objects as streams:

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

Example: Using Cipher and piped streams:

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

Example: Using the cipher.update() and cipher.final() methods:

\n
const {\n  scrypt,\n  randomFill,\n  createCipheriv\n} = await import('crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n\n// First, we'll generate the key. The key length is dependent on the algorithm.\n// In this case for aes192, it is 24 bytes (192 bits).\nscrypt(password, 'salt', 24, (err, key) => {\n  if (err) throw err;\n  // Then, we'll generate a random initialization vector\n  randomFill(new Uint8Array(16), (err, iv) => {\n    if (err) throw err;\n\n    const cipher = createCipheriv(algorithm, key, iv);\n\n    let encrypted = cipher.update('some clear text data', 'utf8', 'hex');\n    encrypted += cipher.final('hex');\n    console.log(encrypted);\n  });\n});\n
\n
const {\n  scrypt,\n  randomFill,\n  createCipheriv,\n} = require('crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n\n// First, we'll generate the key. The key length is dependent on the algorithm.\n// In this case for aes192, it is 24 bytes (192 bits).\nscrypt(password, 'salt', 24, (err, key) => {\n  if (err) throw err;\n  // Then, we'll generate a random initialization vector\n  randomFill(new Uint8Array(16), (err, iv) => {\n    if (err) throw err;\n\n    const cipher = createCipheriv(algorithm, key, iv);\n\n    let encrypted = cipher.update('some clear text data', 'utf8', 'hex');\n    encrypted += cipher.final('hex');\n    console.log(encrypted);\n  });\n});\n
", "methods": [ { "textRaw": "`cipher.final([outputEncoding])`", "type": "method", "name": "final", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string} Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned.", "name": "return", "type": "Buffer | string", "desc": "Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned." }, "params": [ { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Once the cipher.final() method has been called, the Cipher object can no\nlonger be used to encrypt data. Attempts to call cipher.final() more than\nonce will result in an error being thrown.

" }, { "textRaw": "`cipher.getAuthTag()`", "type": "method", "name": "getAuthTag", "meta": { "added": [ "v1.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are currently supported), the `cipher.getAuthTag()` method returns a [`Buffer`][] containing the _authentication tag_ that has been computed from the given data.", "name": "return", "type": "Buffer", "desc": "When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are currently supported), the `cipher.getAuthTag()` method returns a [`Buffer`][] containing the _authentication tag_ that has been computed from the given data." }, "params": [] } ], "desc": "

The cipher.getAuthTag() method should only be called after encryption has\nbeen completed using the cipher.final() method.

" }, { "textRaw": "`cipher.setAAD(buffer[, options])`", "type": "method", "name": "setAAD", "meta": { "added": [ "v1.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Cipher} for method chaining.", "name": "return", "type": "Cipher", "desc": "for method chaining." }, "params": [ { "textRaw": "`buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "buffer", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]", "options": [ { "textRaw": "`plaintextLength` {number}", "name": "plaintextLength", "type": "number" }, { "textRaw": "`encoding` {string} The string encoding to use when `buffer` is a string.", "name": "encoding", "type": "string", "desc": "The string encoding to use when `buffer` is a string." } ] } ] } ], "desc": "

When using an authenticated encryption mode (GCM, CCM and OCB are\ncurrently supported), the cipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.

\n

The plaintextLength option is optional for GCM and OCB. When using CCM,\nthe plaintextLength option must be specified and its value must match the\nlength of the plaintext in bytes. See CCM mode.

\n

The cipher.setAAD() method must be called before cipher.update().

" }, { "textRaw": "`cipher.setAutoPadding([autoPadding])`", "type": "method", "name": "setAutoPadding", "meta": { "added": [ "v0.7.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Cipher} for method chaining.", "name": "return", "type": "Cipher", "desc": "for method chaining." }, "params": [ { "textRaw": "`autoPadding` {boolean} **Default:** `true`", "name": "autoPadding", "type": "boolean", "default": "`true`" } ] } ], "desc": "

When using block encryption algorithms, the Cipher class will automatically\nadd padding to the input data to the appropriate block size. To disable the\ndefault padding call cipher.setAutoPadding(false).

\n

When autoPadding is false, the length of the entire input data must be a\nmultiple of the cipher's block size or cipher.final() will throw an error.\nDisabling automatic padding is useful for non-standard padding, for instance\nusing 0x0 instead of PKCS padding.

\n

The cipher.setAutoPadding() method must be called before\ncipher.final().

" }, { "textRaw": "`cipher.update(data[, inputEncoding][, outputEncoding])`", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`data` {string|Buffer|TypedArray|DataView}", "name": "data", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the data.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the data." }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Updates the cipher with data. If the inputEncoding argument is given,\nthe data\nargument is a string using the specified encoding. If the inputEncoding\nargument is not given, data must be a Buffer, TypedArray, or\nDataView. If data is a Buffer, TypedArray, or DataView, then\ninputEncoding is ignored.

\n

The outputEncoding specifies the output format of the enciphered\ndata. If the outputEncoding\nis specified, a string using the specified encoding is returned. If no\noutputEncoding is provided, a Buffer is returned.

\n

The cipher.update() method can be called multiple times with new data until\ncipher.final() is called. Calling cipher.update() after\ncipher.final() will result in an error being thrown.

" } ] }, { "textRaw": "Class: `Decipher`", "type": "class", "name": "Decipher", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "desc": "\n

Instances of the Decipher class are used to decrypt data. The class can be\nused in one of two ways:

\n\n

The crypto.createDecipher() or crypto.createDecipheriv() methods are\nused to create Decipher instances. Decipher objects are not to be created\ndirectly using the new keyword.

\n

Example: Using Decipher objects as streams:

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

Example: Using Decipher and piped streams:

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

Example: Using the decipher.update() and decipher.final() methods:

\n
import { Buffer } from 'buffer';\nconst {\n  scryptSync,\n  createDecipheriv\n} = await import('crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = createDecipheriv(algorithm, key, iv);\n\n// Encrypted using same algorithm, key and iv.\nconst encrypted =\n  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\nlet decrypted = decipher.update(encrypted, 'hex', 'utf8');\ndecrypted += decipher.final('utf8');\nconsole.log(decrypted);\n// Prints: some clear text data\n
\n
const {\n  scryptSync,\n  createDecipheriv,\n} = require('crypto');\nconst { Buffer } = require('buffer');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = createDecipheriv(algorithm, key, iv);\n\n// Encrypted using same algorithm, key and iv.\nconst encrypted =\n  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\nlet decrypted = decipher.update(encrypted, 'hex', 'utf8');\ndecrypted += decipher.final('utf8');\nconsole.log(decrypted);\n// Prints: some clear text data\n
", "methods": [ { "textRaw": "`decipher.final([outputEncoding])`", "type": "method", "name": "final", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string} Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned.", "name": "return", "type": "Buffer | string", "desc": "Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned." }, "params": [ { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Once the decipher.final() method has been called, the Decipher object can\nno longer be used to decrypt data. Attempts to call decipher.final() more\nthan once will result in an error being thrown.

" }, { "textRaw": "`decipher.setAAD(buffer[, options])`", "type": "method", "name": "setAAD", "meta": { "added": [ "v1.0.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The buffer argument can be a string or ArrayBuffer and is limited to no more than 2 ** 31 - 1 bytes." }, { "version": "v7.2.0", "pr-url": "https://github.com/nodejs/node/pull/9398", "description": "This method now returns a reference to `decipher`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Decipher} for method chaining.", "name": "return", "type": "Decipher", "desc": "for method chaining." }, "params": [ { "textRaw": "`buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "buffer", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]", "options": [ { "textRaw": "`plaintextLength` {number}", "name": "plaintextLength", "type": "number" }, { "textRaw": "`encoding` {string} String encoding to use when `buffer` is a string.", "name": "encoding", "type": "string", "desc": "String encoding to use when `buffer` is a string." } ] } ] } ], "desc": "

When using an authenticated encryption mode (GCM, CCM and OCB are\ncurrently supported), the decipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.

\n

The options argument is optional for GCM. When using CCM, the\nplaintextLength option must be specified and its value must match the length\nof the ciphertext in bytes. See CCM mode.

\n

The decipher.setAAD() method must be called before decipher.update().

\n

When passing a string as the buffer, please consider\ncaveats when using strings as inputs to cryptographic APIs.

" }, { "textRaw": "`decipher.setAuthTag(buffer[, encoding])`", "type": "method", "name": "setAuthTag", "meta": { "added": [ "v1.0.0" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The buffer argument can be a string or ArrayBuffer and is limited to no more than 2 ** 31 - 1 bytes." }, { "version": "v11.0.0", "pr-url": "https://github.com/nodejs/node/pull/17825", "description": "This method now throws if the GCM tag length is invalid." }, { "version": "v7.2.0", "pr-url": "https://github.com/nodejs/node/pull/9398", "description": "This method now returns a reference to `decipher`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Decipher} for method chaining.", "name": "return", "type": "Decipher", "desc": "for method chaining." }, "params": [ { "textRaw": "`buffer` {string|Buffer|ArrayBuffer|TypedArray|DataView}", "name": "buffer", "type": "string|Buffer|ArrayBuffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} String encoding to use when `buffer` is a string.", "name": "encoding", "type": "string", "desc": "String encoding to use when `buffer` is a string." } ] } ], "desc": "

When using an authenticated encryption mode (GCM, CCM and OCB are\ncurrently supported), the decipher.setAuthTag() method is used to pass in the\nreceived authentication tag. If no tag is provided, or if the cipher text\nhas been tampered with, decipher.final() will throw, indicating that the\ncipher text should be discarded due to failed authentication. If the tag length\nis invalid according to NIST SP 800-38D or does not match the value of the\nauthTagLength option, decipher.setAuthTag() will throw an error.

\n

The decipher.setAuthTag() method must be called before decipher.update()\nfor CCM mode or before decipher.final() for GCM and OCB modes.\ndecipher.setAuthTag() can only be called once.

\n

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

" }, { "textRaw": "`decipher.setAutoPadding([autoPadding])`", "type": "method", "name": "setAutoPadding", "meta": { "added": [ "v0.7.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Decipher} for method chaining.", "name": "return", "type": "Decipher", "desc": "for method chaining." }, "params": [ { "textRaw": "`autoPadding` {boolean} **Default:** `true`", "name": "autoPadding", "type": "boolean", "default": "`true`" } ] } ], "desc": "

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

\n

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

\n

The decipher.setAutoPadding() method must be called before\ndecipher.final().

" }, { "textRaw": "`decipher.update(data[, inputEncoding][, outputEncoding])`", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`data` {string|Buffer|TypedArray|DataView}", "name": "data", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string." }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Updates the decipher with data. If the inputEncoding argument is given,\nthe data\nargument is a string using the specified encoding. If the inputEncoding\nargument is not given, data must be a Buffer. If data is a\nBuffer then inputEncoding is ignored.

\n

The outputEncoding specifies the output format of the enciphered\ndata. If the outputEncoding\nis specified, a string using the specified encoding is returned. If no\noutputEncoding is provided, a Buffer is returned.

\n

The decipher.update() method can be called multiple times with new data until\ndecipher.final() is called. Calling decipher.update() after\ndecipher.final() will result in an error being thrown.

" } ] }, { "textRaw": "Class: `DiffieHellman`", "type": "class", "name": "DiffieHellman", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "desc": "

The DiffieHellman class is a utility for creating Diffie-Hellman key\nexchanges.

\n

Instances of the DiffieHellman class can be created using the\ncrypto.createDiffieHellman() function.

\n
import assert from 'assert';\n\nconst {\n  createDiffieHellman\n} = await import('crypto');\n\n// Generate Alice's keys...\nconst alice = createDiffieHellman(2048);\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\n// OK\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n
\n
const assert = require('assert');\n\nconst {\n  createDiffieHellman,\n} = require('crypto');\n\n// Generate Alice's keys...\nconst alice = createDiffieHellman(2048);\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\n// OK\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n
", "methods": [ { "textRaw": "`diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])`", "type": "method", "name": "computeSecret", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`otherPublicKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "otherPublicKey", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of an `otherPublicKey` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of an `otherPublicKey` string." }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Computes the shared secret using otherPublicKey as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using the specified inputEncoding, and secret is\nencoded using specified outputEncoding.\nIf the inputEncoding is not\nprovided, otherPublicKey is expected to be a Buffer,\nTypedArray, or DataView.

\n

If outputEncoding is given a string is returned; otherwise, a\nBuffer is returned.

" }, { "textRaw": "`diffieHellman.generateKeys([encoding])`", "type": "method", "name": "generateKeys", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Generates private and public Diffie-Hellman key values, and returns\nthe public key in the specified encoding. This key should be\ntransferred to the other party.\nIf encoding is provided a string is returned; otherwise a\nBuffer is returned.

" }, { "textRaw": "`diffieHellman.getGenerator([encoding])`", "type": "method", "name": "getGenerator", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Returns the Diffie-Hellman generator in the specified encoding.\nIf encoding is provided a string is\nreturned; otherwise a Buffer is returned.

" }, { "textRaw": "`diffieHellman.getPrime([encoding])`", "type": "method", "name": "getPrime", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Returns the Diffie-Hellman prime in the specified encoding.\nIf encoding is provided a string is\nreturned; otherwise a Buffer is returned.

" }, { "textRaw": "`diffieHellman.getPrivateKey([encoding])`", "type": "method", "name": "getPrivateKey", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Returns the Diffie-Hellman private key in the specified encoding.\nIf encoding is provided a\nstring is returned; otherwise a Buffer is returned.

" }, { "textRaw": "`diffieHellman.getPublicKey([encoding])`", "type": "method", "name": "getPublicKey", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Returns the Diffie-Hellman public key in the specified encoding.\nIf encoding is provided a\nstring is returned; otherwise a Buffer is returned.

" }, { "textRaw": "`diffieHellman.setPrivateKey(privateKey[, encoding])`", "type": "method", "name": "setPrivateKey", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`privateKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "privateKey", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `privateKey` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `privateKey` string." } ] } ], "desc": "

Sets the Diffie-Hellman private key. If the encoding argument is provided,\nprivateKey is expected\nto be a string. If no encoding is provided, privateKey is expected\nto be a Buffer, TypedArray, or DataView.

" }, { "textRaw": "`diffieHellman.setPublicKey(publicKey[, encoding])`", "type": "method", "name": "setPublicKey", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`publicKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "publicKey", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `publicKey` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `publicKey` string." } ] } ], "desc": "

Sets the Diffie-Hellman public key. If the encoding argument is provided,\npublicKey is expected\nto be a string. If no encoding is provided, publicKey is expected\nto be a Buffer, TypedArray, or DataView.

" } ], "properties": [ { "textRaw": "`diffieHellman.verifyError`", "name": "verifyError", "meta": { "added": [ "v0.11.12" ], "changes": [] }, "desc": "

A bit field containing any warnings and/or errors resulting from a check\nperformed during initialization of the DiffieHellman object.

\n

The following values are valid for this property (as defined in constants\nmodule):

\n" } ] }, { "textRaw": "Class: `DiffieHellmanGroup`", "type": "class", "name": "DiffieHellmanGroup", "meta": { "added": [ "v0.7.5" ], "changes": [] }, "desc": "

The DiffieHellmanGroup class takes a well-known modp group as its argument.\nIt works the same as DiffieHellman, except that it does not allow changing\nits keys after creation. In other words, it does not implement setPublicKey()\nor setPrivateKey() methods.

\n
const { createDiffieHellmanGroup } = await import('crypto');\nconst dh = createDiffieHellmanGroup('modp1');\n
\n
const { createDiffieHellmanGroup } = require('crypto');\nconst dh = createDiffieHellmanGroup('modp1');\n
\n

The name (e.g. 'modp1') is taken from RFC 2412 (modp1 and 2) and\nRFC 3526:

\n
$ perl -ne 'print \"$1\\n\" if /\"(modp\\d+)\"/' src/node_crypto_groups.h\nmodp1  #  768 bits\nmodp2  # 1024 bits\nmodp5  # 1536 bits\nmodp14 # 2048 bits\nmodp15 # etc.\nmodp16\nmodp17\nmodp18\n
" }, { "textRaw": "Class: `ECDH`", "type": "class", "name": "ECDH", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "desc": "

The ECDH class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)\nkey exchanges.

\n

Instances of the ECDH class can be created using the\ncrypto.createECDH() function.

\n
import assert from 'assert';\n\nconst {\n  createECDH\n} = await import('crypto');\n\n// Generate Alice's keys...\nconst alice = createECDH('secp521r1');\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = createECDH('secp521r1');\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n// OK\n
\n
const assert = require('assert');\n\nconst {\n  createECDH,\n} = require('crypto');\n\n// Generate Alice's keys...\nconst alice = createECDH('secp521r1');\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = createECDH('secp521r1');\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n// OK\n
", "classMethods": [ { "textRaw": "Static method: `ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])`", "type": "classMethod", "name": "convertKey", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`key` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "key", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`curve` {string}", "name": "curve", "type": "string" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `key` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `key` string." }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value." }, { "textRaw": "`format` {string} **Default:** `'uncompressed'`", "name": "format", "type": "string", "default": "`'uncompressed'`" } ] } ], "desc": "

Converts the EC Diffie-Hellman public key specified by key and curve to the\nformat specified by format. The format argument specifies point encoding\nand can be 'compressed', 'uncompressed' or 'hybrid'. The supplied key is\ninterpreted using the specified inputEncoding, and the returned key is encoded\nusing the specified outputEncoding.

\n

Use crypto.getCurves() to obtain a list of available curve names.\nOn recent OpenSSL releases, openssl ecparam -list_curves will also display\nthe name and description of each available elliptic curve.

\n

If format is not specified the point will be returned in 'uncompressed'\nformat.

\n

If the inputEncoding is not provided, key is expected to be a Buffer,\nTypedArray, or DataView.

\n

Example (uncompressing a key):

\n
const {\n  createECDH,\n  ECDH\n} = await import('crypto');\n\nconst ecdh = createECDH('secp256k1');\necdh.generateKeys();\n\nconst compressedKey = ecdh.getPublicKey('hex', 'compressed');\n\nconst uncompressedKey = ECDH.convertKey(compressedKey,\n                                        'secp256k1',\n                                        'hex',\n                                        'hex',\n                                        'uncompressed');\n\n// The converted key and the uncompressed public key should be the same\nconsole.log(uncompressedKey === ecdh.getPublicKey('hex'));\n
\n
const {\n  createECDH,\n  ECDH,\n} = require('crypto');\n\nconst ecdh = createECDH('secp256k1');\necdh.generateKeys();\n\nconst compressedKey = ecdh.getPublicKey('hex', 'compressed');\n\nconst uncompressedKey = ECDH.convertKey(compressedKey,\n                                        'secp256k1',\n                                        'hex',\n                                        'hex',\n                                        'uncompressed');\n\n// The converted key and the uncompressed public key should be the same\nconsole.log(uncompressedKey === ecdh.getPublicKey('hex'));\n
" } ], "methods": [ { "textRaw": "`ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])`", "type": "method", "name": "computeSecret", "meta": { "added": [ "v0.11.14" ], "changes": [ { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/16849", "description": "Changed error format to better support invalid public key error." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`otherPublicKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "otherPublicKey", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `otherPublicKey` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `otherPublicKey` string." }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Computes the shared secret using otherPublicKey as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using specified inputEncoding, and the returned secret\nis encoded using the specified outputEncoding.\nIf the inputEncoding is not\nprovided, otherPublicKey is expected to be a Buffer, TypedArray, or\nDataView.

\n

If outputEncoding is given a string will be returned; otherwise a\nBuffer is returned.

\n

ecdh.computeSecret will throw an\nERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY error when otherPublicKey\nlies outside of the elliptic curve. Since otherPublicKey is\nusually supplied from a remote user over an insecure network,\nbe sure to handle this exception accordingly.

" }, { "textRaw": "`ecdh.generateKeys([encoding[, format]])`", "type": "method", "name": "generateKeys", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." }, { "textRaw": "`format` {string} **Default:** `'uncompressed'`", "name": "format", "type": "string", "default": "`'uncompressed'`" } ] } ], "desc": "

Generates private and public EC Diffie-Hellman key values, and returns\nthe public key in the specified format and encoding. This key should be\ntransferred to the other party.

\n

The format argument specifies point encoding and can be 'compressed' or\n'uncompressed'. If format is not specified, the point will be returned in\n'uncompressed' format.

\n

If encoding is provided a string is returned; otherwise a Buffer\nis returned.

" }, { "textRaw": "`ecdh.getPrivateKey([encoding])`", "type": "method", "name": "getPrivateKey", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string} The EC Diffie-Hellman in the specified `encoding`.", "name": "return", "type": "Buffer | string", "desc": "The EC Diffie-Hellman in the specified `encoding`." }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

If encoding is specified, a string is returned; otherwise a Buffer is\nreturned.

" }, { "textRaw": "`ecdh.getPublicKey([encoding][, format])`", "type": "method", "name": "getPublicKey", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string} The EC Diffie-Hellman public key in the specified `encoding` and `format`.", "name": "return", "type": "Buffer | string", "desc": "The EC Diffie-Hellman public key in the specified `encoding` and `format`." }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." }, { "textRaw": "`format` {string} **Default:** `'uncompressed'`", "name": "format", "type": "string", "default": "`'uncompressed'`" } ] } ], "desc": "

The format argument specifies point encoding and can be 'compressed' or\n'uncompressed'. If format is not specified the point will be returned in\n'uncompressed' format.

\n

If encoding is specified, a string is returned; otherwise a Buffer is\nreturned.

" }, { "textRaw": "`ecdh.setPrivateKey(privateKey[, encoding])`", "type": "method", "name": "setPrivateKey", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`privateKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "privateKey", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `privateKey` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `privateKey` string." } ] } ], "desc": "

Sets the EC Diffie-Hellman private key.\nIf encoding is provided, privateKey is expected\nto be a string; otherwise privateKey is expected to be a Buffer,\nTypedArray, or DataView.

\n

If privateKey is not valid for the curve specified when the ECDH object was\ncreated, an error is thrown. Upon setting the private key, the associated\npublic point (key) is also generated and set in the ECDH object.

" }, { "textRaw": "`ecdh.setPublicKey(publicKey[, encoding])`", "type": "method", "name": "setPublicKey", "meta": { "added": [ "v0.11.14" ], "deprecated": [ "v5.2.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`publicKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}", "name": "publicKey", "type": "string|ArrayBuffer|Buffer|TypedArray|DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `publicKey` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `publicKey` string." } ] } ], "desc": "

Sets the EC Diffie-Hellman public key.\nIf encoding is provided publicKey is expected to\nbe a string; otherwise a Buffer, TypedArray, or DataView is expected.

\n

There is not normally a reason to call this method because ECDH\nonly requires a private key and the other party's public key to compute the\nshared secret. Typically either ecdh.generateKeys() or\necdh.setPrivateKey() will be called. The ecdh.setPrivateKey() method\nattempts to generate the public point/key associated with the private key being\nset.

\n

Example (obtaining a shared secret):

\n
const {\n  createECDH,\n  createHash\n} = await import('crypto');\n\nconst alice = createECDH('secp256k1');\nconst bob = createECDH('secp256k1');\n\n// This is a shortcut way of specifying one of Alice's previous private\n// keys. It would be unwise to use such a predictable private key in a real\n// application.\nalice.setPrivateKey(\n  createHash('sha256').update('alice', 'utf8').digest()\n);\n\n// Bob uses a newly generated cryptographically strong\n// pseudorandom key pair\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n// aliceSecret and bobSecret should be the same shared secret value\nconsole.log(aliceSecret === bobSecret);\n
\n
const {\n  createECDH,\n  createHash,\n} = require('crypto');\n\nconst alice = createECDH('secp256k1');\nconst bob = createECDH('secp256k1');\n\n// This is a shortcut way of specifying one of Alice's previous private\n// keys. It would be unwise to use such a predictable private key in a real\n// application.\nalice.setPrivateKey(\n  createHash('sha256').update('alice', 'utf8').digest()\n);\n\n// Bob uses a newly generated cryptographically strong\n// pseudorandom key pair\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n// aliceSecret and bobSecret should be the same shared secret value\nconsole.log(aliceSecret === bobSecret);\n
" } ] }, { "textRaw": "Class: `Hash`", "type": "class", "name": "Hash", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "desc": "\n

The Hash class is a utility for creating hash digests of data. It can be\nused in one of two ways:

\n\n

The crypto.createHash() method is used to create Hash instances. Hash\nobjects are not to be created directly using the new keyword.

\n

Example: Using Hash objects as streams:

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

Example: Using Hash and piped streams:

\n
import { createReadStream } from 'fs';\nimport { stdout } from 'process';\nconst { createHash } = await import('crypto');\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream('test.js');\ninput.pipe(hash).setEncoding('hex').pipe(stdout);\n
\n
const { createReadStream } = require('fs');\nconst { createHash } = require('crypto');\nconst { stdout } = require('process');\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream('test.js');\ninput.pipe(hash).setEncoding('hex').pipe(stdout);\n
\n

Example: Using the hash.update() and hash.digest() methods:

\n
const {\n  createHash\n} = await import('crypto');\n\nconst hash = createHash('sha256');\n\nhash.update('some data to hash');\nconsole.log(hash.digest('hex'));\n// Prints:\n//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n
\n
const {\n  createHash,\n} = require('crypto');\n\nconst hash = createHash('sha256');\n\nhash.update('some data to hash');\nconsole.log(hash.digest('hex'));\n// Prints:\n//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n
", "methods": [ { "textRaw": "`hash.copy([options])`", "type": "method", "name": "copy", "meta": { "added": [ "v13.1.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Hash}", "name": "return", "type": "Hash" }, "params": [ { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]" } ] } ], "desc": "

Creates a new Hash object that contains a deep copy of the internal state\nof the current Hash object.

\n

The optional options argument controls stream behavior. For XOF hash\nfunctions such as 'shake256', the outputLength option can be used to\nspecify the desired output length in bytes.

\n

An error is thrown when an attempt is made to copy the Hash object after\nits hash.digest() method has been called.

\n
// Calculate a rolling hash.\nconst {\n  createHash\n} = await import('crypto');\n\nconst hash = createHash('sha256');\n\nhash.update('one');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('two');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('three');\nconsole.log(hash.copy().digest('hex'));\n\n// Etc.\n
\n
// Calculate a rolling hash.\nconst {\n  createHash,\n} = require('crypto');\n\nconst hash = createHash('sha256');\n\nhash.update('one');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('two');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('three');\nconsole.log(hash.copy().digest('hex'));\n\n// Etc.\n
" }, { "textRaw": "`hash.digest([encoding])`", "type": "method", "name": "digest", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Calculates the digest of all of the data passed to be hashed (using the\nhash.update() method).\nIf encoding is provided a string will be returned; otherwise\na Buffer is returned.

\n

The Hash object can not be used again after hash.digest() method has been\ncalled. Multiple calls will cause an error to be thrown.

" }, { "textRaw": "`hash.update(data[, inputEncoding])`", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "params": [ { "textRaw": "`data` {string|Buffer|TypedArray|DataView}", "name": "data", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string." } ] } ], "desc": "

Updates the hash content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.

\n

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

" } ] }, { "textRaw": "Class: `Hmac`", "type": "class", "name": "Hmac", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "desc": "\n

The Hmac class is a utility for creating cryptographic HMAC digests. It can\nbe used in one of two ways:

\n\n

The crypto.createHmac() method is used to create Hmac instances. Hmac\nobjects are not to be created directly using the new keyword.

\n

Example: Using Hmac objects as streams:

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

Example: Using Hmac and piped streams:

\n
import { createReadStream } from 'fs';\nimport { stdout } from 'process';\nconst {\n  createHmac\n} = await import('crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream('test.js');\ninput.pipe(hmac).pipe(stdout);\n
\n
const {\n  createReadStream,\n} = require('fs');\nconst {\n  createHmac,\n} = require('crypto');\nconst { stdout } = require('process');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream('test.js');\ninput.pipe(hmac).pipe(stdout);\n
\n

Example: Using the hmac.update() and hmac.digest() methods:

\n
const {\n  createHmac\n} = await import('crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nhmac.update('some data to hash');\nconsole.log(hmac.digest('hex'));\n// Prints:\n//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n
\n
const {\n  createHmac,\n} = require('crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nhmac.update('some data to hash');\nconsole.log(hmac.digest('hex'));\n// Prints:\n//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n
", "methods": [ { "textRaw": "`hmac.digest([encoding])`", "type": "method", "name": "digest", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value." } ] } ], "desc": "

Calculates the HMAC digest of all of the data passed using hmac.update().\nIf encoding is\nprovided a string is returned; otherwise a Buffer is returned;

\n

The Hmac object can not be used again after hmac.digest() has been\ncalled. Multiple calls to hmac.digest() will result in an error being thrown.

" }, { "textRaw": "`hmac.update(data[, inputEncoding])`", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "params": [ { "textRaw": "`data` {string|Buffer|TypedArray|DataView}", "name": "data", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string." } ] } ], "desc": "

Updates the Hmac content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.

\n

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

" } ] }, { "textRaw": "Class: `KeyObject`", "type": "class", "name": "KeyObject", "meta": { "added": [ "v11.6.0" ], "changes": [ { "version": [ "v14.5.0", "v12.19.0" ], "pr-url": "https://github.com/nodejs/node/pull/33360", "description": "Instances of this class can now be passed to worker threads using `postMessage`." }, { "version": "v11.13.0", "pr-url": "https://github.com/nodejs/node/pull/26438", "description": "This class is now exported." } ] }, "desc": "

Node.js uses a KeyObject class to represent a symmetric or asymmetric key,\nand each kind of key exposes different functions. The\ncrypto.createSecretKey(), crypto.createPublicKey() and\ncrypto.createPrivateKey() methods are used to create KeyObject\ninstances. KeyObject objects are not to be created directly using the new\nkeyword.

\n

Most applications should consider using the new KeyObject API instead of\npassing keys as strings or Buffers due to improved security features.

\n

KeyObject instances can be passed to other threads via postMessage().\nThe receiver obtains a cloned KeyObject, and the KeyObject does not need to\nbe listed in the transferList argument.

", "classMethods": [ { "textRaw": "Static method: `KeyObject.from(key)`", "type": "classMethod", "name": "from", "meta": { "added": [ "v15.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {KeyObject}", "name": "return", "type": "KeyObject" }, "params": [ { "textRaw": "`key` {CryptoKey}", "name": "key", "type": "CryptoKey" } ] } ], "desc": "

Example: Converting a CryptoKey instance to a KeyObject:

\n
const { webcrypto, KeyObject } = await import('crypto');\nconst { subtle } = webcrypto;\n\nconst key = await subtle.generateKey({\n  name: 'HMAC',\n  hash: 'SHA-256',\n  length: 256\n}, true, ['sign', 'verify']);\n\nconst keyObject = KeyObject.from(key);\nconsole.log(keyObject.symmetricKeySize);\n// Prints: 32 (symmetric key size in bytes)\n
\n
const {\n  webcrypto: {\n    subtle,\n  },\n  KeyObject,\n} = require('crypto');\n\n(async function() {\n  const key = await subtle.generateKey({\n    name: 'HMAC',\n    hash: 'SHA-256',\n    length: 256\n  }, true, ['sign', 'verify']);\n\n  const keyObject = KeyObject.from(key);\n  console.log(keyObject.symmetricKeySize);\n  // Prints: 32 (symmetric key size in bytes)\n})();\n
" } ], "properties": [ { "textRaw": "`asymmetricKeyDetails` {Object}", "type": "Object", "name": "asymmetricKeyDetails", "meta": { "added": [ "v15.7.0" ], "changes": [] }, "options": [ { "textRaw": "`modulusLength`: {number} Key size in bits (RSA, DSA).", "name": "modulusLength", "type": "number", "desc": "Key size in bits (RSA, DSA)." }, { "textRaw": "`publicExponent`: {bigint} Public exponent (RSA).", "name": "publicExponent", "type": "bigint", "desc": "Public exponent (RSA)." }, { "textRaw": "`divisorLength`: {number} Size of `q` in bits (DSA).", "name": "divisorLength", "type": "number", "desc": "Size of `q` in bits (DSA)." }, { "textRaw": "`namedCurve`: {string} Name of the curve (EC).", "name": "namedCurve", "type": "string", "desc": "Name of the curve (EC)." } ], "desc": "

This property exists only on asymmetric keys. Depending on the type of the key,\nthis object contains information about the key. None of the information obtained\nthrough this property can be used to uniquely identify a key or to compromise\nthe security of the key.

\n

RSA-PSS parameters, DH, or any future key type details might be exposed via this\nAPI using additional attributes.

" }, { "textRaw": "`asymmetricKeyType` {string}", "type": "string", "name": "asymmetricKeyType", "meta": { "added": [ "v11.6.0" ], "changes": [ { "version": [ "v13.9.0", "v12.17.0" ], "pr-url": "https://github.com/nodejs/node/pull/31178", "description": "Added support for `'dh'`." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26960", "description": "Added support for `'rsa-pss'`." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26786", "description": "This property now returns `undefined` for KeyObject instances of unrecognized type instead of aborting." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26774", "description": "Added support for `'x25519'` and `'x448'`." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26319", "description": "Added support for `'ed25519'` and `'ed448'`." } ] }, "desc": "

For asymmetric keys, this property represents the type of the key. Supported key\ntypes are:

\n\n

This property is undefined for unrecognized KeyObject types and symmetric\nkeys.

" }, { "textRaw": "`symmetricKeySize` {number}", "type": "number", "name": "symmetricKeySize", "meta": { "added": [ "v11.6.0" ], "changes": [] }, "desc": "

For secret keys, this property represents the size of the key in bytes. This\nproperty is undefined for asymmetric keys.

" }, { "textRaw": "`type` {string}", "type": "string", "name": "type", "meta": { "added": [ "v11.6.0" ], "changes": [] }, "desc": "

Depending on the type of this KeyObject, this property is either\n'secret' for secret (symmetric) keys, 'public' for public (asymmetric) keys\nor 'private' for private (asymmetric) keys.

" } ], "methods": [ { "textRaw": "`keyObject.export([options])`", "type": "method", "name": "export", "meta": { "added": [ "v11.6.0" ], "changes": [ { "version": "v15.9.0", "pr-url": "https://github.com/nodejs/node/pull/37081", "description": "Added support for `'jwk'` format." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {string | Buffer | Object}", "name": "return", "type": "string | Buffer | Object" }, "params": [ { "textRaw": "`options`: {Object}", "name": "options", "type": "Object" } ] } ], "desc": "

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

\n\n

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

\n\n

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

\n\n

The result type depends on the selected encoding format, when PEM the\nresult is a string, when DER it will be a buffer containing the data\nencoded as DER, when JWK it will be an object.

\n

When JWK encoding format was selected, all other encoding options are\nignored.

\n

PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of\nthe cipher and format options. The PKCS#8 type can be used with any\nformat to encrypt any key algorithm (RSA, EC, or DH) by specifying a\ncipher. PKCS#1 and SEC1 can only be encrypted by specifying a cipher\nwhen the PEM format is used. For maximum compatibility, use PKCS#8 for\nencrypted private keys. Since PKCS#8 defines its own\nencryption mechanism, PEM-level encryption is not supported when encrypting\na PKCS#8 key. See RFC 5208 for PKCS#8 encryption and RFC 1421 for\nPKCS#1 and SEC1 encryption.

" } ] }, { "textRaw": "Class: `Sign`", "type": "class", "name": "Sign", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "desc": "\n

The Sign class is a utility for generating signatures. It can be used in one\nof two ways:

\n\n

The crypto.createSign() method is used to create Sign instances. The\nargument is the string name of the hash function to use. Sign objects are not\nto be created directly using the new keyword.

\n

Example: Using Sign and Verify objects as streams:

\n
const {\n  generateKeyPairSync,\n  createSign,\n  createVerify\n} = await import('crypto');\n\nconst { privateKey, publicKey } = generateKeyPairSync('ec', {\n  namedCurve: 'sect239k1'\n});\n\nconst sign = createSign('SHA256');\nsign.write('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey, 'hex');\n\nconst verify = createVerify('SHA256');\nverify.write('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature, 'hex'));\n// Prints: true\n
\n
const {\n  generateKeyPairSync,\n  createSign,\n  createVerify,\n} = require('crypto');\n\nconst { privateKey, publicKey } = generateKeyPairSync('ec', {\n  namedCurve: 'sect239k1'\n});\n\nconst sign = createSign('SHA256');\nsign.write('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey, 'hex');\n\nconst verify = createVerify('SHA256');\nverify.write('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature, 'hex'));\n// Prints: true\n
\n

Example: Using the sign.update() and verify.update() methods:

\n
const {\n  generateKeyPairSync,\n  createSign,\n  createVerify\n} = await import('crypto');\n\nconst { privateKey, publicKey } = generateKeyPairSync('rsa', {\n  modulusLength: 2048,\n});\n\nconst sign = createSign('SHA256');\nsign.update('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey);\n\nconst verify = createVerify('SHA256');\nverify.update('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature));\n// Prints: true\n
\n
const {\n  generateKeyPairSync,\n  createSign,\n  createVerify,\n} = require('crypto');\n\nconst { privateKey, publicKey } = generateKeyPairSync('rsa', {\n  modulusLength: 2048,\n});\n\nconst sign = createSign('SHA256');\nsign.update('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey);\n\nconst verify = createVerify('SHA256');\nverify.update('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature));\n// Prints: true\n
", "methods": [ { "textRaw": "`sign.sign(privateKey[, outputEncoding])`", "type": "method", "name": "sign", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The privateKey can also be an ArrayBuffer and CryptoKey." }, { "version": [ "v13.2.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/29292", "description": "This function now supports IEEE-P1363 DSA and ECDSA signatures." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26960", "description": "This function now supports RSA-PSS keys." }, { "version": "v11.6.0", "pr-url": "https://github.com/nodejs/node/pull/24234", "description": "This function now supports key objects." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11705", "description": "Support for RSASSA-PSS and additional options was added." } ] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

Calculates the signature on all the data passed through using either\nsign.update() or sign.write().

\n

If privateKey is not a KeyObject, this function behaves as if\nprivateKey had been passed to crypto.createPrivateKey(). If it is an\nobject, the following additional properties can be passed:

\n\n

If outputEncoding is provided a string is returned; otherwise a Buffer\nis returned.

\n

The Sign object can not be again used after sign.sign() method has been\ncalled. Multiple calls to sign.sign() will result in an error being thrown.

" }, { "textRaw": "`sign.update(data[, inputEncoding])`", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "params": [ { "textRaw": "`data` {string|Buffer|TypedArray|DataView}", "name": "data", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string." } ] } ], "desc": "

Updates the Sign content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.

\n

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

" } ] }, { "textRaw": "Class: `Verify`", "type": "class", "name": "Verify", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "desc": "\n

The Verify class is a utility for verifying signatures. It can be used in one\nof two ways:

\n\n

The crypto.createVerify() method is used to create Verify instances.\nVerify objects are not to be created directly using the new keyword.

\n

See Sign for examples.

", "methods": [ { "textRaw": "`verify.update(data[, inputEncoding])`", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "params": [ { "textRaw": "`data` {string|Buffer|TypedArray|DataView}", "name": "data", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string." } ] } ], "desc": "

Updates the Verify content with the given data, the encoding of which\nis given in inputEncoding.\nIf inputEncoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.

\n

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

" }, { "textRaw": "`verify.verify(object, signature[, signatureEncoding])`", "type": "method", "name": "verify", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v15.0.0", "pr-url": "https://github.com/nodejs/node/pull/35093", "description": "The object can also be an ArrayBuffer and CryptoKey." }, { "version": [ "v13.2.0", "v12.16.0" ], "pr-url": "https://github.com/nodejs/node/pull/29292", "description": "This function now supports IEEE-P1363 DSA and ECDSA signatures." }, { "version": "v12.0.0", "pr-url": "https://github.com/nodejs/node/pull/26960", "description": "This function now supports RSA-PSS keys." }, { "version": "v11.7.0", "pr-url": "https://github.com/nodejs/node/pull/25217", "description": "The key can now be a private key." }, { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11705", "description": "Support for RSASSA-PSS and additional options was added." } ] }, "signatures": [ { "params": [] } ], "desc": "\n\n\n

Verifies the provided data using the given object and signature.

\n

If object is not a KeyObject, this function behaves as if\nobject had been passed to crypto.createPublicKey(). If it is an\nobject, the following additional properties can be passed:

\n\n

The signature argument is the previously calculated signature for the data, in\nthe signatureEncoding.\nIf a signatureEncoding is specified, the signature is expected to be a\nstring; otherwise signature is expected to be a Buffer,\nTypedArray, or DataView.

\n

The verify object can not be used again after verify.verify() has been\ncalled. Multiple calls to verify.verify() will result in an error being\nthrown.

\n

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

" } ] }, { "textRaw": "Class: `X509Certificate`", "type": "class", "name": "X509Certificate", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

Encapsulates an X509 certificate and provides read-only access to\nits information.

\n
const { X509Certificate } = await import('crypto');\n\nconst x509 = new X509Certificate('{... pem encoded cert ...}');\n\nconsole.log(x509.subject);\n
\n
const { X509Certificate } = require('crypto');\n\nconst x509 = new X509Certificate('{... pem encoded cert ...}');\n\nconsole.log(x509.subject);\n
", "properties": [ { "textRaw": "`ca` Type: {boolean} Will be `true` if this is a Certificate Authority (ca) certificate.", "type": "boolean", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "Will be `true` if this is a Certificate Authority (ca) certificate." }, { "textRaw": "`fingerprint` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The SHA-1 fingerprint of this certificate.

" }, { "textRaw": "`fingerprint256` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The SHA-256 fingerprint of this certificate.

" }, { "textRaw": "`infoAccess` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The information access content of this certificate.

" }, { "textRaw": "`issuer` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The issuer identification included in this certificate.

" }, { "textRaw": "`issuerCertificate` Type: {X509Certificate}", "type": "X509Certificate", "name": "Type", "meta": { "added": [ "v15.9.0" ], "changes": [] }, "desc": "

The issuer certificate or undefined if the issuer certificate is not\navailable.

" }, { "textRaw": "`keyUsage` Type: {string[]}", "type": "string[]", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

An array detailing the key usages for this certificate.

" }, { "textRaw": "`publicKey` Type: {KeyObject}", "type": "KeyObject", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The public key <KeyObject> for this certificate.

" }, { "textRaw": "`raw` Type: {Buffer}", "type": "Buffer", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

A Buffer containing the DER encoding of this certificate.

" }, { "textRaw": "`serialNumber` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The serial number of this certificate.

" }, { "textRaw": "`subject` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The complete subject of this certificate.

" }, { "textRaw": "`subjectAltName` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The subject alternative name specified for this certificate.

" }, { "textRaw": "`validFrom` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The date/time from which this certificate is considered valid.

" }, { "textRaw": "`validTo` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "desc": "

The date/time until which this certificate is considered valid.

" } ], "methods": [ { "textRaw": "`x509.checkEmail(email[, options])`", "type": "method", "name": "checkEmail", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string|undefined} Returns `email` if the certificate matches, `undefined` if it does not.", "name": "return", "type": "string|undefined", "desc": "Returns `email` if the certificate matches, `undefined` if it does not." }, "params": [ { "textRaw": "`email` {string}", "name": "email", "type": "string" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`subject` {string} `'always'` or `'never'`. **Default:** `'always'`.", "name": "subject", "type": "string", "default": "`'always'`", "desc": "`'always'` or `'never'`." }, { "textRaw": "`wildcards` {boolean} **Default:** `true`.", "name": "wildcards", "type": "boolean", "default": "`true`" }, { "textRaw": "`partialWildcards` {boolean} **Default:** `true`.", "name": "partialWildcards", "type": "boolean", "default": "`true`" }, { "textRaw": "`multiLabelWildcards` {boolean} **Default:** `false`.", "name": "multiLabelWildcards", "type": "boolean", "default": "`false`" }, { "textRaw": "`singleLabelSubdomains` {boolean} **Default:** `false`.", "name": "singleLabelSubdomains", "type": "boolean", "default": "`false`" } ] } ] } ], "desc": "

Checks whether the certificate matches the given email address.

" }, { "textRaw": "`x509.checkHost(name[, options])`", "type": "method", "name": "checkHost", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string|undefined} Returns `name` if the certificate matches, `undefined` if it does not.", "name": "return", "type": "string|undefined", "desc": "Returns `name` if the certificate matches, `undefined` if it does not." }, "params": [ { "textRaw": "`name` {string}", "name": "name", "type": "string" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`subject` {string} `'always'` or `'never'`. **Default:** `'always'`.", "name": "subject", "type": "string", "default": "`'always'`", "desc": "`'always'` or `'never'`." }, { "textRaw": "`wildcards` {boolean} **Default:** `true`.", "name": "wildcards", "type": "boolean", "default": "`true`" }, { "textRaw": "`partialWildcards` {boolean} **Default:** `true`.", "name": "partialWildcards", "type": "boolean", "default": "`true`" }, { "textRaw": "`multiLabelWildcards` {boolean} **Default:** `false`.", "name": "multiLabelWildcards", "type": "boolean", "default": "`false`" }, { "textRaw": "`singleLabelSubdomains` {boolean} **Default:** `false`.", "name": "singleLabelSubdomains", "type": "boolean", "default": "`false`" } ] } ] } ], "desc": "

Checks whether the certificate matches the given host name.

" }, { "textRaw": "`x509.checkIP(ip[, options])`", "type": "method", "name": "checkIP", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string|undefined} Returns `ip` if the certificate matches, `undefined` if it does not.", "name": "return", "type": "string|undefined", "desc": "Returns `ip` if the certificate matches, `undefined` if it does not." }, "params": [ { "textRaw": "`ip` {string}", "name": "ip", "type": "string" }, { "textRaw": "`options` {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`subject` {string} `'always'` or `'never'`. **Default:** `'always'`.", "name": "subject", "type": "string", "default": "`'always'`", "desc": "`'always'` or `'never'`." }, { "textRaw": "`wildcards` {boolean} **Default:** `true`.", "name": "wildcards", "type": "boolean", "default": "`true`" }, { "textRaw": "`partialWildcards` {boolean} **Default:** `true`.", "name": "partialWildcards", "type": "boolean", "default": "`true`" }, { "textRaw": "`multiLabelWildcards` {boolean} **Default:** `false`.", "name": "multiLabelWildcards", "type": "boolean", "default": "`false`" }, { "textRaw": "`singleLabelSubdomains` {boolean} **Default:** `false`.", "name": "singleLabelSubdomains", "type": "boolean", "default": "`false`" } ] } ] } ], "desc": "

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

" }, { "textRaw": "`x509.checkIssued(otherCert)`", "type": "method", "name": "checkIssued", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`otherCert` {X509Certificate}", "name": "otherCert", "type": "X509Certificate" } ] } ], "desc": "

Checks whether this certificate was issued by the given otherCert.

" }, { "textRaw": "`x509.checkPrivateKey(privateKey)`", "type": "method", "name": "checkPrivateKey", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`privateKey` {KeyObject} A private key.", "name": "privateKey", "type": "KeyObject", "desc": "A private key." } ] } ], "desc": "

Checks whether the public key for this certificate is consistent with\nthe given private key.

" }, { "textRaw": "`x509.toJSON()`", "type": "method", "name": "toJSON", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "Type: {string}", "name": "Type", "type": "string" } ] } ], "desc": "

There is no standard JSON encoding for X509 certificates. The\ntoJSON() method returns a string containing the PEM encoded\ncertificate.

" }, { "textRaw": "`x509.toLegacyObject()`", "type": "method", "name": "toLegacyObject", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "Type: {Object}", "name": "Type", "type": "Object" } ] } ], "desc": "

Returns information about this certificate using the legacy\ncertificate object encoding.

" }, { "textRaw": "`x509.toString()`", "type": "method", "name": "toString", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "Type: {string}", "name": "Type", "type": "string" } ] } ], "desc": "

Returns the PEM-encoded certificate.

" }, { "textRaw": "`x509.verify(publicKey)`", "type": "method", "name": "verify", "meta": { "added": [ "v15.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`publicKey` {KeyObject} A public key.", "name": "publicKey", "type": "KeyObject", "desc": "A public key." } ] } ], "desc": "

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

" } ], "signatures": [ { "params": [ { "textRaw": "`buffer` {string|TypedArray|Buffer|DataView} A PEM or DER encoded X509 Certificate.", "name": "buffer", "type": "string|TypedArray|Buffer|DataView", "desc": "A PEM or DER encoded X509 Certificate." } ] } ] } ], "type": "module", "displayName": "Crypto" } ] }