{ "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
\nThe node:crypto module provides cryptographic functionality that includes a\nset of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify\nfunctions.
const { createHmac } = await import('node: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\nconst { createHmac } = require('node: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",
"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\nnode:crypto module. In such cases, attempting to import from crypto or\ncalling require('node:crypto') will result in an error being thrown.
When using CommonJS, the error thrown can be caught using try/catch:
\n\nlet crypto;\ntry {\n crypto = require('node:crypto');\n} catch (err) {\n console.error('crypto support is disabled!');\n}\n\nWhen 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).
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:
let crypto;\ntry {\n crypto = await import('node:crypto');\n} catch (err) {\n console.error('crypto support is disabled!');\n}\n",
"type": "module",
"displayName": "Determining if crypto support is unavailable"
},
{
"textRaw": "`node:crypto` module methods and properties",
"name": "`node:crypto`_module_methods_and_properties",
"properties": [
{
"textRaw": "`constants` {Object}",
"type": "Object",
"name": "constants",
"meta": {
"added": [
"v6.3.0"
],
"changes": []
},
"desc": "An object containing commonly used constants for crypto and security related\noperations. The specific constants currently defined are described in\nCrypto 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.
The crypto.DEFAULT_ENCODING mechanism is provided for backward compatibility\nwith legacy programs that expect 'latin1' to be the default encoding.
New applications should expect the default to be 'buffer'.
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.
\nThis property is deprecated. Please use crypto.setFips() and\ncrypto.getFips() instead.
A convenient alias for crypto.webcrypto.subtle.
Type: <Crypto> An implementation of the Web Crypto API standard.
\nSee the Web Crypto API documentation for details.
" } ], "methods": [ { "textRaw": "`crypto.checkPrime(candidate[, options], callback)`", "type": "method", "name": "checkPrime", "meta": { "added": [ "v15.8.0" ], "changes": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." } ] }, "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.
Checks the primality of the candidate.
Creates and returns a Cipher object that uses the given algorithm and\npassword.
The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode (e.g. 'aes-128-ccm') is used. 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.\nFor chacha20-poly1305, the authTagLength option defaults to 16 bytes.
The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms will\ndisplay the available cipher algorithms.
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.
This function is semantically insecure for all\nsupported ciphers and fatally flawed for ciphers in counter mode (such as CTR,\nGCM, or CCM).
\nThe 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.
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.
Creates and returns a Cipher object, with the given algorithm, key and\ninitialization vector (iv).
The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode (e.g. 'aes-128-ccm') is used. 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.\nFor chacha20-poly1305, the authTagLength option defaults to 16 bytes.
The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms will\ndisplay the available cipher algorithms.
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.
When passing strings for key or iv, please consider\ncaveats when using strings as inputs to cryptographic APIs.
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": "v17.9.0", "pr-url": "https://github.com/nodejs/node/pull/42427", "description": "The `authTagLength` option is now optional when using the `chacha20-poly1305` cipher and defaults to 16 bytes." }, { "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).
The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode (e.g. 'aes-128-ccm') is used. In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode.\nFor chacha20-poly1305, the authTagLength option defaults to 16 bytes.
This function is semantically insecure for all\nsupported ciphers and fatally flawed for ciphers in counter mode (such as CTR,\nGCM, or CCM).
\nThe 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.
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.
Creates and returns a Decipher object that uses the given algorithm, key\nand initialization vector (iv).
The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode (e.g. 'aes-128-ccm') is used. 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.\nFor chacha20-poly1305, the authTagLength option defaults to 16 bytes.
The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms will\ndisplay the available cipher algorithms.
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.
When passing strings for key or iv, please consider\ncaveats when using strings as inputs to cryptographic APIs.
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.
The generator argument can be a number, string, or Buffer. If\ngenerator is not specified, the value 2 is used.
If primeEncoding is specified, prime is expected to be a string; otherwise\na Buffer, TypedArray, or DataView is expected.
If generatorEncoding is specified, generator is expected to be a string;\notherwise a number, Buffer, TypedArray, or DataView is expected.
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.
An alias for crypto.getDiffieHellman()
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.
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.
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 will\ndisplay the available digest algorithms.
Example: generating the sha256 sum of a file
\nimport {\n createReadStream,\n} from 'node:fs';\nimport { argv } from 'node:process';\nconst {\n createHash,\n} = await import('node: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\nconst {\n createReadStream,\n} = require('node:fs');\nconst {\n createHash,\n} = require('node:crypto');\nconst { argv } = require('node: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.
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 will\ndisplay the available digest algorithms.
The key is the HMAC key used to generate the cryptographic HMAC hash. If it is\na KeyObject, its type must be secret. If it is a string, please consider\ncaveats when using strings as inputs to cryptographic APIs. If it was\nobtained from a cryptographically secure source of entropy, such as\ncrypto.randomBytes() or crypto.generateKey(), its length should not\nexceed the block size of algorithm (e.g., 512 bits for SHA-256).
Example: generating the sha256 HMAC of a file
\nimport {\n createReadStream,\n} from 'node:fs';\nimport { argv } from 'node:process';\nconst {\n createHmac,\n} = await import('node: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\nconst {\n createReadStream,\n} = require('node:fs');\nconst {\n createHmac,\n} = require('node:crypto');\nconst { argv } = require('node: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": "\nkey <Object> | <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView>\nkey: <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <Object> The key\nmaterial, either in PEM, DER, or JWK format.format: <string> Must be 'pem', 'der', or ''jwk'.\nDefault: 'pem'.type: <string> Must be 'pkcs1', 'pkcs8' or 'sec1'. This option is\nrequired only if the format is 'der' and ignored otherwise.passphrase: <string> | <Buffer> The passphrase to use for decryption.encoding: <string> The string encoding to use when key is a string.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.
If the private key is encrypted, a passphrase must be specified. The length\nof the passphrase is limited to 1024 bytes.
key <Object> | <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView>\nkey: <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <Object> The key\nmaterial, either in PEM, DER, or JWK format.format: <string> Must be 'pem', 'der', or 'jwk'.\nDefault: 'pem'.type: <string> Must be 'pkcs1' or 'spki'. This option is\nrequired only if the format is 'der' and ignored otherwise.encoding <string> The string encoding to use when key is a string.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.
If the format is 'pem', the 'key' may also be an X.509 certificate.
Because public keys can be derived from private keys, a private key may be\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.
Creates and returns a new key object containing a secret key for symmetric\nencryption or Hmac.
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.
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.
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.
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.
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).
Asynchronously generates a new random secret key of the given length. The\ntype will determine which validations will be performed on the length.
const {\n generateKey,\n} = await import('node:crypto');\n\ngenerateKey('hmac', { length: 512 }, (err, key) => {\n if (err) throw err;\n console.log(key.export().toString('hex')); // 46e..........620\n});\n\nconst {\n generateKey,\n} = require('node:crypto');\n\ngenerateKey('hmac', { length: 512 }, (err, key) => {\n if (err) throw err;\n console.log(key.export().toString('hex')); // 46e..........620\n});\n\nThe size of a generated HMAC key should not exceed the block size of the\nunderlying hash function. See crypto.createHmac() for more information.
Generates a new asymmetric key pair of the given type. RSA, RSA-PSS, DSA, EC,\nEd25519, Ed448, X25519, X448, and DH are currently supported.
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.
It is recommended to encode public keys as 'spki' and private keys as\n'pkcs8' with encryption for long-term storage:
const {\n generateKeyPair,\n} = await import('node: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\nconst {\n generateKeyPair,\n} = require('node: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\nOn completion, callback will be called with err set to undefined and\npublicKey / privateKey representing the generated key pair.
If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with publicKey and privateKey properties.
Generates a new asymmetric key pair of the given type. RSA, RSA-PSS, DSA, EC,\nEd25519, Ed448, X25519, X448, and DH are currently supported.
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.
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.
const {\n generateKeyPairSync,\n} = await import('node: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\nconst {\n generateKeyPairSync,\n} = require('node: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\nThe 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.
Synchronously generates a new random secret key of the given length. The\ntype will determine which validations will be performed on the length.
const {\n generateKeySync,\n} = await import('node:crypto');\n\nconst key = generateKeySync('hmac', { length: 512 });\nconsole.log(key.export().toString('hex')); // e89..........41e\n\nconst {\n generateKeySync,\n} = require('node:crypto');\n\nconst key = generateKeySync('hmac', { length: 512 });\nconsole.log(key.export().toString('hex')); // e89..........41e\n\nThe size of a generated HMAC key should not exceed the block size of the\nunderlying hash function. See crypto.createHmac() for more information.
Generates a pseudorandom prime of size bits.
If options.safe is true, the prime will be a safe prime -- that is,\n(prime - 1) / 2 will also be a prime.
The options.add and options.rem parameters can be used to enforce additional\nrequirements, e.g., for Diffie-Hellman:
options.add and options.rem are both set, the prime will satisfy the\ncondition that prime % add = rem.options.add is set and options.safe is not true, the prime will\nsatisfy the condition that prime % add = 1.options.add is set and options.safe is set to true, the prime\nwill instead satisfy the condition that prime % add = 3. This is necessary\nbecause prime % add = 1 for options.add > 2 would contradict the condition\nenforced by options.safe.options.rem is ignored if options.add is not given.Both options.add and options.rem must be encoded as big-endian sequences\nif given as an ArrayBuffer, SharedArrayBuffer, TypedArray, Buffer, or\nDataView.
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.
Generates a pseudorandom prime of size bits.
If options.safe is true, the prime will be a safe prime -- that is,\n(prime - 1) / 2 will also be a prime.
The options.add and options.rem parameters can be used to enforce additional\nrequirements, e.g., for Diffie-Hellman:
options.add and options.rem are both set, the prime will satisfy the\ncondition that prime % add = rem.options.add is set and options.safe is not true, the prime will\nsatisfy the condition that prime % add = 1.options.add is set and options.safe is set to true, the prime\nwill instead satisfy the condition that prime % add = 3. This is necessary\nbecause prime % add = 1 for options.add > 2 would contradict the condition\nenforced by options.safe.options.rem is ignored if options.add is not given.Both options.add and options.rem must be encoded as big-endian sequences\nif given as an ArrayBuffer, SharedArrayBuffer, TypedArray, Buffer, or\nDataView.
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.
Returns information about a given cipher.
\nSome 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.
const {\n getCiphers,\n} = await import('node:crypto');\n\nconsole.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]\n\nconst {\n getCiphers,\n} = require('node: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('node:crypto');\n\nconsole.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n\nconst {\n getCurves,\n} = require('node: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 listed in the documentation for DiffieHellmanGroup.
The returned 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.
Example (obtaining a shared secret):
\nconst {\n getDiffieHellman,\n} = await import('node: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\nconst {\n getDiffieHellman,\n} = require('node: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('node:crypto');\n\nconsole.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n\nconst {\n getHashes,\n} = require('node:crypto');\n\nconsole.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n"
},
{
"textRaw": "`crypto.getRandomValues(typedArray)`",
"type": "method",
"name": "getRandomValues",
"meta": {
"added": [
"v17.4.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Buffer|TypedArray|DataView|ArrayBuffer} Returns `typedArray`.",
"name": "return",
"type": "Buffer|TypedArray|DataView|ArrayBuffer",
"desc": "Returns `typedArray`."
},
"params": [
{
"textRaw": "`typedArray` {Buffer|TypedArray|DataView|ArrayBuffer}",
"name": "typedArray",
"type": "Buffer|TypedArray|DataView|ArrayBuffer"
}
]
}
],
"desc": "A convenient alias for crypto.webcrypto.getRandomValues(). This\nimplementation is not compliant with the Web Crypto spec, to write\nweb-compatible code use crypto.webcrypto.getRandomValues() instead.
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.
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.
import { Buffer } from 'node:buffer';\nconst {\n hkdf,\n} = await import('node: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\nconst {\n hkdf,\n} = require('node:crypto');\nconst { Buffer } = require('node: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": [
{
"version": "v18.8.0",
"pr-url": "https://github.com/nodejs/node/pull/44201",
"description": "The input keying material can now be zero-length."
}
]
},
"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. Must be provided but can be zero-length.",
"name": "ikm",
"type": "string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject",
"desc": "The input keying material. Must be provided but can be zero-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.
The successfully generated derivedKey will be returned as an <ArrayBuffer>.
An error will be thrown if any of the input arguments specify invalid values or\ntypes, or if the derived key cannot be generated.
\nimport { Buffer } from 'node:buffer';\nconst {\n hkdfSync,\n} = await import('node:crypto');\n\nconst derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);\nconsole.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'\n\nconst {\n hkdfSync,\n} = require('node:crypto');\nconst { Buffer } = require('node: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": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"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.
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.
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.
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.
When passing strings for password or salt, please consider\ncaveats when using strings as inputs to cryptographic APIs.
const {\n pbkdf2,\n} = await import('node: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\nconst {\n pbkdf2,\n} = require('node: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\nAn array of supported digest functions can be retrieved using\ncrypto.getHashes().
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.
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.
If an error occurs an Error will be thrown, otherwise the derived key will be\nreturned as a Buffer.
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.
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.
When passing strings for password or salt, please consider\ncaveats when using strings as inputs to cryptographic APIs.
const {\n pbkdf2Sync,\n} = await import('node:crypto');\n\nconst key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');\nconsole.log(key.toString('hex')); // '3745e48...08d59ae'\n\nconst {\n pbkdf2Sync,\n} = require('node:crypto');\n\nconst key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');\nconsole.log(key.toString('hex')); // '3745e48...08d59ae'\n\nAn array of supported digest functions can be retrieved using\ncrypto.getHashes().
privateKey <Object> | <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey>\noaepHash <string> The hash function to use for OAEP padding and MGF1.\nDefault: 'sha1'oaepLabel <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> The label to\nuse for OAEP padding. If not specified, no label is used.padding <crypto.constants> An optional padding value defined in\ncrypto.constants, which may be: crypto.constants.RSA_NO_PADDING,\ncrypto.constants.RSA_PKCS1_PADDING, or\ncrypto.constants.RSA_PKCS1_OAEP_PADDING.buffer <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView>Buffer with the decrypted content.Decrypts buffer with privateKey. buffer was previously encrypted using\nthe corresponding public key, for example using crypto.publicEncrypt().
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.
Using crypto.constants.RSA_PKCS1_PADDING in crypto.privateDecrypt()\nrequires OpenSSL to support implicit rejection (rsa_pkcs1_implicit_rejection).\nIf the version of OpenSSL used by Node.js does not support this feature,\nattempting to use RSA_PKCS1_PADDING will fail.
privateKey <Object> | <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey>\nkey <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey>\nA PEM encoded private key.passphrase <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> An optional\npassphrase for the private key.padding <crypto.constants> An optional padding value defined in\ncrypto.constants, which may be: crypto.constants.RSA_NO_PADDING or\ncrypto.constants.RSA_PKCS1_PADDING.encoding <string> The string encoding to use when buffer, key,\nor passphrase are strings.buffer <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView>Buffer with the encrypted content.Encrypts buffer with privateKey. The returned data can be decrypted using\nthe corresponding public key, for example using crypto.publicDecrypt().
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.
key <Object> | <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey>\npassphrase <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> An optional\npassphrase for the private key.padding <crypto.constants> An optional padding value defined in\ncrypto.constants, which may be: crypto.constants.RSA_NO_PADDING or\ncrypto.constants.RSA_PKCS1_PADDING.encoding <string> The string encoding to use when buffer, key,\nor passphrase are strings.buffer <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView>Buffer with the decrypted content.Decrypts buffer with key.buffer was previously encrypted using\nthe corresponding private key, for example using crypto.privateEncrypt().
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.
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": "\nkey <Object> | <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey>\nkey <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey>\nA PEM encoded public or private key, <KeyObject>, or <CryptoKey>.oaepHash <string> The hash function to use for OAEP padding and MGF1.\nDefault: 'sha1'oaepLabel <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> The label to\nuse for OAEP padding. If not specified, no label is used.passphrase <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> An optional\npassphrase for the private key.padding <crypto.constants> An optional padding value defined in\ncrypto.constants, which may be: crypto.constants.RSA_NO_PADDING,\ncrypto.constants.RSA_PKCS1_PADDING, or\ncrypto.constants.RSA_PKCS1_OAEP_PADDING.encoding <string> The string encoding to use when buffer, key,\noaepLabel, or passphrase are strings.buffer <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView>Buffer with the encrypted content.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().
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.
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": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." }, { "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.
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.
// Asynchronous\nconst {\n randomBytes,\n} = await import('node: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('node: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\nIf 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.
// Synchronous\nconst {\n randomBytes,\n} = await import('node: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('node:crypto');\n\nconst buf = randomBytes(256);\nconsole.log(\n `${buf.length} bytes of random data: ${buf.toString('hex')}`);\n\nThe 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.
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.
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.
Synchronous version of crypto.randomFill().
import { Buffer } from 'node:buffer';\nconst { randomFillSync } = await import('node: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\nconst { randomFillSync } = require('node:crypto');\nconst { Buffer } = require('node: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\nAny ArrayBuffer, TypedArray or DataView instance may be passed as\nbuffer.
import { Buffer } from 'node:buffer';\nconst { randomFillSync } = await import('node: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\nconst { randomFillSync } = require('node:crypto');\nconst { Buffer } = require('node: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": "v18.0.0",
"pr-url": "https://github.com/nodejs/node/pull/41678",
"description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`."
},
{
"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.
If the callback function is not provided, an error will be thrown.
import { Buffer } from 'node:buffer';\nconst { randomFill } = await import('node: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\nconst { randomFill } = require('node:crypto');\nconst { Buffer } = require('node: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\nAny ArrayBuffer, TypedArray, or DataView instance may be passed as\nbuffer.
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.
import { Buffer } from 'node:buffer';\nconst { randomFill } = await import('node: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\nconst { randomFill } = require('node:crypto');\nconst { Buffer } = require('node: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\nThis 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.
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.
Return a random integer n such that min <= n < max. This\nimplementation avoids modulo bias.
The range (max - min) must be less than 248. min and max must\nbe safe integers.
If the callback function is not provided, the random integer is\ngenerated synchronously.
// Asynchronous\nconst {\n randomInt,\n} = await import('node: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('node: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('node:crypto');\n\nconst n = randomInt(3);\nconsole.log(`Random number chosen from (0, 1, 2): ${n}`);\n\n// Synchronous\nconst {\n randomInt,\n} = require('node: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('node:crypto');\n\nconst n = randomInt(1, 7);\nconsole.log(`The dice rolled: ${n}`);\n\n// With `min` argument\nconst {\n randomInt,\n} = require('node: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",
"v14.17.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": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." }, { "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.
\nThe 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.
When passing strings for password or salt, please consider\ncaveats when using strings as inputs to cryptographic APIs.
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.
An exception is thrown when any of the input arguments specify invalid values\nor types.
\nconst {\n scrypt,\n} = await import('node: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\nconst {\n scrypt,\n} = require('node: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.
\nThe 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.
When passing strings for password or salt, please consider\ncaveats when using strings as inputs to cryptographic APIs.
An exception is thrown when key derivation fails, otherwise the derived key is\nreturned as a Buffer.
An exception is thrown when any of the input arguments specify invalid values\nor types.
\nconst {\n scryptSync,\n} = await import('node: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\nconst {\n scryptSync,\n} = require('node: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).
engine could be either an id or a path to the engine's shared library.
The optional flags argument uses ENGINE_METHOD_ALL by default. The flags\nis a bit field taking one of or a mix of the following flags (defined in\ncrypto.constants):
crypto.constants.ENGINE_METHOD_RSAcrypto.constants.ENGINE_METHOD_DSAcrypto.constants.ENGINE_METHOD_DHcrypto.constants.ENGINE_METHOD_RANDcrypto.constants.ENGINE_METHOD_ECcrypto.constants.ENGINE_METHOD_CIPHERScrypto.constants.ENGINE_METHOD_DIGESTScrypto.constants.ENGINE_METHOD_PKEY_METHScrypto.constants.ENGINE_METHOD_PKEY_ASN1_METHScrypto.constants.ENGINE_METHOD_ALLcrypto.constants.ENGINE_METHOD_NONEEnables 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": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41678", "description": "Passing an invalid callback to the `callback` argument now throws `ERR_INVALID_ARG_TYPE` instead of `ERR_INVALID_CALLBACK`." }, { "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": "\nalgorithm <string> | <null> | <undefined>data <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView>key <Object> | <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey>callback <Function>\n\ncallback function is not provided.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).
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:
dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:
'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.padding <integer> Optional padding value for RSA, one of the following:
crypto.constants.RSA_PKCS1_PADDING (default)crypto.constants.RSA_PKCS1_PSS_PADDINGRSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to sign the message as specified in section 3.1 of RFC 4055.
saltLength <integer> Salt length for when padding is\nRSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the\nmaximum permissible value.
If the callback function is provided this function uses libuv's threadpool.
This function compares the underlying bytes that represent the given\nArrayBuffer, TypedArray, or DataView instances using a constant-time\nalgorithm.
This function does not leak 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.
\na and b must both be Buffers, TypedArrays, or DataViews, and they\nmust have the same byte length. An error is thrown if a and b have\ndifferent byte lengths.
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.
When both of the inputs are Float32Arrays or\nFloat64Arrays, this function might return unexpected results due to IEEE 754\nencoding of floating-point numbers. In particular, neither x === y nor\nObject.is(x, y) implies that the byte representations of two floating-point\nnumbers x and y are equal.
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.
algorithm <string> | <null> | <undefined>data <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView>key <Object> | <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey>signature <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView>callback <Function>\n\ntrue or false depending on the validity of the\nsignature for the data and public key if the callback function is not\nprovided.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).
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:
dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the signature. It can be one of the following:
'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.padding <integer> Optional padding value for RSA, one of the following:
crypto.constants.RSA_PKCS1_PADDING (default)crypto.constants.RSA_PKCS1_PSS_PADDINGRSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to sign the message as specified in section 3.1 of RFC 4055.
saltLength <integer> Salt length for when padding is\nRSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the\nmaximum permissible value.
The signature argument is the previously calculated signature for the data.
Because public keys can be derived from private keys, a private key or a public\nkey may be passed for key.
If the callback function is provided this function uses libuv's threadpool.
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.
\nWhen passing strings to cryptographic APIs, consider the following factors.
\nNot all byte sequences are valid UTF-8 strings. Therefore, when a byte\nsequence of length n is derived from a string, its entropy is generally\nlower than the entropy of a random or pseudorandom n byte sequence.\nFor example, no UTF-8 string will result in the byte sequence c0 af. Secret\nkeys should almost exclusively be random or pseudorandom byte sequences.
Similarly, when converting random or pseudorandom byte sequences to UTF-8\nstrings, subsequences that do not represent valid code points may be replaced\nby the Unicode replacement character (U+FFFD). The byte representation of\nthe resulting Unicode string may, therefore, not be equal to the byte sequence\nthat the string was created from.
const original = [0xc0, 0xaf];\nconst bytesAsString = Buffer.from(original).toString('utf8');\nconst stringAsBytes = Buffer.from(bytesAsString, 'utf8');\nconsole.log(stringAsBytes);\n// Prints '<Buffer ef bf bd ef bf bd>'.\n\nThe outputs of ciphers, hash functions, signature algorithms, and key\nderivation functions are pseudorandom byte sequences and should not be\nused as Unicode strings.
\nWhen strings are obtained from user input, some Unicode characters can be\nrepresented in multiple equivalent ways that result in different byte\nsequences. For example, when passing a user passphrase to a key derivation\nfunction, such as PBKDF2 or scrypt, the result of the key derivation function\ndepends on whether the string uses composed or decomposed characters. Node.js\ndoes not normalize character representations. Developers should consider using\nString.prototype.normalize() on user inputs before passing them to\ncryptographic APIs.
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, many crypto 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.
The node:crypto module still supports some algorithms which are already\ncompromised and are not 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.
Users should take full responsibility for selecting the crypto\nalgorithm and key size according to their security requirements.
\nBased on the recommendations of NIST SP 800-131A:
\nmodp1, modp2 and modp5 have a key size\nsmaller than 2048 bits and are not recommended.See the reference for other recommendations and details.
\nSome algorithms that have known weaknesses and are of little relevance in\npractice are only available through the legacy provider, which is not\nenabled by default.
", "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:
\nauthTagLength option and must be one of 4, 6, 8, 10, 12, 14 or\n16 bytes.N must be between 7 and 13\nbytes (7 ≤ N ≤ 13).2 ** (8 * (15 - N)) bytes.setAuthTag() before\ncalling update().\nOtherwise, decryption will fail and final() will throw an error in\ncompliance with section 2.6 of RFC 3610.write(data), end(data) or pipe() in CCM\nmode might fail as CCM cannot handle more than one chunk of data per instance.setAAD() via the plaintextLength\noption.\nMany crypto libraries include the authentication tag in the ciphertext,\nwhich means that they produce ciphertexts of the length\nplaintextLength + authTagLength. Node.js does not include the authentication\ntag, so the ciphertext length is always plaintextLength.\nThis is not necessary if no AAD is used.update() must be called exactly\nonce.update() is sufficient to encrypt/decrypt the message,\napplications must call final() to compute or verify the\nauthentication tag.import { Buffer } from 'node:buffer';\nconst {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} = await import('node: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 throw new Error('Authentication failed!', { cause: err });\n}\n\nconsole.log(receivedPlaintext);\n\nconst { Buffer } = require('node:buffer');\nconst {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} = require('node: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 throw new Error('Authentication failed!', { cause: err });\n}\n\nconsole.log(receivedPlaintext);\n",
"type": "module",
"displayName": "CCM mode"
},
{
"textRaw": "FIPS mode",
"name": "fips_mode",
"desc": "When using OpenSSL 3, Node.js supports FIPS 140-2 when used with an appropriate\nOpenSSL 3 provider, such as the FIPS provider from OpenSSL 3 which can be\ninstalled by following the instructions in OpenSSL's FIPS README file.
\nFor FIPS support in Node.js you will need:
\nNode.js will need to be configured with an OpenSSL configuration file that\npoints to the FIPS provider. An example configuration file looks like this:
\nnodejs_conf = nodejs_init\n\n.include /<absolute path>/fipsmodule.cnf\n\n[nodejs_init]\nproviders = provider_sect\n\n[provider_sect]\ndefault = default_sect\n# The fips section name should match the section name inside the\n# included fipsmodule.cnf.\nfips = fips_sect\n\n[default_sect]\nactivate = 1\n\nwhere fipsmodule.cnf is the FIPS module configuration file generated from the\nFIPS provider installation step:
openssl fipsinstall\n\nSet the OPENSSL_CONF environment variable to point to\nyour configuration file and OPENSSL_MODULES to the location of the FIPS\nprovider dynamic library. e.g.
export OPENSSL_CONF=/<path to configuration file>/nodejs.cnf\nexport OPENSSL_MODULES=/<path to openssl lib>/ossl-modules\n\nFIPS mode can then be enabled in Node.js either by:
\n--enable-fips or --force-fips command line flags.crypto.setFips(true).Optionally FIPS mode can be enabled in Node.js via the OpenSSL configuration\nfile. e.g.
\nnodejs_conf = nodejs_init\n\n.include /<absolute path>/fipsmodule.cnf\n\n[nodejs_init]\nproviders = provider_sect\nalg_section = algorithm_sect\n\n[provider_sect]\ndefault = default_sect\n# The fips section name should match the section name inside the\n# included fipsmodule.cnf.\nfips = fips_sect\n\n[default_sect]\nactivate = 1\n\n[algorithm_sect]\ndefault_properties = fips=yes\n",
"type": "module",
"displayName": "FIPS 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 node:crypto, node:tls, and node:https modules and are generally\nspecific to OpenSSL.
See the list of SSL OP Flags for details.
\n| Constant | \nDescription | \n
|---|---|
SSL_OP_ALL | \n Applies multiple bug workarounds within OpenSSL. See\n https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html\n for detail. | \n
SSL_OP_ALLOW_NO_DHE_KEX | \n Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode\n for TLS v1.3 | \n
SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION | \n Allows legacy insecure renegotiation between OpenSSL and unpatched\n clients or servers. See\n https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html. | \n
SSL_OP_CIPHER_SERVER_PREFERENCE | \n Attempts 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/man3.0/man3/SSL_CTX_set_options.html. | \n
SSL_OP_CISCO_ANYCONNECT | \n Instructs OpenSSL to use Cisco's \"speshul\" version of DTLS_BAD_VER. | \n
SSL_OP_COOKIE_EXCHANGE | \n Instructs OpenSSL to turn on cookie exchange. | \n
SSL_OP_CRYPTOPRO_TLSEXT_BUG | \n Instructs OpenSSL to add server-hello extension from an early version\n of the cryptopro draft. | \n
SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS | \n Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability\n workaround added in OpenSSL 0.9.6d. | \n
SSL_OP_LEGACY_SERVER_CONNECT | \n Allows initial connection to servers that do not support RI. | \n
SSL_OP_NO_COMPRESSION | \n Instructs OpenSSL to disable support for SSL/TLS compression. | \n
SSL_OP_NO_ENCRYPT_THEN_MAC | \n Instructs OpenSSL to disable encrypt-then-MAC. | \n
SSL_OP_NO_QUERY_MTU | \n \n |
SSL_OP_NO_RENEGOTIATION | \n Instructs OpenSSL to disable renegotiation. | \n
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | \n Instructs OpenSSL to always start a new session when performing\n renegotiation. | \n
SSL_OP_NO_SSLv2 | \n Instructs OpenSSL to turn off SSL v2 | \n
SSL_OP_NO_SSLv3 | \n Instructs OpenSSL to turn off SSL v3 | \n
SSL_OP_NO_TICKET | \n Instructs OpenSSL to disable use of RFC4507bis tickets. | \n
SSL_OP_NO_TLSv1 | \n Instructs OpenSSL to turn off TLS v1 | \n
SSL_OP_NO_TLSv1_1 | \n Instructs OpenSSL to turn off TLS v1.1 | \n
SSL_OP_NO_TLSv1_2 | \n Instructs OpenSSL to turn off TLS v1.2 | \n
SSL_OP_NO_TLSv1_3 | \n Instructs OpenSSL to turn off TLS v1.3 | \n
SSL_OP_PRIORITIZE_CHACHA | \n Instructs OpenSSL server to prioritize ChaCha20-Poly1305\n when the client does.\n This option has no effect if\n SSL_OP_CIPHER_SERVER_PREFERENCE\n is not enabled. | \n
SSL_OP_TLS_ROLLBACK_BUG | \n Instructs OpenSSL to disable version rollback attack detection. | \n
| Constant | \nDescription | \n
|---|---|
ENGINE_METHOD_RSA | \n Limit engine usage to RSA | \n
ENGINE_METHOD_DSA | \n Limit engine usage to DSA | \n
ENGINE_METHOD_DH | \n Limit engine usage to DH | \n
ENGINE_METHOD_RAND | \n Limit engine usage to RAND | \n
ENGINE_METHOD_EC | \n Limit engine usage to EC | \n
ENGINE_METHOD_CIPHERS | \n Limit engine usage to CIPHERS | \n
ENGINE_METHOD_DIGESTS | \n Limit engine usage to DIGESTS | \n
ENGINE_METHOD_PKEY_METHS | \n Limit engine usage to PKEY_METHDS | \n
ENGINE_METHOD_PKEY_ASN1_METHS | \n Limit engine usage to PKEY_ASN1_METHS | \n
ENGINE_METHOD_ALL | \n \n |
ENGINE_METHOD_NONE | \n \n |
| Constant | \nDescription | \n
|---|---|
DH_CHECK_P_NOT_SAFE_PRIME | \n \n |
DH_CHECK_P_NOT_PRIME | \n \n |
DH_UNABLE_TO_CHECK_GENERATOR | \n \n |
DH_NOT_SUITABLE_GENERATOR | \n \n |
ALPN_ENABLED | \n \n |
RSA_PKCS1_PADDING | \n \n |
RSA_SSLV23_PADDING | \n \n |
RSA_NO_PADDING | \n \n |
RSA_PKCS1_OAEP_PADDING | \n \n |
RSA_X931_PADDING | \n \n |
RSA_PKCS1_PSS_PADDING | \n \n |
RSA_PSS_SALTLEN_DIGEST | \n Sets the salt length for RSA_PKCS1_PSS_PADDING to the\n digest size when signing or verifying. | \n
RSA_PSS_SALTLEN_MAX_SIGN | \n Sets the salt length for RSA_PKCS1_PSS_PADDING to the\n maximum permissible value when signing data. | \n
RSA_PSS_SALTLEN_AUTO | \n Causes the salt length for RSA_PKCS1_PSS_PADDING to be\n determined automatically when verifying a signature. | \n
POINT_CONVERSION_COMPRESSED | \n \n |
POINT_CONVERSION_UNCOMPRESSED | \n \n |
POINT_CONVERSION_HYBRID | \n \n |
| Constant | \nDescription | \n
|---|---|
defaultCoreCipherList | \n Specifies the built-in default cipher list used by Node.js. | \n
defaultCipherList | \n Specifies the active default cipher list used by the current Node.js\n process. | \n
SPKAC is a Certificate Signing Request mechanism originally implemented by\nNetscape and was specified formally as part of HTML5's keygen element.
<keygen> is deprecated since HTML 5.2 and new projects\nshould not use this element anymore.
The node: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.
const { Certificate } = await import('node:crypto');\nconst spkac = getSpkacSomehow();\nconst challenge = Certificate.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n\nconst { Certificate } = require('node: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('node:crypto');\nconst spkac = getSpkacSomehow();\nconst publicKey = Certificate.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n\nconst { Certificate } = require('node: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 'node:buffer';\nconst { Certificate } = await import('node:crypto');\n\nconst spkac = getSpkacSomehow();\nconsole.log(Certificate.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n\nconst { Buffer } = require('node:buffer');\nconst { Certificate } = require('node:crypto');\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.
Instances of the Certificate class can be created using the new keyword\nor by calling crypto.Certificate() as a function:
const { Certificate } = await import('node:crypto');\n\nconst cert1 = new Certificate();\nconst cert2 = Certificate();\n\nconst { Certificate } = require('node: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('node: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\nconst { Certificate } = require('node: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('node:crypto');\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconst publicKey = cert.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n\nconst { Certificate } = require('node: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 'node:buffer';\nconst { Certificate } = await import('node:crypto');\n\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n\nconst { Buffer } = require('node:buffer');\nconst { Certificate } = require('node:crypto');\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": "Instances of the Cipher class are used to encrypt data. The class can be\nused in one of two ways:
cipher.update() and cipher.final() methods to produce\nthe encrypted data.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.
Example: Using Cipher objects as streams:
const {\n scrypt,\n randomFill,\n createCipheriv,\n} = await import('node: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\nconst {\n scrypt,\n randomFill,\n createCipheriv,\n} = require('node: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\nExample: Using Cipher and piped streams:
import {\n createReadStream,\n createWriteStream,\n} from 'node:fs';\n\nimport {\n pipeline,\n} from 'node:stream';\n\nconst {\n scrypt,\n randomFill,\n createCipheriv,\n} = await import('node: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\nconst {\n createReadStream,\n createWriteStream,\n} = require('node:fs');\n\nconst {\n pipeline,\n} = require('node:stream');\n\nconst {\n scrypt,\n randomFill,\n createCipheriv,\n} = require('node: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\nExample: Using the cipher.update() and cipher.final() methods:
const {\n scrypt,\n randomFill,\n createCipheriv,\n} = await import('node: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\nconst {\n scrypt,\n randomFill,\n createCipheriv,\n} = require('node: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.
The cipher.getAuthTag() method should only be called after encryption has\nbeen completed using the cipher.final() method.
If the authTagLength option was set during the cipher instance's creation,\nthis function will return exactly authTagLength bytes.
When using an authenticated encryption mode (GCM, CCM, OCB, and\nchacha20-poly1305 are\ncurrently supported), the cipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.
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.
The cipher.setAAD() method must be called before cipher.update().
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).
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.
The cipher.setAutoPadding() method must be called before\ncipher.final().
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.
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.
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.
Instances of the Decipher class are used to decrypt data. The class can be\nused in one of two ways:
decipher.update() and decipher.final() methods to\nproduce the unencrypted data.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.
Example: Using Decipher objects as streams:
import { Buffer } from 'node:buffer';\nconst {\n scryptSync,\n createDecipheriv,\n} = await import('node: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 let chunk;\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\nconst {\n scryptSync,\n createDecipheriv,\n} = require('node:crypto');\nconst { Buffer } = require('node: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 let chunk;\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\nExample: Using Decipher and piped streams:
import {\n createReadStream,\n createWriteStream,\n} from 'node:fs';\nimport { Buffer } from 'node:buffer';\nconst {\n scryptSync,\n createDecipheriv,\n} = await import('node: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\nconst {\n createReadStream,\n createWriteStream,\n} = require('node:fs');\nconst {\n scryptSync,\n createDecipheriv,\n} = require('node:crypto');\nconst { Buffer } = require('node: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\nExample: Using the decipher.update() and decipher.final() methods:
import { Buffer } from 'node:buffer';\nconst {\n scryptSync,\n createDecipheriv,\n} = await import('node: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\nconst {\n scryptSync,\n createDecipheriv,\n} = require('node:crypto');\nconst { Buffer } = require('node: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.
When using an authenticated encryption mode (GCM, CCM, OCB, and\nchacha20-poly1305 are\ncurrently supported), the decipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.
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.
The decipher.setAAD() method must be called before decipher.update().
When passing a string as the buffer, please consider\ncaveats when using strings as inputs to cryptographic APIs.
When using an authenticated encryption mode (GCM, CCM, OCB, and\nchacha20-poly1305 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.
The decipher.setAuthTag() method must be called before decipher.update()\nfor CCM mode or before decipher.final() for GCM and OCB modes and\nchacha20-poly1305.\ndecipher.setAuthTag() can only be called once.
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.
Turning auto padding off will only work if the input data's length is a\nmultiple of the ciphers block size.
\nThe decipher.setAutoPadding() method must be called before\ndecipher.final().
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.
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.
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.
The DiffieHellman class is a utility for creating Diffie-Hellman key\nexchanges.
Instances of the DiffieHellman class can be created using the\ncrypto.createDiffieHellman() function.
import assert from 'node:assert';\n\nconst {\n createDiffieHellman,\n} = await import('node: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\nconst assert = require('node:assert');\n\nconst {\n createDiffieHellman,\n} = require('node: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.
If outputEncoding is given a string is returned; otherwise, a\nBuffer is returned.
Generates private and public Diffie-Hellman key values unless they have been\ngenerated or computed already, 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.
This function is a thin wrapper around DH_generate_key(). In particular,\nonce a private key has been generated or set, calling this function only updates\nthe public key but does not generate a new private key.
Returns the Diffie-Hellman generator in the specified encoding.\nIf encoding is provided a string is\nreturned; otherwise a Buffer is returned.
Returns the Diffie-Hellman prime in the specified encoding.\nIf encoding is provided a string is\nreturned; otherwise a Buffer is returned.
Returns the Diffie-Hellman private key in the specified encoding.\nIf encoding is provided a\nstring is returned; otherwise a Buffer is returned.
Returns the Diffie-Hellman public key in the specified encoding.\nIf encoding is provided a\nstring is returned; otherwise a Buffer is returned.
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.
This function does not automatically compute the associated public key. Either\ndiffieHellman.setPublicKey() or diffieHellman.generateKeys() can be\nused to manually provide the public key or to automatically derive it.
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.
A bit field containing any warnings and/or errors resulting from a check\nperformed during initialization of the DiffieHellman object.
The following values are valid for this property (as defined in node:constants module):
DH_CHECK_P_NOT_SAFE_PRIMEDH_CHECK_P_NOT_PRIMEDH_UNABLE_TO_CHECK_GENERATORDH_NOT_SUITABLE_GENERATORThe 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.
const { createDiffieHellmanGroup } = await import('node:crypto');\nconst dh = createDiffieHellmanGroup('modp16');\n\nconst { createDiffieHellmanGroup } = require('node:crypto');\nconst dh = createDiffieHellmanGroup('modp16');\n\nThe following groups are supported:
\n'modp14' (2048 bits, RFC 3526 Section 3)'modp15' (3072 bits, RFC 3526 Section 4)'modp16' (4096 bits, RFC 3526 Section 5)'modp17' (6144 bits, RFC 3526 Section 6)'modp18' (8192 bits, RFC 3526 Section 7)The following groups are still supported but deprecated (see Caveats):
\n'modp1' (768 bits, RFC 2409 Section 6.1) 'modp2' (1024 bits, RFC 2409 Section 6.2) 'modp5' (1536 bits, RFC 3526 Section 2) These deprecated groups might be removed in future versions of Node.js.
" }, { "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.
Instances of the ECDH class can be created using the\ncrypto.createECDH() function.
import assert from 'node:assert';\n\nconst {\n createECDH,\n} = await import('node: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\nconst assert = require('node:assert');\n\nconst {\n createECDH,\n} = require('node: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.
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.
If format is not specified the point will be returned in 'uncompressed'\nformat.
If the inputEncoding is not provided, key is expected to be a Buffer,\nTypedArray, or DataView.
Example (uncompressing a key):
\nconst {\n createECDH,\n ECDH,\n} = await import('node: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\nconst {\n createECDH,\n ECDH,\n} = require('node: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.
If outputEncoding is given a string will be returned; otherwise a\nBuffer is returned.
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.
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.
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.
If encoding is provided a string is returned; otherwise a Buffer\nis returned.
If encoding is specified, a string is returned; otherwise a Buffer is\nreturned.
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.
If encoding is specified, a string is returned; otherwise a Buffer is\nreturned.
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.
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.
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.
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.
Example (obtaining a shared secret):
\nconst {\n createECDH,\n createHash,\n} = await import('node: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\nconst {\n createECDH,\n createHash,\n} = require('node: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": "The Hash class is a utility for creating hash digests of data. It can be\nused in one of two ways:
hash.update() and hash.digest() methods to produce the\ncomputed hash.The crypto.createHash() method is used to create Hash instances. Hash\nobjects are not to be created directly using the new keyword.
Example: Using Hash objects as streams:
const {\n createHash,\n} = await import('node: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\nconst {\n createHash,\n} = require('node: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\nExample: Using Hash and piped streams:
import { createReadStream } from 'node:fs';\nimport { stdout } from 'node:process';\nconst { createHash } = await import('node:crypto');\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream('test.js');\ninput.pipe(hash).setEncoding('hex').pipe(stdout);\n\nconst { createReadStream } = require('node:fs');\nconst { createHash } = require('node:crypto');\nconst { stdout } = require('node:process');\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream('test.js');\ninput.pipe(hash).setEncoding('hex').pipe(stdout);\n\nExample: Using the hash.update() and hash.digest() methods:
const {\n createHash,\n} = await import('node:crypto');\n\nconst hash = createHash('sha256');\n\nhash.update('some data to hash');\nconsole.log(hash.digest('hex'));\n// Prints:\n// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n\nconst {\n createHash,\n} = require('node: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.
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.
An error is thrown when an attempt is made to copy the Hash object after\nits hash.digest() method has been called.
// Calculate a rolling hash.\nconst {\n createHash,\n} = await import('node: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('node: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.
The Hash object can not be used again after hash.digest() method has been\ncalled. Multiple calls will cause an error to be thrown.
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.
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": "The Hmac class is a utility for creating cryptographic HMAC digests. It can\nbe used in one of two ways:
hmac.update() and hmac.digest() methods to produce the\ncomputed HMAC digest.The crypto.createHmac() method is used to create Hmac instances. Hmac\nobjects are not to be created directly using the new keyword.
Example: Using Hmac objects as streams:
const {\n createHmac,\n} = await import('node: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\nconst {\n createHmac,\n} = require('node: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\nExample: Using Hmac and piped streams:
import { createReadStream } from 'node:fs';\nimport { stdout } from 'node:process';\nconst {\n createHmac,\n} = await import('node:crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream('test.js');\ninput.pipe(hmac).pipe(stdout);\n\nconst {\n createReadStream,\n} = require('node:fs');\nconst {\n createHmac,\n} = require('node:crypto');\nconst { stdout } = require('node:process');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream('test.js');\ninput.pipe(hmac).pipe(stdout);\n\nExample: Using the hmac.update() and hmac.digest() methods:
const {\n createHmac,\n} = await import('node: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\nconst {\n createHmac,\n} = require('node: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;
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.
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.
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.
Most applications should consider using the new KeyObject API instead of\npassing keys as strings or Buffers due to improved security features.
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.
Example: Converting a CryptoKey instance to a KeyObject:
const { webcrypto, KeyObject } = await import('node: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\nconst {\n webcrypto: {\n subtle,\n },\n KeyObject,\n} = require('node: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": [
{
"version": "v16.9.0",
"pr-url": "https://github.com/nodejs/node/pull/39851",
"description": "Expose `RSASSA-PSS-params` sequence parameters for RSA-PSS keys."
}
]
},
"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": "`hashAlgorithm`: {string} Name of the message digest (RSA-PSS).",
"name": "hashAlgorithm",
"type": "string",
"desc": "Name of the message digest (RSA-PSS)."
},
{
"textRaw": "`mgf1HashAlgorithm`: {string} Name of the message digest used by MGF1 (RSA-PSS).",
"name": "mgf1HashAlgorithm",
"type": "string",
"desc": "Name of the message digest used by MGF1 (RSA-PSS)."
},
{
"textRaw": "`saltLength`: {number} Minimal salt length in bytes (RSA-PSS).",
"name": "saltLength",
"type": "number",
"desc": "Minimal salt length in bytes (RSA-PSS)."
},
{
"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.
\nFor RSA-PSS keys, if the key material contains a RSASSA-PSS-params sequence,\nthe hashAlgorithm, mgf1HashAlgorithm, and saltLength properties will be\nset.
Other key details might be exposed via this API 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'rsa' (OID 1.2.840.113549.1.1.1)'rsa-pss' (OID 1.2.840.113549.1.1.10)'dsa' (OID 1.2.840.10040.4.1)'ec' (OID 1.2.840.10045.2.1)'x25519' (OID 1.3.101.110)'x448' (OID 1.3.101.111)'ed25519' (OID 1.3.101.112)'ed448' (OID 1.3.101.113)'dh' (OID 1.2.840.113549.1.3.1)This property is undefined for unrecognized KeyObject types and symmetric\nkeys.
For secret keys, this property represents the size of the key in bytes. This\nproperty is undefined for asymmetric keys.
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.
For symmetric keys, the following encoding options can be used:
\nformat: <string> Must be 'buffer' (default) or 'jwk'.For public keys, the following encoding options can be used:
\ntype: <string> Must be one of 'pkcs1' (RSA only) or 'spki'.format: <string> Must be 'pem', 'der', or 'jwk'.For private keys, the following encoding options can be used:
\ntype: <string> Must be one of 'pkcs1' (RSA only), 'pkcs8' or\n'sec1' (EC only).format: <string> Must be 'pem', 'der', or 'jwk'.cipher: <string> If specified, the private key will be encrypted with\nthe given cipher and passphrase using PKCS#5 v2.0 password based\nencryption.passphrase: <string> | <Buffer> The passphrase to use for encryption, see\ncipher.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.
\nWhen JWK encoding format was selected, all other encoding options are\nignored.
\nPKCS#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.
Returns true or false depending on whether the keys have exactly the same\ntype, value, and parameters. This method is not\nconstant time.
The Sign class is a utility for generating signatures. It can be used in one\nof two ways:
sign.sign() method is used to generate and return the signature, orsign.update() and sign.sign() methods to produce the\nsignature.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.
Example: Using Sign and Verify objects as streams:
const {\n generateKeyPairSync,\n createSign,\n createVerify,\n} = await import('node: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\nconst {\n generateKeyPairSync,\n createSign,\n createVerify,\n} = require('node: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\nExample: Using the sign.update() and verify.update() methods:
const {\n generateKeyPairSync,\n createSign,\n createVerify,\n} = await import('node: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\nconst {\n generateKeyPairSync,\n createSign,\n createVerify,\n} = require('node: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": "\nprivateKey <Object> | <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey>\n\noutputEncoding <string> The encoding of the return value.Calculates the signature on all the data passed through using either\nsign.update() or sign.write().
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:
dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:
'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.padding <integer> Optional padding value for RSA, one of the following:
crypto.constants.RSA_PKCS1_PADDING (default)crypto.constants.RSA_PKCS1_PSS_PADDINGRSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to sign the message as specified in section 3.1 of RFC 4055, unless\nan MGF1 hash function has been specified as part of the key in compliance with\nsection 3.3 of RFC 4055.
saltLength <integer> Salt length for when padding is\nRSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN (default) sets it to the\nmaximum permissible value.
If outputEncoding is provided a string is returned; otherwise a Buffer\nis returned.
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.
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.
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": "The Verify class is a utility for verifying signatures. It can be used in one\nof two ways:
verify.update() and verify.verify() methods to verify\nthe signature.The crypto.createVerify() method is used to create Verify instances.\nVerify objects are not to be created directly using the new keyword.
See Sign for examples.
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.
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": "\nobject <Object> | <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView> | <KeyObject> | <CryptoKey>\n\nsignature <string> | <ArrayBuffer> | <Buffer> | <TypedArray> | <DataView>signatureEncoding <string> The encoding of the signature string.true or false depending on the validity of the\nsignature for the data and public key.Verifies the provided data using the given object and signature.
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:
dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the signature. It can be one of the following:
'der' (default): DER-encoded ASN.1 signature structure encoding (r, s).'ieee-p1363': Signature format r || s as proposed in IEEE-P1363.padding <integer> Optional padding value for RSA, one of the following:
crypto.constants.RSA_PKCS1_PADDING (default)crypto.constants.RSA_PKCS1_PSS_PADDINGRSA_PKCS1_PSS_PADDING will use MGF1 with the same hash function\nused to verify the message as specified in section 3.1 of RFC 4055, unless\nan MGF1 hash function has been specified as part of the key in compliance with\nsection 3.3 of RFC 4055.
saltLength <integer> Salt length for when padding is\nRSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_AUTO (default) causes it to be\ndetermined automatically.
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.
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.
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.
\nconst { X509Certificate } = await import('node:crypto');\n\nconst x509 = new X509Certificate('{... pem encoded cert ...}');\n\nconsole.log(x509.subject);\n\nconst { X509Certificate } = require('node: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.
\nBecause SHA-1 is cryptographically broken and because the security of SHA-1 is\nsignificantly worse than that of algorithms that are commonly used to sign\ncertificates, consider using x509.fingerprint256 instead.
The SHA-256 fingerprint of this certificate.
" }, { "textRaw": "`fingerprint512` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v17.2.0", "v16.14.0" ], "changes": [] }, "desc": "The SHA-512 fingerprint of this certificate.
\nBecause computing the SHA-256 fingerprint is usually faster and because it is\nonly half the size of the SHA-512 fingerprint, x509.fingerprint256 may be\na better choice. While SHA-512 presumably provides a higher level of security in\ngeneral, the security of SHA-256 matches that of most algorithms that are\ncommonly used to sign certificates.
A textual representation of the certificate's authority information access\nextension.
\nThis is a line feed separated list of access descriptions. Each line begins with\nthe access method and the kind of the access location, followed by a colon and\nthe value associated with the access location.
\nAfter the prefix denoting the access method and the kind of the access location,\nthe remainder of each line might be enclosed in quotes to indicate that the\nvalue is a JSON string literal. For backward compatibility, Node.js only uses\nJSON string literals within this property when necessary to avoid ambiguity.\nThird-party code should be prepared to handle both possible entry formats.
" }, { "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.
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.
The serial number of this certificate.
\nSerial numbers are assigned by certificate authorities and do not uniquely\nidentify certificates. Consider using x509.fingerprint256 as a unique\nidentifier instead.
The complete subject of this certificate.
" }, { "textRaw": "`subjectAltName` Type: {string}", "type": "string", "name": "Type", "meta": { "added": [ "v15.6.0" ], "changes": [ { "version": [ "v17.3.1", "v16.13.2" ], "pr-url": "https://github.com/nodejs-private/node-private/pull/300", "description": "Parts of this string may be encoded as JSON string literals in response to CVE-2021-44532." } ] }, "desc": "The subject alternative name specified for this certificate.
\nThis is a comma-separated list of subject alternative names. Each entry begins\nwith a string identifying the kind of the subject alternative name followed by\na colon and the value associated with the entry.
\nEarlier versions of Node.js incorrectly assumed that it is safe to split this\nproperty at the two-character sequence ', ' (see CVE-2021-44532). However,\nboth malicious and legitimate certificates can contain subject alternative names\nthat include this sequence when represented as a string.
After the prefix denoting the type of the entry, the remainder of each entry\nmight be enclosed in quotes to indicate that the value is a JSON string literal.\nFor backward compatibility, Node.js only uses JSON string literals within this\nproperty when necessary to avoid ambiguity. Third-party code should be prepared\nto handle both possible entry formats.
" }, { "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": [ { "version": "v18.0.0", "pr-url": "https://github.com/nodejs/node/pull/41600", "description": "The subject option now defaults to `'default'`." }, { "version": [ "v17.5.0", "v16.14.1" ], "pr-url": "https://github.com/nodejs/node/pull/41599", "description": "The `wildcards`, `partialWildcards`, `multiLabelWildcards`, and `singleLabelSubdomains` options have been removed since they had no effect." }, { "version": "v17.5.0", "pr-url": "https://github.com/nodejs/node/pull/41569", "description": "The subject option can now be set to `'default'`." } ] }, "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} `'default'`, `'always'`, or `'never'`. **Default:** `'default'`.", "name": "subject", "type": "string", "default": "`'default'`", "desc": "`'default'`, `'always'`, or `'never'`." } ] } ] } ], "desc": "Checks whether the certificate matches the given email address.
\nIf the 'subject' option is undefined or set to 'default', the certificate\nsubject is only considered if the subject alternative name extension either does\nnot exist or does not contain any email addresses.
If the 'subject' option is set to 'always' and if the subject alternative\nname extension either does not exist or does not contain a matching email\naddress, the certificate subject is considered.
If the 'subject' option is set to 'never', the certificate subject is never\nconsidered, even if the certificate contains no subject alternative names.
Checks whether the certificate matches the given host name.
\nIf the certificate matches the given host name, the matching subject name is\nreturned. The returned name might be an exact match (e.g., foo.example.com)\nor it might contain wildcards (e.g., *.example.com). Because host name\ncomparisons are case-insensitive, the returned subject name might also differ\nfrom the given name in capitalization.
If the 'subject' option is undefined or set to 'default', the certificate\nsubject is only considered if the subject alternative name extension either does\nnot exist or does not contain any DNS names. This behavior is consistent with\nRFC 2818 (\"HTTP Over TLS\").
If the 'subject' option is set to 'always' and if the subject alternative\nname extension either does not exist or does not contain a matching DNS name,\nthe certificate subject is considered.
If the 'subject' option is set to 'never', the certificate subject is never\nconsidered, even if the certificate contains no subject alternative names.
Checks whether the certificate matches the given IP address (IPv4 or IPv6).
\nOnly RFC 5280 iPAddress subject alternative names are considered, and they\nmust match the given ip address exactly. Other subject alternative names as\nwell as the subject field of the certificate are ignored.
Checks whether this certificate was issued by the given otherCert.
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.
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" } ] }