/
opt
/
alt
/
alt-nodejs10
/
root
/
usr
/
share
/
doc
/
alt-nodejs10-nodejs-10.24.1
/
html
/
api
/
Upload Filee
HOME
{ "type": "module", "source": "doc/api/crypto.md", "modules": [ { "textRaw": "Crypto", "name": "crypto", "introduced_in": "v0.3.6", "stability": 2, "stabilityText": "Stable", "desc": "<p>The <code>crypto</code> module provides cryptographic functionality that includes a set of\nwrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.</p>\n<p>Use <code>require('crypto')</code> to access this module.</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\n\nconst secret = 'abcdefg';\nconst hash = crypto.createHmac('sha256', secret)\n .update('I love cupcakes')\n .digest('hex');\nconsole.log(hash);\n// Prints:\n// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e\n</code></pre>", "modules": [ { "textRaw": "Determining if crypto support is unavailable", "name": "determining_if_crypto_support_is_unavailable", "desc": "<p>It is possible for Node.js to be built without including support for the\n<code>crypto</code> module. In such cases, calling <code>require('crypto')</code> will result in an\nerror being thrown.</p>\n<pre><code class=\"language-js\">let crypto;\ntry {\n crypto = require('crypto');\n} catch (err) {\n console.log('crypto support is disabled!');\n}\n</code></pre>", "type": "module", "displayName": "Determining if crypto support is unavailable" }, { "textRaw": "`crypto` module methods and properties", "name": "`crypto`_module_methods_and_properties", "properties": [ { "textRaw": "`constants` Returns: {Object} An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in [Crypto Constants][].", "type": "Object", "name": "return", "meta": { "added": [ "v6.3.0" ], "changes": [] }, "desc": "An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in [Crypto Constants][]." }, { "textRaw": "crypto.DEFAULT_ENCODING", "name": "DEFAULT_ENCODING", "meta": { "added": [ "v0.9.3" ], "deprecated": [ "v10.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated", "desc": "<p>The default encoding to use for functions that can take either strings\nor <a href=\"buffer.html\">buffers</a>. The default value is <code>'buffer'</code>, which makes methods\ndefault to <a href=\"buffer.html\"><code>Buffer</code></a> objects.</p>\n<p>The <code>crypto.DEFAULT_ENCODING</code> mechanism is provided for backwards compatibility\nwith legacy programs that expect <code>'latin1'</code> to be the default encoding.</p>\n<p>New applications should expect the default to be <code>'buffer'</code>.</p>\n<p>This property is deprecated.</p>" }, { "textRaw": "crypto.fips", "name": "fips", "meta": { "added": [ "v6.0.0" ], "deprecated": [ "v10.0.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated", "desc": "<p>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.</p>\n<p>This property is deprecated. Please use <code>crypto.setFips()</code> and\n<code>crypto.getFips()</code> instead.</p>" } ], "methods": [ { "textRaw": "crypto.createCipher(algorithm, password[, options])", "type": "method", "name": "createCipher", "meta": { "added": [ "v0.1.94" ], "deprecated": [ "v10.0.0" ], "changes": [ { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/21447", "description": "Ciphers in OCB mode are now supported." }, { "version": "v10.2.0", "pr-url": "https://github.com/nodejs/node/pull/20235", "description": "The `authTagLength` option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes." } ] }, "stability": 0, "stabilityText": "Deprecated: Use [`crypto.createCipheriv()`][] instead.", "signatures": [ { "return": { "textRaw": "Returns: {Cipher}", "name": "return", "type": "Cipher" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`password` {string | Buffer | TypedArray | DataView}", "name": "password", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]", "optional": true } ] } ], "desc": "<p>Creates and returns a <code>Cipher</code> object that uses the given <code>algorithm</code> and\n<code>password</code>.</p>\n<p>The <code>options</code> argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. <code>'aes-128-ccm'</code>). In that case, the\n<code>authTagLength</code> option is required and specifies the length of the\nauthentication tag in bytes, see <a href=\"#crypto_ccm_mode\">CCM mode</a>. In GCM mode, the <code>authTagLength</code>\noption is not required but can be used to set the length of the authentication\ntag that will be returned by <code>getAuthTag()</code> and defaults to 16 bytes.</p>\n<p>The <code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc. On\nrecent OpenSSL releases, <code>openssl list -cipher-algorithms</code>\n(<code>openssl list-cipher-algorithms</code> for older versions of OpenSSL) will\ndisplay the available cipher algorithms.</p>\n<p>The <code>password</code> is used to derive the cipher key and initialization vector (IV).\nThe value must be either a <code>'latin1'</code> encoded string, a <a href=\"buffer.html\"><code>Buffer</code></a>, a\n<code>TypedArray</code>, or a <code>DataView</code>.</p>\n<p>The implementation of <code>crypto.createCipher()</code> derives keys using the OpenSSL\nfunction <a href=\"https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html\"><code>EVP_BytesToKey</code></a> 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.</p>\n<p>In line with OpenSSL's recommendation to use a more modern algorithm instead of\n<a href=\"https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html\"><code>EVP_BytesToKey</code></a> it is recommended that developers derive a key and IV on\ntheir own using <a href=\"#crypto_crypto_scrypt_password_salt_keylen_options_callback\"><code>crypto.scrypt()</code></a> and to use <a href=\"#crypto_crypto_createcipheriv_algorithm_key_iv_options\"><code>crypto.createCipheriv()</code></a>\nto create the <code>Cipher</code> object. Users should not use ciphers with counter mode\n(e.g. CTR, GCM, or CCM) in <code>crypto.createCipher()</code>. 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 <a href=\"https://github.com/nonce-disrespect/nonce-disrespect\">Nonce-Disrespecting\nAdversaries</a> for details.</p>" }, { "textRaw": "crypto.createCipheriv(algorithm, key, iv[, options])", "type": "method", "name": "createCipheriv", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v10.17.0", "pr-url": "https://github.com/nodejs/node/pull/24081", "description": "The cipher `chacha20-poly1305` is now supported." }, { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/21447", "description": "Ciphers in OCB mode are now supported." }, { "version": "v10.2.0", "pr-url": "https://github.com/nodejs/node/pull/20235", "description": "The `authTagLength` option can now be used to produce shorter authentication tags in GCM mode and defaults to 16 bytes." }, { "version": "v9.9.0", "pr-url": "https://github.com/nodejs/node/pull/18644", "description": "The `iv` parameter may now be `null` for ciphers which do not need an initialization vector." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Cipher}", "name": "return", "type": "Cipher" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`key` {string | Buffer | TypedArray | DataView}", "name": "key", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`iv` {string | Buffer | TypedArray | DataView}", "name": "iv", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]", "optional": true } ] } ], "desc": "<p>Creates and returns a <code>Cipher</code> object, with the given <code>algorithm</code>, <code>key</code> and\ninitialization vector (<code>iv</code>).</p>\n<p>The <code>options</code> argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. <code>'aes-128-ccm'</code>). In that case, the\n<code>authTagLength</code> option is required and specifies the length of the\nauthentication tag in bytes, see <a href=\"#crypto_ccm_mode\">CCM mode</a>. In GCM mode, the <code>authTagLength</code>\noption is not required but can be used to set the length of the authentication\ntag that will be returned by <code>getAuthTag()</code> and defaults to 16 bytes.</p>\n<p>The <code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc. On\nrecent OpenSSL releases, <code>openssl list -cipher-algorithms</code>\n(<code>openssl list-cipher-algorithms</code> for older versions of OpenSSL) will\ndisplay the available cipher algorithms.</p>\n<p>The <code>key</code> is the raw key used by the <code>algorithm</code> and <code>iv</code> is an\n<a href=\"https://en.wikipedia.org/wiki/Initialization_vector\">initialization vector</a>. Both arguments must be <code>'utf8'</code> encoded strings,\n<a href=\"buffer.html\">Buffers</a>, <code>TypedArray</code>, or <code>DataView</code>s. If the cipher does not need\nan initialization vector, <code>iv</code> may be <code>null</code>.</p>\n<p>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;\nit is important to remember that an attacker must not be able to predict ahead\nof time what a given IV will be.</p>" }, { "textRaw": "crypto.createCredentials(details)", "type": "method", "name": "createCredentials", "meta": { "added": [ "v0.1.92" ], "deprecated": [ "v0.11.13" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated: Use [`tls.createSecureContext()`][] instead.", "signatures": [ { "return": { "textRaw": "Returns: {tls.SecureContext}", "name": "return", "type": "tls.SecureContext" }, "params": [ { "textRaw": "`details` {Object} Identical to [`tls.createSecureContext()`][].", "name": "details", "type": "Object", "desc": "Identical to [`tls.createSecureContext()`][]." } ] } ], "desc": "<p>The <code>crypto.createCredentials()</code> method is a deprecated function for creating\nand returning a <code>tls.SecureContext</code>. It should not be used. Replace it with\n<a href=\"tls.html#tls_tls_createsecurecontext_options\"><code>tls.createSecureContext()</code></a> which has the exact same arguments and return\nvalue.</p>\n<p>Returns a <code>tls.SecureContext</code>, as-if <a href=\"tls.html#tls_tls_createsecurecontext_options\"><code>tls.createSecureContext()</code></a> had been\ncalled.</p>" }, { "textRaw": "crypto.createDecipher(algorithm, password[, options])", "type": "method", "name": "createDecipher", "meta": { "added": [ "v0.1.94" ], "deprecated": [ "v10.0.0" ], "changes": [ { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/21447", "description": "Ciphers in OCB mode are now supported." } ] }, "stability": 0, "stabilityText": "Deprecated: Use [`crypto.createDecipheriv()`][] instead.", "signatures": [ { "return": { "textRaw": "Returns: {Decipher}", "name": "return", "type": "Decipher" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`password` {string | Buffer | TypedArray | DataView}", "name": "password", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]", "optional": true } ] } ], "desc": "<p>Creates and returns a <code>Decipher</code> object that uses the given <code>algorithm</code> and\n<code>password</code> (key).</p>\n<p>The <code>options</code> argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. <code>'aes-128-ccm'</code>). In that case, the\n<code>authTagLength</code> option is required and specifies the length of the\nauthentication tag in bytes, see <a href=\"#crypto_ccm_mode\">CCM mode</a>.</p>\n<p>The implementation of <code>crypto.createDecipher()</code> derives keys using the OpenSSL\nfunction <a href=\"https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html\"><code>EVP_BytesToKey</code></a> 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.</p>\n<p>In line with OpenSSL's recommendation to use a more modern algorithm instead of\n<a href=\"https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html\"><code>EVP_BytesToKey</code></a> it is recommended that developers derive a key and IV on\ntheir own using <a href=\"#crypto_crypto_scrypt_password_salt_keylen_options_callback\"><code>crypto.scrypt()</code></a> and to use <a href=\"#crypto_crypto_createdecipheriv_algorithm_key_iv_options\"><code>crypto.createDecipheriv()</code></a>\nto create the <code>Decipher</code> object.</p>" }, { "textRaw": "crypto.createDecipheriv(algorithm, key, iv[, options])", "type": "method", "name": "createDecipheriv", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v10.17.0", "pr-url": "https://github.com/nodejs/node/pull/24081", "description": "The cipher `chacha20-poly1305` is now supported." }, { "version": "v10.10.0", "pr-url": "https://github.com/nodejs/node/pull/21447", "description": "Ciphers in OCB mode are now supported." }, { "version": "v10.2.0", "pr-url": "https://github.com/nodejs/node/pull/20039", "description": "The `authTagLength` option can now be used to restrict accepted GCM authentication tag lengths." }, { "version": "v9.9.0", "pr-url": "https://github.com/nodejs/node/pull/18644", "description": "The `iv` parameter may now be `null` for ciphers which do not need an initialization vector." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Decipher}", "name": "return", "type": "Decipher" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`key` {string | Buffer | TypedArray | DataView}", "name": "key", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`iv` {string | Buffer | TypedArray | DataView}", "name": "iv", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]", "optional": true } ] } ], "desc": "<p>Creates and returns a <code>Decipher</code> object that uses the given <code>algorithm</code>, <code>key</code>\nand initialization vector (<code>iv</code>).</p>\n<p>The <code>options</code> argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode is used (e.g. <code>'aes-128-ccm'</code>). In that case, the\n<code>authTagLength</code> option is required and specifies the length of the\nauthentication tag in bytes, see <a href=\"#crypto_ccm_mode\">CCM mode</a>. In GCM mode, the <code>authTagLength</code>\noption is not required but can be used to restrict accepted authentication tags\nto those with the specified length.</p>\n<p>The <code>algorithm</code> is dependent on OpenSSL, examples are <code>'aes192'</code>, etc. On\nrecent OpenSSL releases, <code>openssl list -cipher-algorithms</code>\n(<code>openssl list-cipher-algorithms</code> for older versions of OpenSSL) will\ndisplay the available cipher algorithms.</p>\n<p>The <code>key</code> is the raw key used by the <code>algorithm</code> and <code>iv</code> is an\n<a href=\"https://en.wikipedia.org/wiki/Initialization_vector\">initialization vector</a>. Both arguments must be <code>'utf8'</code> encoded strings,\n<a href=\"buffer.html\">Buffers</a>, <code>TypedArray</code>, or <code>DataView</code>s. If the cipher does not need\nan initialization vector, <code>iv</code> may be <code>null</code>.</p>\n<p>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;\nit is important to remember that an attacker must not be able to predict ahead\nof time what a given IV will be.</p>" }, { "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 | Buffer | TypedArray | DataView}", "name": "prime", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`primeEncoding` {string} The [encoding][] of the `prime` string.", "name": "primeEncoding", "type": "string", "desc": "The [encoding][] of the `prime` string.", "optional": true }, { "textRaw": "`generator` {number | string | Buffer | TypedArray | DataView} **Default:** `2`", "name": "generator", "type": "number | string | Buffer | TypedArray | DataView", "default": "`2`", "optional": true }, { "textRaw": "`generatorEncoding` {string} The [encoding][] of the `generator` string.", "name": "generatorEncoding", "type": "string", "desc": "The [encoding][] of the `generator` string.", "optional": true } ] } ], "desc": "<p>Creates a <code>DiffieHellman</code> key exchange object using the supplied <code>prime</code> and an\noptional specific <code>generator</code>.</p>\n<p>The <code>generator</code> argument can be a number, string, or <a href=\"buffer.html\"><code>Buffer</code></a>. If\n<code>generator</code> is not specified, the value <code>2</code> is used.</p>\n<p>If <code>primeEncoding</code> is specified, <code>prime</code> is expected to be a string; otherwise\na <a href=\"buffer.html\"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code> is expected.</p>\n<p>If <code>generatorEncoding</code> is specified, <code>generator</code> is expected to be a string;\notherwise a number, <a href=\"buffer.html\"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code> is expected.</p>" }, { "textRaw": "crypto.createDiffieHellman(primeLength[, generator])", "type": "method", "name": "createDiffieHellman", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {DiffieHellman}", "name": "return", "type": "DiffieHellman" }, "params": [ { "textRaw": "`primeLength` {number}", "name": "primeLength", "type": "number" }, { "textRaw": "`generator` {number | string | Buffer | TypedArray | DataView} **Default:** `2`", "name": "generator", "type": "number | string | Buffer | TypedArray | DataView", "default": "`2`", "optional": true } ] } ], "desc": "<p>Creates a <code>DiffieHellman</code> key exchange object and generates a prime of\n<code>primeLength</code> bits using an optional specific numeric <code>generator</code>.\nIf <code>generator</code> is not specified, the value <code>2</code> is used.</p>" }, { "textRaw": "crypto.createECDH(curveName)", "type": "method", "name": "createECDH", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {ECDH}", "name": "return", "type": "ECDH" }, "params": [ { "textRaw": "`curveName` {string}", "name": "curveName", "type": "string" } ] } ], "desc": "<p>Creates an Elliptic Curve Diffie-Hellman (<code>ECDH</code>) key exchange object using a\npredefined curve specified by the <code>curveName</code> string. Use\n<a href=\"#crypto_crypto_getcurves\"><code>crypto.getCurves()</code></a> to obtain a list of available curve names. On recent\nOpenSSL releases, <code>openssl ecparam -list_curves</code> will also display the name\nand description of each available elliptic curve.</p>" }, { "textRaw": "crypto.createHash(algorithm[, options])", "type": "method", "name": "createHash", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Hash}", "name": "return", "type": "Hash" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]", "optional": true } ] } ], "desc": "<p>Creates and returns a <code>Hash</code> object that can be used to generate hash digests\nusing the given <code>algorithm</code>. Optional <code>options</code> argument controls stream\nbehavior.</p>\n<p>The <code>algorithm</code> is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are <code>'sha256'</code>, <code>'sha512'</code>, etc.\nOn recent releases of OpenSSL, <code>openssl list -digest-algorithms</code>\n(<code>openssl list-message-digest-algorithms</code> for older versions of OpenSSL) will\ndisplay the available digest algorithms.</p>\n<p>Example: generating the sha256 sum of a file</p>\n<pre><code class=\"language-js\">const filename = process.argv[2];\nconst crypto = require('crypto');\nconst fs = require('fs');\n\nconst hash = crypto.createHash('sha256');\n\nconst input = fs.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</code></pre>" }, { "textRaw": "crypto.createHmac(algorithm, key[, options])", "type": "method", "name": "createHmac", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Hmac}", "name": "return", "type": "Hmac" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`key` {string | Buffer | TypedArray | DataView}", "name": "key", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]", "optional": true } ] } ], "desc": "<p>Creates and returns an <code>Hmac</code> object that uses the given <code>algorithm</code> and <code>key</code>.\nOptional <code>options</code> argument controls stream behavior.</p>\n<p>The <code>algorithm</code> is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are <code>'sha256'</code>, <code>'sha512'</code>, etc.\nOn recent releases of OpenSSL, <code>openssl list -digest-algorithms</code>\n(<code>openssl list-message-digest-algorithms</code> for older versions of OpenSSL) will\ndisplay the available digest algorithms.</p>\n<p>The <code>key</code> is the HMAC key used to generate the cryptographic HMAC hash.</p>\n<p>Example: generating the sha256 HMAC of a file</p>\n<pre><code class=\"language-js\">const filename = process.argv[2];\nconst crypto = require('crypto');\nconst fs = require('fs');\n\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nconst input = fs.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</code></pre>" }, { "textRaw": "crypto.createSign(algorithm[, options])", "type": "method", "name": "createSign", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Sign}", "name": "return", "type": "Sign" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`options` {Object} [`stream.Writable` options][]", "name": "options", "type": "Object", "desc": "[`stream.Writable` options][]", "optional": true } ] } ], "desc": "<p>Creates and returns a <code>Sign</code> object that uses the given <code>algorithm</code>.\nUse <a href=\"#crypto_crypto_gethashes\"><code>crypto.getHashes()</code></a> to obtain an array of names of the available\nsigning algorithms. Optional <code>options</code> argument controls the\n<code>stream.Writable</code> behavior.</p>" }, { "textRaw": "crypto.createVerify(algorithm[, options])", "type": "method", "name": "createVerify", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Verify}", "name": "return", "type": "Verify" }, "params": [ { "textRaw": "`algorithm` {string}", "name": "algorithm", "type": "string" }, { "textRaw": "`options` {Object} [`stream.Writable` options][]", "name": "options", "type": "Object", "desc": "[`stream.Writable` options][]", "optional": true } ] } ], "desc": "<p>Creates and returns a <code>Verify</code> object that uses the given algorithm.\nUse <a href=\"#crypto_crypto_gethashes\"><code>crypto.getHashes()</code></a> to obtain an array of names of the available\nsigning algorithms. Optional <code>options</code> argument controls the\n<code>stream.Writable</code> behavior.</p>" }, { "textRaw": "crypto.generateKeyPair(type, options, callback)", "type": "method", "name": "generateKeyPair", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`type`: {string} Must be `'rsa'`, `'dsa'` or `'ec'`.", "name": "type", "type": "string", "desc": "Must be `'rsa'`, `'dsa'` or `'ec'`." }, { "textRaw": "`options`: {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`modulusLength`: {number} Key size in bits (RSA, DSA).", "name": "modulusLength", "type": "number", "desc": "Key size in bits (RSA, DSA)." }, { "textRaw": "`publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.", "name": "publicExponent", "type": "number", "default": "`0x10001`", "desc": "Public exponent (RSA)." }, { "textRaw": "`divisorLength`: {number} Size of `q` in bits (DSA).", "name": "divisorLength", "type": "number", "desc": "Size of `q` in bits (DSA)." }, { "textRaw": "`namedCurve`: {string} Name of the curve to use (EC).", "name": "namedCurve", "type": "string", "desc": "Name of the curve to use (EC)." }, { "textRaw": "`publicKeyEncoding`: {Object}", "name": "publicKeyEncoding", "type": "Object", "options": [ { "textRaw": "`type`: {string} Must be one of `'pkcs1'` (RSA only) or `'spki'`.", "name": "type", "type": "string", "desc": "Must be one of `'pkcs1'` (RSA only) or `'spki'`." }, { "textRaw": "`format`: {string} Must be `'pem'` or `'der'`.", "name": "format", "type": "string", "desc": "Must be `'pem'` or `'der'`." } ] }, { "textRaw": "`privateKeyEncoding`: {Object}", "name": "privateKeyEncoding", "type": "Object", "options": [ { "textRaw": "`type`: {string} Must be one of `'pkcs1'` (RSA only), `'pkcs8'` or `'sec1'` (EC only).", "name": "type", "type": "string", "desc": "Must be one of `'pkcs1'` (RSA only), `'pkcs8'` or `'sec1'` (EC only)." }, { "textRaw": "`format`: {string} Must be `'pem'` or `'der'`.", "name": "format", "type": "string", "desc": "Must be `'pem'` or `'der'`." }, { "textRaw": "`cipher`: {string} If specified, the private key will be encrypted with the given `cipher` and `passphrase` using PKCS#5 v2.0 password based encryption.", "name": "cipher", "type": "string", "desc": "If specified, the private key will be encrypted with the given `cipher` and `passphrase` using PKCS#5 v2.0 password based encryption." }, { "textRaw": "`passphrase`: {string} The passphrase to use for encryption, see `cipher`.", "name": "passphrase", "type": "string", "desc": "The passphrase to use for encryption, see `cipher`." } ] } ] }, { "textRaw": "`callback`: {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err`: {Error}", "name": "err", "type": "Error" }, { "textRaw": "`publicKey`: {string|Buffer}", "name": "publicKey", "type": "string|Buffer" }, { "textRaw": "`privateKey`: {string|Buffer}", "name": "privateKey", "type": "string|Buffer" } ] } ] } ], "desc": "<p>Generates a new asymmetric key pair of the given <code>type</code>. Only RSA, DSA and EC\nare currently supported.</p>\n<p>It is recommended to encode public keys as <code>'spki'</code> and private keys as\n<code>'pkcs8'</code> with encryption:</p>\n<pre><code class=\"language-js\">const { generateKeyPair } = require('crypto');\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</code></pre>\n<p>On completion, <code>callback</code> will be called with <code>err</code> set to <code>undefined</code> and\n<code>publicKey</code> / <code>privateKey</code> representing the generated key pair. When PEM\nencoding was selected, the result will be a string, otherwise it will be a\nbuffer containing the data encoded as DER. Note that Node.js itself does not\naccept DER, it is supported for interoperability with other libraries such as\nWebCrypto only.</p>\n<p>If this method is invoked as its <a href=\"util.html#util_util_promisify_original\"><code>util.promisify()</code></a>ed version, it returns\na <code>Promise</code> for an <code>Object</code> with <code>publicKey</code> and <code>privateKey</code> properties.</p>" }, { "textRaw": "crypto.generateKeyPairSync(type, options)", "type": "method", "name": "generateKeyPairSync", "meta": { "added": [ "v10.12.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Object}", "name": "return", "type": "Object", "options": [ { "textRaw": "`publicKey`: {string|Buffer}", "name": "publicKey", "type": "string|Buffer" }, { "textRaw": "`privateKey`: {string|Buffer}", "name": "privateKey", "type": "string|Buffer" } ] }, "params": [ { "textRaw": "`type`: {string} Must be `'rsa'`, `'dsa'` or `'ec'`.", "name": "type", "type": "string", "desc": "Must be `'rsa'`, `'dsa'` or `'ec'`." }, { "textRaw": "`options`: {Object}", "name": "options", "type": "Object", "options": [ { "textRaw": "`modulusLength`: {number} Key size in bits (RSA, DSA).", "name": "modulusLength", "type": "number", "desc": "Key size in bits (RSA, DSA)." }, { "textRaw": "`publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.", "name": "publicExponent", "type": "number", "default": "`0x10001`", "desc": "Public exponent (RSA)." }, { "textRaw": "`divisorLength`: {number} Size of `q` in bits (DSA).", "name": "divisorLength", "type": "number", "desc": "Size of `q` in bits (DSA)." }, { "textRaw": "`namedCurve`: {string} Name of the curve to use (EC).", "name": "namedCurve", "type": "string", "desc": "Name of the curve to use (EC)." }, { "textRaw": "`publicKeyEncoding`: {Object}", "name": "publicKeyEncoding", "type": "Object", "options": [ { "textRaw": "`type`: {string} Must be one of `'pkcs1'` (RSA only) or `'spki'`.", "name": "type", "type": "string", "desc": "Must be one of `'pkcs1'` (RSA only) or `'spki'`." }, { "textRaw": "`format`: {string} Must be `'pem'` or `'der'`.", "name": "format", "type": "string", "desc": "Must be `'pem'` or `'der'`." } ] }, { "textRaw": "`privateKeyEncoding`: {Object}", "name": "privateKeyEncoding", "type": "Object", "options": [ { "textRaw": "`type`: {string} Must be one of `'pkcs1'` (RSA only), `'pkcs8'` or `'sec1'` (EC only).", "name": "type", "type": "string", "desc": "Must be one of `'pkcs1'` (RSA only), `'pkcs8'` or `'sec1'` (EC only)." }, { "textRaw": "`format`: {string} Must be `'pem'` or `'der'`.", "name": "format", "type": "string", "desc": "Must be `'pem'` or `'der'`." }, { "textRaw": "`cipher`: {string} If specified, the private key will be encrypted with the given `cipher` and `passphrase` using PKCS#5 v2.0 password based encryption.", "name": "cipher", "type": "string", "desc": "If specified, the private key will be encrypted with the given `cipher` and `passphrase` using PKCS#5 v2.0 password based encryption." }, { "textRaw": "`passphrase`: {string} The passphrase to use for encryption, see `cipher`.", "name": "passphrase", "type": "string", "desc": "The passphrase to use for encryption, see `cipher`." } ] } ] } ] } ], "desc": "<p>Generates a new asymmetric key pair of the given <code>type</code>. Only RSA, DSA and EC\nare currently supported.</p>\n<p>It is recommended to encode public keys as <code>'spki'</code> and private keys as\n<code>'pkcs8'</code> with encryption:</p>\n<pre><code class=\"language-js\">const { generateKeyPairSync } = require('crypto');\nconst { publicKey, privateKey } = 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</code></pre>\n<p>The return value <code>{ publicKey, privateKey }</code> 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.</p>" }, { "textRaw": "crypto.getCiphers()", "type": "method", "name": "getCiphers", "meta": { "added": [ "v0.9.3" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {string[]} An array with the names of the supported cipher algorithms.", "name": "return", "type": "string[]", "desc": "An array with the names of the supported cipher algorithms." }, "params": [] } ], "desc": "<pre><code class=\"language-js\">const ciphers = crypto.getCiphers();\nconsole.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]\n</code></pre>" }, { "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": "<pre><code class=\"language-js\">const curves = crypto.getCurves();\nconsole.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n</code></pre>" }, { "textRaw": "crypto.getDiffieHellman(groupName)", "type": "method", "name": "getDiffieHellman", "meta": { "added": [ "v0.7.5" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {DiffieHellman}", "name": "return", "type": "DiffieHellman" }, "params": [ { "textRaw": "`groupName` {string}", "name": "groupName", "type": "string" } ] } ], "desc": "<p>Creates a predefined <code>DiffieHellman</code> key exchange object. The\nsupported groups are: <code>'modp1'</code>, <code>'modp2'</code>, <code>'modp5'</code> (defined in\n<a href=\"https://www.rfc-editor.org/rfc/rfc2412.txt\">RFC 2412</a>, but see <a href=\"#crypto_support_for_weak_or_compromised_algorithms\">Caveats</a>) and <code>'modp14'</code>, <code>'modp15'</code>,\n<code>'modp16'</code>, <code>'modp17'</code>, <code>'modp18'</code> (defined in <a href=\"https://www.rfc-editor.org/rfc/rfc3526.txt\">RFC 3526</a>). The\nreturned object mimics the interface of objects created by\n<a href=\"#crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding\"><code>crypto.createDiffieHellman()</code></a>, but will not allow changing\nthe keys (with <a href=\"#crypto_diffiehellman_setpublickey_publickey_encoding\"><code>diffieHellman.setPublicKey()</code></a>, 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.</p>\n<p>Example (obtaining a shared secret):</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst alice = crypto.getDiffieHellman('modp14');\nconst bob = crypto.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</code></pre>" }, { "textRaw": "crypto.getFips()", "type": "method", "name": "getFips", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `true` if and only if a FIPS compliant crypto provider is currently in use.", "name": "return", "type": "boolean", "desc": "`true` if and only if a FIPS compliant crypto provider is currently in use." }, "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'`.", "name": "return", "type": "string[]", "desc": "An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`." }, "params": [] } ], "desc": "<pre><code class=\"language-js\">const hashes = crypto.getHashes();\nconsole.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n</code></pre>" }, { "textRaw": "crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)", "type": "method", "name": "pbkdf2", "meta": { "added": [ "v0.5.5" ], "changes": [ { "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|Buffer|TypedArray|DataView}", "name": "password", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`salt` {string|Buffer|TypedArray|DataView}", "name": "salt", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`iterations` {number}", "name": "iterations", "type": "number" }, { "textRaw": "`keylen` {number}", "name": "keylen", "type": "number" }, { "textRaw": "`digest` {string}", "name": "digest", "type": "string" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`derivedKey` {Buffer}", "name": "derivedKey", "type": "Buffer" } ] } ] } ], "desc": "<p>Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)\nimplementation. A selected HMAC digest algorithm specified by <code>digest</code> is\napplied to derive a key of the requested byte length (<code>keylen</code>) from the\n<code>password</code>, <code>salt</code> and <code>iterations</code>.</p>\n<p>The supplied <code>callback</code> function is called with two arguments: <code>err</code> and\n<code>derivedKey</code>. If an error occurs while deriving the key, <code>err</code> will be set;\notherwise <code>err</code> will be <code>null</code>. By default, the successfully generated\n<code>derivedKey</code> will be passed to the callback as a <a href=\"buffer.html\"><code>Buffer</code></a>. An error will be\nthrown if any of the input arguments specify invalid values or types.</p>\n<p>If <code>digest</code> is <code>null</code>, <code>'sha1'</code> will be used. This behavior will be deprecated\nin a future version of Node.js.</p>\n<p>The <code>iterations</code> 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.</p>\n<p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See <a href=\"https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf\">NIST SP 800-132</a> for details.</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\ncrypto.pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'\n});\n</code></pre>\n<p>The <code>crypto.DEFAULT_ENCODING</code> property can be used to change the way the\n<code>derivedKey</code> is passed to the callback. This property, however, has been\ndeprecated and use should be avoided.</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\ncrypto.DEFAULT_ENCODING = 'hex';\ncrypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey); // '3745e48...aa39b34'\n});\n</code></pre>\n<p>An array of supported digest functions can be retrieved using\n<a href=\"#crypto_crypto_gethashes\"><code>crypto.getHashes()</code></a>.</p>\n<p>Note that this API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications, see the\n<a href=\"cli.html#cli_uv_threadpool_size_size\"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p>" }, { "textRaw": "crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)", "type": "method", "name": "pbkdf2Sync", "meta": { "added": [ "v0.9.3" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/4047", "description": "Calling this function without passing the `digest` parameter is deprecated now and will emit a warning." }, { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default encoding for `password` if it is a string changed from `binary` to `utf8`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer}", "name": "return", "type": "Buffer" }, "params": [ { "textRaw": "`password` {string|Buffer|TypedArray|DataView}", "name": "password", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`salt` {string|Buffer|TypedArray|DataView}", "name": "salt", "type": "string|Buffer|TypedArray|DataView" }, { "textRaw": "`iterations` {number}", "name": "iterations", "type": "number" }, { "textRaw": "`keylen` {number}", "name": "keylen", "type": "number" }, { "textRaw": "`digest` {string}", "name": "digest", "type": "string" } ] } ], "desc": "<p>Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)\nimplementation. A selected HMAC digest algorithm specified by <code>digest</code> is\napplied to derive a key of the requested byte length (<code>keylen</code>) from the\n<code>password</code>, <code>salt</code> and <code>iterations</code>.</p>\n<p>If an error occurs an <code>Error</code> will be thrown, otherwise the derived key will be\nreturned as a <a href=\"buffer.html\"><code>Buffer</code></a>.</p>\n<p>If <code>digest</code> is <code>null</code>, <code>'sha1'</code> will be used. This behavior will be deprecated\nin a future version of Node.js.</p>\n<p>The <code>iterations</code> 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.</p>\n<p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See <a href=\"https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf\">NIST SP 800-132</a> for details.</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');\nconsole.log(key.toString('hex')); // '3745e48...08d59ae'\n</code></pre>\n<p>The <code>crypto.DEFAULT_ENCODING</code> property may be used to change the way the\n<code>derivedKey</code> is returned. This property, however, is deprecated and use\nshould be avoided.</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\ncrypto.DEFAULT_ENCODING = 'hex';\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');\nconsole.log(key); // '3745e48...aa39b34'\n</code></pre>\n<p>An array of supported digest functions can be retrieved using\n<a href=\"#crypto_crypto_gethashes\"><code>crypto.getHashes()</code></a>.</p>" }, { "textRaw": "crypto.privateDecrypt(privateKey, buffer)", "type": "method", "name": "privateDecrypt", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} A new `Buffer` with the decrypted content.", "name": "return", "type": "Buffer", "desc": "A new `Buffer` with the decrypted content." }, "params": [ { "textRaw": "`privateKey` {Object | string}", "name": "privateKey", "type": "Object | string", "options": [ { "textRaw": "`key` {string} A PEM encoded private key.", "name": "key", "type": "string", "desc": "A PEM encoded private key." }, { "textRaw": "`passphrase` {string} An optional passphrase for the private key.", "name": "passphrase", "type": "string", "desc": "An optional passphrase for the private key." }, { "textRaw": "`padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`.", "name": "padding", "type": "crypto.constants", "desc": "An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`." } ] }, { "textRaw": "`buffer` {Buffer | TypedArray | DataView}", "name": "buffer", "type": "Buffer | TypedArray | DataView" } ] } ], "desc": "<p>Decrypts <code>buffer</code> with <code>privateKey</code>. <code>buffer</code> was previously encrypted using\nthe corresponding public key, for example using <a href=\"#crypto_crypto_publicencrypt_key_buffer\"><code>crypto.publicEncrypt()</code></a>.</p>\n<p><code>privateKey</code> can be an object or a string. If <code>privateKey</code> is a string, it is\ntreated as the key with no passphrase and will use <code>RSA_PKCS1_OAEP_PADDING</code>.</p>" }, { "textRaw": "crypto.privateEncrypt(privateKey, buffer)", "type": "method", "name": "privateEncrypt", "meta": { "added": [ "v1.1.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} A new `Buffer` with the encrypted content.", "name": "return", "type": "Buffer", "desc": "A new `Buffer` with the encrypted content." }, "params": [ { "textRaw": "`privateKey` {Object | string}", "name": "privateKey", "type": "Object | string", "options": [ { "textRaw": "`key` {string} A PEM encoded private key.", "name": "key", "type": "string", "desc": "A PEM encoded private key." }, { "textRaw": "`passphrase` {string} An optional passphrase for the private key.", "name": "passphrase", "type": "string", "desc": "An optional passphrase for the private key." }, { "textRaw": "`padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or `crypto.constants.RSA_PKCS1_PADDING`.", "name": "padding", "type": "crypto.constants", "desc": "An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or `crypto.constants.RSA_PKCS1_PADDING`." } ] }, { "textRaw": "`buffer` {Buffer | TypedArray | DataView}", "name": "buffer", "type": "Buffer | TypedArray | DataView" } ] } ], "desc": "<p>Encrypts <code>buffer</code> with <code>privateKey</code>. The returned data can be decrypted using\nthe corresponding public key, for example using <a href=\"#crypto_crypto_publicdecrypt_key_buffer\"><code>crypto.publicDecrypt()</code></a>.</p>\n<p><code>privateKey</code> can be an object or a string. If <code>privateKey</code> is a string, it is\ntreated as the key with no passphrase and will use <code>RSA_PKCS1_PADDING</code>.</p>" }, { "textRaw": "crypto.publicDecrypt(key, buffer)", "type": "method", "name": "publicDecrypt", "meta": { "added": [ "v1.1.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} A new `Buffer` with the decrypted content.", "name": "return", "type": "Buffer", "desc": "A new `Buffer` with the decrypted content." }, "params": [ { "textRaw": "`key` {Object | string}", "name": "key", "type": "Object | string", "options": [ { "textRaw": "`key` {string} A PEM encoded public or private key.", "name": "key", "type": "string", "desc": "A PEM encoded public or private key." }, { "textRaw": "`passphrase` {string} An optional passphrase for the private key.", "name": "passphrase", "type": "string", "desc": "An optional passphrase for the private key." }, { "textRaw": "`padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or `crypto.constants.RSA_PKCS1_PADDING`.", "name": "padding", "type": "crypto.constants", "desc": "An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or `crypto.constants.RSA_PKCS1_PADDING`." } ] }, { "textRaw": "`buffer` {Buffer | TypedArray | DataView}", "name": "buffer", "type": "Buffer | TypedArray | DataView" } ] } ], "desc": "<p>Decrypts <code>buffer</code> with <code>key</code>.<code>buffer</code> was previously encrypted using\nthe corresponding private key, for example using <a href=\"#crypto_crypto_privateencrypt_privatekey_buffer\"><code>crypto.privateEncrypt()</code></a>.</p>\n<p><code>key</code> can be an object or a string. If <code>key</code> is a string, it is treated as\nthe key with no passphrase and will use <code>RSA_PKCS1_PADDING</code>.</p>\n<p>Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.</p>" }, { "textRaw": "crypto.publicEncrypt(key, buffer)", "type": "method", "name": "publicEncrypt", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} A new `Buffer` with the encrypted content.", "name": "return", "type": "Buffer", "desc": "A new `Buffer` with the encrypted content." }, "params": [ { "textRaw": "`key` {Object | string}", "name": "key", "type": "Object | string", "options": [ { "textRaw": "`key` {string} A PEM encoded public or private key.", "name": "key", "type": "string", "desc": "A PEM encoded public or private key." }, { "textRaw": "`passphrase` {string} An optional passphrase for the private key.", "name": "passphrase", "type": "string", "desc": "An optional passphrase for the private key." }, { "textRaw": "`padding` {crypto.constants} An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`.", "name": "padding", "type": "crypto.constants", "desc": "An optional padding value defined in `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`, `crypto.constants.RSA_PKCS1_PADDING`, or `crypto.constants.RSA_PKCS1_OAEP_PADDING`." } ] }, { "textRaw": "`buffer` {Buffer | TypedArray | DataView}", "name": "buffer", "type": "Buffer | TypedArray | DataView" } ] } ], "desc": "<p>Encrypts the content of <code>buffer</code> with <code>key</code> and returns a new\n<a href=\"buffer.html\"><code>Buffer</code></a> with encrypted content. The returned data can be decrypted using\nthe corresponding private key, for example using <a href=\"#crypto_crypto_privatedecrypt_privatekey_buffer\"><code>crypto.privateDecrypt()</code></a>.</p>\n<p><code>key</code> can be an object or a string. If <code>key</code> is a string, it is treated as\nthe key with no passphrase and will use <code>RSA_PKCS1_OAEP_PADDING</code>.</p>\n<p>Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.</p>" }, { "textRaw": "crypto.randomBytes(size[, callback])", "type": "method", "name": "randomBytes", "meta": { "added": [ "v0.5.8" ], "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/16454", "description": "Passing `null` as the `callback` argument now throws `ERR_INVALID_CALLBACK`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} if the `callback` function is not provided.", "name": "return", "type": "Buffer", "desc": "if the `callback` function is not provided." }, "params": [ { "textRaw": "`size` {number}", "name": "size", "type": "number" }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`buf` {Buffer}", "name": "buf", "type": "Buffer" } ], "optional": true } ] } ], "desc": "<p>Generates cryptographically strong pseudo-random data. The <code>size</code> argument\nis a number indicating the number of bytes to generate.</p>\n<p>If a <code>callback</code> function is provided, the bytes are generated asynchronously\nand the <code>callback</code> function is invoked with two arguments: <code>err</code> and <code>buf</code>.\nIf an error occurs, <code>err</code> will be an <code>Error</code> object; otherwise it is <code>null</code>. The\n<code>buf</code> argument is a <a href=\"buffer.html\"><code>Buffer</code></a> containing the generated bytes.</p>\n<pre><code class=\"language-js\">// Asynchronous\nconst crypto = require('crypto');\ncrypto.randomBytes(256, (err, buf) => {\n if (err) throw err;\n console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);\n});\n</code></pre>\n<p>If the <code>callback</code> function is not provided, the random bytes are generated\nsynchronously and returned as a <a href=\"buffer.html\"><code>Buffer</code></a>. An error will be thrown if\nthere is a problem generating the bytes.</p>\n<pre><code class=\"language-js\">// Synchronous\nconst buf = crypto.randomBytes(256);\nconsole.log(\n `${buf.length} bytes of random data: ${buf.toString('hex')}`);\n</code></pre>\n<p>The <code>crypto.randomBytes()</code> 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.</p>\n<p>Note that this API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications, see the\n<a href=\"cli.html#cli_uv_threadpool_size_size\"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p>\n<p>The asynchronous version of <code>crypto.randomBytes()</code> is carried out in a single\nthreadpool request. To minimize threadpool task length variation, partition\nlarge <code>randomBytes</code> requests when doing so as part of fulfilling a client\nrequest.</p>" }, { "textRaw": "crypto.randomFillSync(buffer[, offset][, size])", "type": "method", "name": "randomFillSync", "meta": { "added": [ "v7.10.0", "v6.13.0" ], "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15231", "description": "The `buffer` argument may be any `TypedArray` or `DataView`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer|TypedArray|DataView} The object passed as `buffer` argument.", "name": "return", "type": "Buffer|TypedArray|DataView", "desc": "The object passed as `buffer` argument." }, "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView} Must be supplied.", "name": "buffer", "type": "Buffer|TypedArray|DataView", "desc": "Must be supplied." }, { "textRaw": "`offset` {number} **Default:** `0`", "name": "offset", "type": "number", "default": "`0`", "optional": true }, { "textRaw": "`size` {number} **Default:** `buffer.length - offset`", "name": "size", "type": "number", "default": "`buffer.length - offset`", "optional": true } ] } ], "desc": "<p>Synchronous version of <a href=\"#crypto_crypto_randomfill_buffer_offset_size_callback\"><code>crypto.randomFill()</code></a>.</p>\n<pre><code class=\"language-js\">const buf = Buffer.alloc(10);\nconsole.log(crypto.randomFillSync(buf).toString('hex'));\n\ncrypto.randomFillSync(buf, 5);\nconsole.log(buf.toString('hex'));\n\n// The above is equivalent to the following:\ncrypto.randomFillSync(buf, 5, 5);\nconsole.log(buf.toString('hex'));\n</code></pre>\n<p>Any <code>TypedArray</code> or <code>DataView</code> instance may be passed as <code>buffer</code>.</p>\n<pre><code class=\"language-js\">const a = new Uint32Array(10);\nconsole.log(Buffer.from(crypto.randomFillSync(a).buffer,\n a.byteOffset, a.byteLength).toString('hex'));\n\nconst b = new Float64Array(10);\nconsole.log(Buffer.from(crypto.randomFillSync(b).buffer,\n b.byteOffset, b.byteLength).toString('hex'));\n\nconst c = new DataView(new ArrayBuffer(10));\nconsole.log(Buffer.from(crypto.randomFillSync(c).buffer,\n c.byteOffset, c.byteLength).toString('hex'));\n</code></pre>" }, { "textRaw": "crypto.randomFill(buffer[, offset][, size], callback)", "type": "method", "name": "randomFill", "meta": { "added": [ "v7.10.0", "v6.13.0" ], "changes": [ { "version": "v9.0.0", "pr-url": "https://github.com/nodejs/node/pull/15231", "description": "The `buffer` argument may be any `TypedArray` or `DataView`." } ] }, "signatures": [ { "params": [ { "textRaw": "`buffer` {Buffer|TypedArray|DataView} Must be supplied.", "name": "buffer", "type": "Buffer|TypedArray|DataView", "desc": "Must be supplied." }, { "textRaw": "`offset` {number} **Default:** `0`", "name": "offset", "type": "number", "default": "`0`", "optional": true }, { "textRaw": "`size` {number} **Default:** `buffer.length - offset`", "name": "size", "type": "number", "default": "`buffer.length - offset`", "optional": true }, { "textRaw": "`callback` {Function} `function(err, buf) {}`.", "name": "callback", "type": "Function", "desc": "`function(err, buf) {}`." } ] } ], "desc": "<p>This function is similar to <a href=\"#crypto_crypto_randombytes_size_callback\"><code>crypto.randomBytes()</code></a> but requires the first\nargument to be a <a href=\"buffer.html\"><code>Buffer</code></a> that will be filled. It also\nrequires that a callback is passed in.</p>\n<p>If the <code>callback</code> function is not provided, an error will be thrown.</p>\n<pre><code class=\"language-js\">const buf = Buffer.alloc(10);\ncrypto.randomFill(buf, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n\ncrypto.randomFill(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:\ncrypto.randomFill(buf, 5, 5, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n</code></pre>\n<p>Any <code>TypedArray</code> or <code>DataView</code> instance may be passed as <code>buffer</code>.</p>\n<pre><code class=\"language-js\">const a = new Uint32Array(10);\ncrypto.randomFill(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 Float64Array(10);\ncrypto.randomFill(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 DataView(new ArrayBuffer(10));\ncrypto.randomFill(c, (err, buf) => {\n if (err) throw err;\n console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n .toString('hex'));\n});\n</code></pre>\n<p>Note that this API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications, see the\n<a href=\"cli.html#cli_uv_threadpool_size_size\"><code>UV_THREADPOOL_SIZE</code></a> documentation for more information.</p>\n<p>The asynchronous version of <code>crypto.randomFill()</code> is carried out in a single\nthreadpool request. To minimize threadpool task length variation, partition\nlarge <code>randomFill</code> requests when doing so as part of fulfilling a client\nrequest.</p>" }, { "textRaw": "crypto.scrypt(password, salt, keylen[, options], callback)", "type": "method", "name": "scrypt", "meta": { "added": [ "v10.5.0" ], "changes": [ { "version": "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|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", "name": "cost", "type": "number", "desc": "CPU/memory cost parameter. Must be a power of two greater" }, { "textRaw": "`N` {number} CPU/memory cost parameter. Must be a power of two greater than one. **Default:** `16384`.", "name": "N", "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`." } ], "optional": true }, { "textRaw": "`callback` {Function}", "name": "callback", "type": "Function", "options": [ { "textRaw": "`err` {Error}", "name": "err", "type": "Error" }, { "textRaw": "`derivedKey` {Buffer}", "name": "derivedKey", "type": "Buffer" } ] } ] } ], "desc": "<p>Provides an asynchronous <a href=\"https://en.wikipedia.org/wiki/Scrypt\">scrypt</a> 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.</p>\n<p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See <a href=\"https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf\">NIST SP 800-132</a> for details.</p>\n<p>The <code>callback</code> function is called with two arguments: <code>err</code> and <code>derivedKey</code>.\n<code>err</code> is an exception object when key derivation fails, otherwise <code>err</code> is\n<code>null</code>. <code>derivedKey</code> is passed to the callback as a <a href=\"buffer.html\"><code>Buffer</code></a>.</p>\n<p>An exception is thrown when any of the input arguments specify invalid values\nor types.</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\n// Using the factory defaults.\ncrypto.scrypt('secret', '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.\ncrypto.scrypt('secret', 'salt', 64, { N: 1024 }, (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'\n});\n</code></pre>" }, { "textRaw": "crypto.scryptSync(password, salt, keylen[, options])", "type": "method", "name": "scryptSync", "meta": { "added": [ "v10.5.0" ], "changes": [ { "version": "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", "name": "cost", "type": "number", "desc": "CPU/memory cost parameter. Must be a power of two greater" }, { "textRaw": "`N` {number} CPU/memory cost parameter. Must be a power of two greater than one. **Default:** `16384`.", "name": "N", "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`." } ], "optional": true } ] } ], "desc": "<p>Provides a synchronous <a href=\"https://en.wikipedia.org/wiki/Scrypt\">scrypt</a> 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.</p>\n<p>The <code>salt</code> should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See <a href=\"https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf\">NIST SP 800-132</a> for details.</p>\n<p>An exception is thrown when key derivation fails, otherwise the derived key is\nreturned as a <a href=\"buffer.html\"><code>Buffer</code></a>.</p>\n<p>An exception is thrown when any of the input arguments specify invalid values\nor types.</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\n// Using the factory defaults.\nconst key1 = crypto.scryptSync('secret', 'salt', 64);\nconsole.log(key1.toString('hex')); // '3745e48...08d59ae'\n// Using a custom N parameter. Must be a power of two.\nconst key2 = crypto.scryptSync('secret', 'salt', 64, { N: 1024 });\nconsole.log(key2.toString('hex')); // '3745e48...aa39b34'\n</code></pre>" }, { "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`", "optional": true } ] } ], "desc": "<p>Load and set the <code>engine</code> for some or all OpenSSL functions (selected by flags).</p>\n<p><code>engine</code> could be either an id or a path to the engine's shared library.</p>\n<p>The optional <code>flags</code> argument uses <code>ENGINE_METHOD_ALL</code> by default. The <code>flags</code>\nis a bit field taking one of or a mix of the following flags (defined in\n<code>crypto.constants</code>):</p>\n<ul>\n<li><code>crypto.constants.ENGINE_METHOD_RSA</code></li>\n<li><code>crypto.constants.ENGINE_METHOD_DSA</code></li>\n<li><code>crypto.constants.ENGINE_METHOD_DH</code></li>\n<li><code>crypto.constants.ENGINE_METHOD_RAND</code></li>\n<li><code>crypto.constants.ENGINE_METHOD_EC</code></li>\n<li><code>crypto.constants.ENGINE_METHOD_CIPHERS</code></li>\n<li><code>crypto.constants.ENGINE_METHOD_DIGESTS</code></li>\n<li><code>crypto.constants.ENGINE_METHOD_PKEY_METHS</code></li>\n<li><code>crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS</code></li>\n<li><code>crypto.constants.ENGINE_METHOD_ALL</code></li>\n<li><code>crypto.constants.ENGINE_METHOD_NONE</code></li>\n</ul>\n<p>The flags below are deprecated in OpenSSL-1.1.0.</p>\n<ul>\n<li><code>crypto.constants.ENGINE_METHOD_ECDH</code></li>\n<li><code>crypto.constants.ENGINE_METHOD_ECDSA</code></li>\n<li><code>crypto.constants.ENGINE_METHOD_STORE</code></li>\n</ul>" }, { "textRaw": "crypto.setFips(bool)", "type": "method", "name": "setFips", "meta": { "added": [ "v10.0.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`bool` {boolean} `true` to enable FIPS mode.", "name": "bool", "type": "boolean", "desc": "`true` to enable FIPS mode." } ] } ], "desc": "<p>Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.\nThrows an error if FIPS mode is not available.</p>" }, { "textRaw": "crypto.timingSafeEqual(a, b)", "type": "method", "name": "timingSafeEqual", "meta": { "added": [ "v6.6.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean}", "name": "return", "type": "boolean" }, "params": [ { "textRaw": "`a` {Buffer | TypedArray | DataView}", "name": "a", "type": "Buffer | TypedArray | DataView" }, { "textRaw": "`b` {Buffer | TypedArray | DataView}", "name": "b", "type": "Buffer | TypedArray | DataView" } ] } ], "desc": "<p>This function is based on a constant-time algorithm.\nReturns true if <code>a</code> is equal to <code>b</code>, without leaking timing information that\nwould allow an attacker to guess one of the values. This is suitable for\ncomparing HMAC digests or secret values like authentication cookies or\n<a href=\"https://www.w3.org/TR/capability-urls/\">capability urls</a>.</p>\n<p><code>a</code> and <code>b</code> must both be <code>Buffer</code>s, <code>TypedArray</code>s, or <code>DataView</code>s, and they\nmust have the same length.</p>\n<p>Use of <code>crypto.timingSafeEqual</code> does not guarantee that the <em>surrounding</em> code\nis timing-safe. Care should be taken to ensure that the surrounding code does\nnot introduce timing vulnerabilities.</p>" } ], "type": "module", "displayName": "`crypto` module methods and properties" }, { "textRaw": "Notes", "name": "notes", "modules": [ { "textRaw": "Legacy Streams API (pre Node.js v0.10)", "name": "legacy_streams_api_(pre_node.js_v0.10)", "desc": "<p>The Crypto module was added to Node.js before there was the concept of a\nunified Stream API, and before there were <a href=\"buffer.html\"><code>Buffer</code></a> objects for handling\nbinary data. As such, the many of the <code>crypto</code> defined classes have methods not\ntypically found on other Node.js classes that implement the <a href=\"stream.html\">streams</a>\nAPI (e.g. <code>update()</code>, <code>final()</code>, or <code>digest()</code>). Also, many methods accepted\nand returned <code>'latin1'</code> encoded strings by default rather than <code>Buffer</code>s. This\ndefault was changed after Node.js v0.8 to use <a href=\"buffer.html\"><code>Buffer</code></a> objects by default\ninstead.</p>", "type": "module", "displayName": "Legacy Streams API (pre Node.js v0.10)" }, { "textRaw": "Recent ECDH Changes", "name": "recent_ecdh_changes", "desc": "<p>Usage of <code>ECDH</code> with non-dynamically generated key pairs has been simplified.\nNow, <a href=\"#crypto_ecdh_setprivatekey_privatekey_encoding\"><code>ecdh.setPrivateKey()</code></a> can be called with a preselected private key\nand the associated public point (key) will be computed and stored in the object.\nThis allows code to only store and provide the private part of the EC key pair.\n<a href=\"#crypto_ecdh_setprivatekey_privatekey_encoding\"><code>ecdh.setPrivateKey()</code></a> now also validates that the private key is valid for\nthe selected curve.</p>\n<p>The <a href=\"#crypto_ecdh_setpublickey_publickey_encoding\"><code>ecdh.setPublicKey()</code></a> method is now deprecated as its inclusion in the\nAPI is not useful. Either a previously stored private key should be set, which\nautomatically generates the associated public key, or <a href=\"#crypto_ecdh_generatekeys_encoding_format\"><code>ecdh.generateKeys()</code></a>\nshould be called. The main drawback of using <a href=\"#crypto_ecdh_setpublickey_publickey_encoding\"><code>ecdh.setPublicKey()</code></a> is that\nit can be used to put the ECDH key pair into an inconsistent state.</p>", "type": "module", "displayName": "Recent ECDH Changes" }, { "textRaw": "Support for weak or compromised algorithms", "name": "support_for_weak_or_compromised_algorithms", "desc": "<p>The <code>crypto</code> module still supports some algorithms which are already\ncompromised and are not currently recommended for use. The API also allows\nthe use of ciphers and hashes with a small key size that are considered to be\ntoo weak for safe use.</p>\n<p>Users should take full responsibility for selecting the crypto\nalgorithm and key size according to their security requirements.</p>\n<p>Based on the recommendations of <a href=\"https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf\">NIST SP 800-131A</a>:</p>\n<ul>\n<li>MD5 and SHA-1 are no longer acceptable where collision resistance is\nrequired such as digital signatures.</li>\n<li>The key used with RSA, DSA, and DH algorithms is recommended to have\nat least 2048 bits and that of the curve of ECDSA and ECDH at least\n224 bits, to be safe to use for several years.</li>\n<li>The DH groups of <code>modp1</code>, <code>modp2</code> and <code>modp5</code> have a key size\nsmaller than 2048 bits and are not recommended.</li>\n</ul>\n<p>See the reference for other recommendations and details.</p>", "type": "module", "displayName": "Support for weak or compromised algorithms" }, { "textRaw": "CCM mode", "name": "ccm_mode", "desc": "<p>CCM is one of the supported <a href=\"https://en.wikipedia.org/wiki/Authenticated_encryption\">AEAD algorithms</a>. Applications which use this\nmode must adhere to certain restrictions when using the cipher API:</p>\n<ul>\n<li>The authentication tag length must be specified during cipher creation by\nsetting the <code>authTagLength</code> option and must be one of 4, 6, 8, 10, 12, 14 or\n16 bytes.</li>\n<li>The length of the initialization vector (nonce) <code>N</code> must be between 7 and 13\nbytes (<code>7 ≤ N ≤ 13</code>).</li>\n<li>The length of the plaintext is limited to <code>2 ** (8 * (15 - N))</code> bytes.</li>\n<li>When decrypting, the authentication tag must be set via <code>setAuthTag()</code> before\nspecifying additional authenticated data or calling <code>update()</code>.\nOtherwise, decryption will fail and <code>final()</code> will throw an error in\ncompliance with section 2.6 of <a href=\"https://www.rfc-editor.org/rfc/rfc3610.txt\">RFC 3610</a>.</li>\n<li>Using stream methods such as <code>write(data)</code>, <code>end(data)</code> or <code>pipe()</code> in CCM\nmode might fail as CCM cannot handle more than one chunk of data per instance.</li>\n<li>When passing additional authenticated data (AAD), the length of the actual\nmessage in bytes must be passed to <code>setAAD()</code> via the <code>plaintextLength</code>\noption. This is not necessary if no AAD is used.</li>\n<li>As CCM processes the whole message at once, <code>update()</code> can only be called\nonce.</li>\n<li>Even though calling <code>update()</code> is sufficient to encrypt/decrypt the message,\napplications <em>must</em> call <code>final()</code> to compute or verify the\nauthentication tag.</li>\n</ul>\n<pre><code class=\"language-js\">const crypto = require('crypto');\n\nconst key = 'keykeykeykeykeykeykeykey';\nconst nonce = crypto.randomBytes(12);\n\nconst aad = Buffer.from('0123456789', 'hex');\n\nconst cipher = crypto.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 = crypto.createDecipheriv('aes-192-ccm', key, nonce, {\n authTagLength: 16\n});\ndecipher.setAuthTag(tag);\ndecipher.setAAD(aad, {\n plaintextLength: ciphertext.length\n});\nconst receivedPlaintext = decipher.update(ciphertext, null, 'utf8');\n\ntry {\n decipher.final();\n} catch (err) {\n console.error('Authentication failed!');\n}\n\nconsole.log(receivedPlaintext);\n</code></pre>", "type": "module", "displayName": "CCM mode" } ], "type": "module", "displayName": "Notes" }, { "textRaw": "Crypto Constants", "name": "crypto_constants", "desc": "<p>The following constants exported by <code>crypto.constants</code> apply to various uses of\nthe <code>crypto</code>, <code>tls</code>, and <code>https</code> modules and are generally specific to OpenSSL.</p>", "modules": [ { "textRaw": "OpenSSL Options", "name": "openssl_options", "desc": "<!--lint disable maximum-line-length-->\n<table>\n <tr>\n <th>Constant</th>\n <th>Description</th>\n </tr>\n <tr>\n <td><code>SSL_OP_ALL</code></td>\n <td>Applies multiple bug workarounds within OpenSSL. See\n <a href=\"https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html\">https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html</a>\n for detail.</td>\n </tr>\n <tr>\n <td><code>SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION</code></td>\n <td>Allows legacy insecure renegotiation between OpenSSL and unpatched\n clients or servers. See\n <a href=\"https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html\">https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html</a>.</td>\n </tr>\n <tr>\n <td><code>SSL_OP_CIPHER_SERVER_PREFERENCE</code></td>\n <td>Attempts to use the server's preferences instead of the client's when\n selecting a cipher. Behavior depends on protocol version. See\n <a href=\"https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html\">https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html</a>.</td>\n </tr>\n <tr>\n <td><code>SSL_OP_CISCO_ANYCONNECT</code></td>\n <td>Instructs OpenSSL to use Cisco's \"speshul\" version of DTLS_BAD_VER.</td>\n </tr>\n <tr>\n <td><code>SSL_OP_COOKIE_EXCHANGE</code></td>\n <td>Instructs OpenSSL to turn on cookie exchange.</td>\n </tr>\n <tr>\n <td><code>SSL_OP_CRYPTOPRO_TLSEXT_BUG</code></td>\n <td>Instructs OpenSSL to add server-hello extension from an early version\n of the cryptopro draft.</td>\n </tr>\n <tr>\n <td><code>SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS</code></td>\n <td>Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability\n workaround added in OpenSSL 0.9.6d.</td>\n </tr>\n <tr>\n <td><code>SSL_OP_EPHEMERAL_RSA</code></td>\n <td>Instructs OpenSSL to always use the tmp_rsa key when performing RSA\n operations.</td>\n </tr>\n <tr>\n <td><code>SSL_OP_LEGACY_SERVER_CONNECT</code></td>\n <td>Allows initial connection to servers that do not support RI.</td>\n </tr>\n <tr>\n <td><code>SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>SSL_OP_MICROSOFT_SESS_ID_BUG</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>SSL_OP_MSIE_SSLV2_RSA_PADDING</code></td>\n <td>Instructs OpenSSL to disable the workaround for a man-in-the-middle\n protocol-version vulnerability in the SSL 2.0 server implementation.</td>\n </tr>\n <tr>\n <td><code>SSL_OP_NETSCAPE_CA_DN_BUG</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>SSL_OP_NETSCAPE_CHALLENGE_BUG</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>SSL_OP_NO_COMPRESSION</code></td>\n <td>Instructs OpenSSL to disable support for SSL/TLS compression.</td>\n </tr>\n <tr>\n <td><code>SSL_OP_NO_QUERY_MTU</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION</code></td>\n <td>Instructs OpenSSL to always start a new session when performing\n renegotiation.</td>\n </tr>\n <tr>\n <td><code>SSL_OP_NO_SSLv2</code></td>\n <td>Instructs OpenSSL to turn off SSL v2</td>\n </tr>\n <tr>\n <td><code>SSL_OP_NO_SSLv3</code></td>\n <td>Instructs OpenSSL to turn off SSL v3</td>\n </tr>\n <tr>\n <td><code>SSL_OP_NO_TICKET</code></td>\n <td>Instructs OpenSSL to disable use of RFC4507bis tickets.</td>\n </tr>\n <tr>\n <td><code>SSL_OP_NO_TLSv1</code></td>\n <td>Instructs OpenSSL to turn off TLS v1</td>\n </tr>\n <tr>\n <td><code>SSL_OP_NO_TLSv1_1</code></td>\n <td>Instructs OpenSSL to turn off TLS v1.1</td>\n </tr>\n <tr>\n <td><code>SSL_OP_NO_TLSv1_2</code></td>\n <td>Instructs OpenSSL to turn off TLS v1.2</td>\n </tr>\n <td><code>SSL_OP_PKCS1_CHECK_1</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>SSL_OP_PKCS1_CHECK_2</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>SSL_OP_SINGLE_DH_USE</code></td>\n <td>Instructs OpenSSL to always create a new key when using\n temporary/ephemeral DH parameters.</td>\n </tr>\n <tr>\n <td><code>SSL_OP_SINGLE_ECDH_USE</code></td>\n <td>Instructs OpenSSL to always create a new key when using\n temporary/ephemeral ECDH parameters.</td>\n </tr>\n <td><code>SSL_OP_SSLEAY_080_CLIENT_DH_BUG</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>SSL_OP_TLS_BLOCK_PADDING_BUG</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>SSL_OP_TLS_D5_BUG</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>SSL_OP_TLS_ROLLBACK_BUG</code></td>\n <td>Instructs OpenSSL to disable version rollback attack detection.</td>\n </tr>\n</table>", "type": "module", "displayName": "OpenSSL Options" }, { "textRaw": "OpenSSL Engine Constants", "name": "openssl_engine_constants", "desc": "<!--lint enable maximum-line-length remark-lint-->\n<table>\n <tr>\n <th>Constant</th>\n <th>Description</th>\n </tr>\n <tr>\n <td><code>ENGINE_METHOD_RSA</code></td>\n <td>Limit engine usage to RSA</td>\n </tr>\n <tr>\n <td><code>ENGINE_METHOD_DSA</code></td>\n <td>Limit engine usage to DSA</td>\n </tr>\n <tr>\n <td><code>ENGINE_METHOD_DH</code></td>\n <td>Limit engine usage to DH</td>\n </tr>\n <tr>\n <td><code>ENGINE_METHOD_RAND</code></td>\n <td>Limit engine usage to RAND</td>\n </tr>\n <tr>\n <td><code>ENGINE_METHOD_EC</code></td>\n <td>Limit engine usage to EC</td>\n </tr>\n <tr>\n <td><code>ENGINE_METHOD_CIPHERS</code></td>\n <td>Limit engine usage to CIPHERS</td>\n </tr>\n <tr>\n <td><code>ENGINE_METHOD_DIGESTS</code></td>\n <td>Limit engine usage to DIGESTS</td>\n </tr>\n <tr>\n <td><code>ENGINE_METHOD_PKEY_METHS</code></td>\n <td>Limit engine usage to PKEY_METHDS</td>\n </tr>\n <tr>\n <td><code>ENGINE_METHOD_PKEY_ASN1_METHS</code></td>\n <td>Limit engine usage to PKEY_ASN1_METHS</td>\n </tr>\n <tr>\n <td><code>ENGINE_METHOD_ALL</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>ENGINE_METHOD_NONE</code></td>\n <td></td>\n </tr>\n</table>", "type": "module", "displayName": "OpenSSL Engine Constants" }, { "textRaw": "Other OpenSSL Constants", "name": "other_openssl_constants", "desc": "<table>\n <tr>\n <th>Constant</th>\n <th>Description</th>\n </tr>\n <tr>\n <td><code>DH_CHECK_P_NOT_SAFE_PRIME</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>DH_CHECK_P_NOT_PRIME</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>DH_UNABLE_TO_CHECK_GENERATOR</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>DH_NOT_SUITABLE_GENERATOR</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>ALPN_ENABLED</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>RSA_PKCS1_PADDING</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>RSA_SSLV23_PADDING</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>RSA_NO_PADDING</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>RSA_PKCS1_OAEP_PADDING</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>RSA_X931_PADDING</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>RSA_PKCS1_PSS_PADDING</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>RSA_PSS_SALTLEN_DIGEST</code></td>\n <td>Sets the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to the\n digest size when signing or verifying.</td>\n </tr>\n <tr>\n <td><code>RSA_PSS_SALTLEN_MAX_SIGN</code></td>\n <td>Sets the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to the\n maximum permissible value when signing data.</td>\n </tr>\n <tr>\n <td><code>RSA_PSS_SALTLEN_AUTO</code></td>\n <td>Causes the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to be\n determined automatically when verifying a signature.</td>\n </tr>\n <tr>\n <td><code>POINT_CONVERSION_COMPRESSED</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>POINT_CONVERSION_UNCOMPRESSED</code></td>\n <td></td>\n </tr>\n <tr>\n <td><code>POINT_CONVERSION_HYBRID</code></td>\n <td></td>\n </tr>\n</table>", "type": "module", "displayName": "Other OpenSSL Constants" }, { "textRaw": "Node.js Crypto Constants", "name": "node.js_crypto_constants", "desc": "<table>\n <tr>\n <th>Constant</th>\n <th>Description</th>\n </tr>\n <tr>\n <td><code>defaultCoreCipherList</code></td>\n <td>Specifies the built-in default cipher list used by Node.js.</td>\n </tr>\n <tr>\n <td><code>defaultCipherList</code></td>\n <td>Specifies the active default cipher list used by the current Node.js\n process.</td>\n </tr>\n</table>", "type": "module", "displayName": "Node.js Crypto Constants" } ], "type": "module", "displayName": "Crypto Constants" } ], "classes": [ { "textRaw": "Class: Certificate", "type": "class", "name": "Certificate", "meta": { "added": [ "v0.11.8" ], "changes": [] }, "desc": "<p>SPKAC is a Certificate Signing Request mechanism originally implemented by\nNetscape and was specified formally as part of <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen\">HTML5's <code>keygen</code> element</a>.</p>\n<p>Note that <code><keygen></code> is deprecated since <a href=\"https://www.w3.org/TR/html52/changes.html#features-removed\">HTML 5.2</a> and new projects\nshould not use this element anymore.</p>\n<p>The <code>crypto</code> module provides the <code>Certificate</code> class for working with SPKAC\ndata. The most common usage is handling output generated by the HTML5\n<code><keygen></code> element. Node.js uses <a href=\"https://www.openssl.org/docs/man1.1.0/apps/openssl-spkac.html\">OpenSSL's SPKAC implementation</a> internally.</p>", "methods": [ { "textRaw": "Certificate.exportChallenge(spkac)", "type": "method", "name": "exportChallenge", "meta": { "added": [ "v9.0.0" ], "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 | Buffer | TypedArray | DataView}", "name": "spkac", "type": "string | Buffer | TypedArray | DataView" } ] } ], "desc": "<pre><code class=\"language-js\">const { Certificate } = require('crypto');\nconst spkac = getSpkacSomehow();\nconst challenge = Certificate.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n</code></pre>" }, { "textRaw": "Certificate.exportPublicKey(spkac[, encoding])", "type": "method", "name": "exportPublicKey", "meta": { "added": [ "v9.0.0" ], "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 | Buffer | TypedArray | DataView}", "name": "spkac", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `spkac` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `spkac` string.", "optional": true } ] } ], "desc": "<pre><code class=\"language-js\">const { Certificate } = require('crypto');\nconst spkac = getSpkacSomehow();\nconst publicKey = Certificate.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n</code></pre>" }, { "textRaw": "Certificate.verifySpkac(spkac)", "type": "method", "name": "verifySpkac", "meta": { "added": [ "v9.0.0" ], "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` {Buffer | TypedArray | DataView}", "name": "spkac", "type": "Buffer | TypedArray | DataView" } ] } ], "desc": "<pre><code class=\"language-js\">const { Certificate } = require('crypto');\nconst spkac = getSpkacSomehow();\nconsole.log(Certificate.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n</code></pre>" } ], "modules": [ { "textRaw": "Legacy API", "name": "legacy_api", "desc": "<p>As a still supported legacy interface, it is possible (but not recommended) to\ncreate new instances of the <code>crypto.Certificate</code> class as illustrated in the\nexamples below.</p>", "ctors": [ { "textRaw": "new crypto.Certificate()", "type": "ctor", "name": "crypto.Certificate", "signatures": [ { "params": [] } ], "desc": "<p>Instances of the <code>Certificate</code> class can be created using the <code>new</code> keyword\nor by calling <code>crypto.Certificate()</code> as a function:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\n\nconst cert1 = new crypto.Certificate();\nconst cert2 = crypto.Certificate();\n</code></pre>" } ], "methods": [ { "textRaw": "certificate.exportChallenge(spkac)", "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 | Buffer | TypedArray | DataView}", "name": "spkac", "type": "string | Buffer | TypedArray | DataView" } ] } ], "desc": "<pre><code class=\"language-js\">const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconst challenge = cert.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n</code></pre>" }, { "textRaw": "certificate.exportPublicKey(spkac)", "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 | Buffer | TypedArray | DataView}", "name": "spkac", "type": "string | Buffer | TypedArray | DataView" } ] } ], "desc": "<pre><code class=\"language-js\">const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconst publicKey = cert.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n</code></pre>" }, { "textRaw": "certificate.verifySpkac(spkac)", "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` {Buffer | TypedArray | DataView}", "name": "spkac", "type": "Buffer | TypedArray | DataView" } ] } ], "desc": "<pre><code class=\"language-js\">const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n</code></pre>" } ], "type": "module", "displayName": "Legacy API" } ] }, { "textRaw": "Class: Cipher", "type": "class", "name": "Cipher", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "desc": "<p>Instances of the <code>Cipher</code> class are used to encrypt data. The class can be\nused in one of two ways:</p>\n<ul>\n<li>As a <a href=\"stream.html\">stream</a> that is both readable and writable, where plain unencrypted\ndata is written to produce encrypted data on the readable side, or</li>\n<li>Using the <a href=\"#crypto_cipher_update_data_inputencoding_outputencoding\"><code>cipher.update()</code></a> and <a href=\"#crypto_cipher_final_outputencoding\"><code>cipher.final()</code></a> methods to produce\nthe encrypted data.</li>\n</ul>\n<p>The <a href=\"#crypto_crypto_createcipher_algorithm_password_options\"><code>crypto.createCipher()</code></a> or <a href=\"#crypto_crypto_createcipheriv_algorithm_key_iv_options\"><code>crypto.createCipheriv()</code></a> methods are\nused to create <code>Cipher</code> instances. <code>Cipher</code> objects are not to be created\ndirectly using the <code>new</code> keyword.</p>\n<p>Example: Using <code>Cipher</code> objects as streams:</p>\n<pre><code class=\"language-js\">const crypto = require('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 async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// Use `crypto.randomBytes()` to generate a random iv instead of the static iv\n// shown here.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst cipher = crypto.createCipheriv(algorithm, key, iv);\n\nlet encrypted = '';\ncipher.on('readable', () => {\n let chunk;\n while (null !== (chunk = cipher.read())) {\n encrypted += chunk.toString('hex');\n }\n});\ncipher.on('end', () => {\n console.log(encrypted);\n // Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa\n});\n\ncipher.write('some clear text data');\ncipher.end();\n</code></pre>\n<p>Example: Using <code>Cipher</code> and piped streams:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst fs = require('fs');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// Use `crypto.randomBytes()` to generate a random iv instead of the static iv\n// shown here.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst cipher = crypto.createCipheriv(algorithm, key, iv);\n\nconst input = fs.createReadStream('test.js');\nconst output = fs.createWriteStream('test.enc');\n\ninput.pipe(cipher).pipe(output);\n</code></pre>\n<p>Example: Using the <a href=\"#crypto_cipher_update_data_inputencoding_outputencoding\"><code>cipher.update()</code></a> and <a href=\"#crypto_cipher_final_outputencoding\"><code>cipher.final()</code></a> methods:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = crypto.scryptSync(password, 'salt', 24);\n// Use `crypto.randomBytes` to generate a random iv instead of the static iv\n// shown here.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst cipher = crypto.createCipheriv(algorithm, key, iv);\n\nlet encrypted = cipher.update('some clear text data', 'utf8', 'hex');\nencrypted += cipher.final('hex');\nconsole.log(encrypted);\n// Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa\n</code></pre>", "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.", "optional": true } ] } ], "desc": "<p>Once the <code>cipher.final()</code> method has been called, the <code>Cipher</code> object can no\nlonger be used to encrypt data. Attempts to call <code>cipher.final()</code> more than\nonce will result in an error being thrown.</p>" }, { "textRaw": "cipher.setAAD(buffer[, options])", "type": "method", "name": "setAAD", "meta": { "added": [ "v1.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Cipher} for method chaining.", "name": "return", "type": "Cipher", "desc": "for method chaining." }, "params": [ { "textRaw": "`buffer` {Buffer}", "name": "buffer", "type": "Buffer" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]", "options": [ { "textRaw": "`plaintextLength` {number}", "name": "plaintextLength", "type": "number" } ], "optional": true } ] } ], "desc": "<p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code> and <code>OCB</code> are\ncurrently supported), the <code>cipher.setAAD()</code> method sets the value used for the\n<em>additional authenticated data</em> (AAD) input parameter.</p>\n<p>The <code>options</code> argument is optional for <code>GCM</code> and <code>OCB</code>. When using <code>CCM</code>, the\n<code>plaintextLength</code> option must be specified and its value must match the length\nof the plaintext in bytes. See <a href=\"#crypto_ccm_mode\">CCM mode</a>.</p>\n<p>The <code>cipher.setAAD()</code> method must be called before <a href=\"#crypto_cipher_update_data_inputencoding_outputencoding\"><code>cipher.update()</code></a>.</p>" }, { "textRaw": "cipher.getAuthTag()", "type": "method", "name": "getAuthTag", "meta": { "added": [ "v1.0.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer} When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are currently supported), the `cipher.getAuthTag()` method returns a [`Buffer`][] containing the _authentication tag_ that has been computed from the given data.", "name": "return", "type": "Buffer", "desc": "When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are currently supported), the `cipher.getAuthTag()` method returns a [`Buffer`][] containing the _authentication tag_ that has been computed from the given data." }, "params": [] } ], "desc": "<p>The <code>cipher.getAuthTag()</code> method should only be called after encryption has\nbeen completed using the <a href=\"#crypto_cipher_final_outputencoding\"><code>cipher.final()</code></a> method.</p>" }, { "textRaw": "cipher.setAutoPadding([autoPadding])", "type": "method", "name": "setAutoPadding", "meta": { "added": [ "v0.7.1" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Cipher} for method chaining.", "name": "return", "type": "Cipher", "desc": "for method chaining." }, "params": [ { "textRaw": "`autoPadding` {boolean} **Default:** `true`", "name": "autoPadding", "type": "boolean", "default": "`true`", "optional": true } ] } ], "desc": "<p>When using block encryption algorithms, the <code>Cipher</code> class will automatically\nadd padding to the input data to the appropriate block size. To disable the\ndefault padding call <code>cipher.setAutoPadding(false)</code>.</p>\n<p>When <code>autoPadding</code> is <code>false</code>, the length of the entire input data must be a\nmultiple of the cipher's block size or <a href=\"#crypto_cipher_final_outputencoding\"><code>cipher.final()</code></a> will throw an error.\nDisabling automatic padding is useful for non-standard padding, for instance\nusing <code>0x0</code> instead of PKCS padding.</p>\n<p>The <code>cipher.setAutoPadding()</code> method must be called before\n<a href=\"#crypto_cipher_final_outputencoding\"><code>cipher.final()</code></a>.</p>" }, { "textRaw": "cipher.update(data[, inputEncoding][, outputEncoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`data` {string | Buffer | TypedArray | DataView}", "name": "data", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the data.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the data.", "optional": true }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value.", "optional": true } ] } ], "desc": "<p>Updates the cipher with <code>data</code>. If the <code>inputEncoding</code> argument is given,\nthe <code>data</code>\nargument is a string using the specified encoding. If the <code>inputEncoding</code>\nargument is not given, <code>data</code> must be a <a href=\"buffer.html\"><code>Buffer</code></a>, <code>TypedArray</code>, or\n<code>DataView</code>. If <code>data</code> is a <a href=\"buffer.html\"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>, then\n<code>inputEncoding</code> is ignored.</p>\n<p>The <code>outputEncoding</code> specifies the output format of the enciphered\ndata. If the <code>outputEncoding</code>\nis specified, a string using the specified encoding is returned. If no\n<code>outputEncoding</code> is provided, a <a href=\"buffer.html\"><code>Buffer</code></a> is returned.</p>\n<p>The <code>cipher.update()</code> method can be called multiple times with new data until\n<a href=\"#crypto_cipher_final_outputencoding\"><code>cipher.final()</code></a> is called. Calling <code>cipher.update()</code> after\n<a href=\"#crypto_cipher_final_outputencoding\"><code>cipher.final()</code></a> will result in an error being thrown.</p>" } ] }, { "textRaw": "Class: Decipher", "type": "class", "name": "Decipher", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "desc": "<p>Instances of the <code>Decipher</code> class are used to decrypt data. The class can be\nused in one of two ways:</p>\n<ul>\n<li>As a <a href=\"stream.html\">stream</a> that is both readable and writable, where plain encrypted\ndata is written to produce unencrypted data on the readable side, or</li>\n<li>Using the <a href=\"#crypto_decipher_update_data_inputencoding_outputencoding\"><code>decipher.update()</code></a> and <a href=\"#crypto_decipher_final_outputencoding\"><code>decipher.final()</code></a> methods to\nproduce the unencrypted data.</li>\n</ul>\n<p>The <a href=\"#crypto_crypto_createdecipher_algorithm_password_options\"><code>crypto.createDecipher()</code></a> or <a href=\"#crypto_crypto_createdecipheriv_algorithm_key_iv_options\"><code>crypto.createDecipheriv()</code></a> methods are\nused to create <code>Decipher</code> instances. <code>Decipher</code> objects are not to be created\ndirectly using the <code>new</code> keyword.</p>\n<p>Example: Using <code>Decipher</code> objects as streams:</p>\n<pre><code class=\"language-js\">const crypto = require('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 = crypto.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 = crypto.createDecipheriv(algorithm, key, iv);\n\nlet decrypted = '';\ndecipher.on('readable', () => {\n while (null !== (chunk = decipher.read())) {\n decrypted += chunk.toString('utf8');\n }\n});\ndecipher.on('end', () => {\n console.log(decrypted);\n // Prints: some clear text data\n});\n\n// Encrypted with same algorithm, key and iv.\nconst encrypted =\n 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\ndecipher.write(encrypted, 'hex');\ndecipher.end();\n</code></pre>\n<p>Example: Using <code>Decipher</code> and piped streams:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst fs = require('fs');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = crypto.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 = crypto.createDecipheriv(algorithm, key, iv);\n\nconst input = fs.createReadStream('test.enc');\nconst output = fs.createWriteStream('test.js');\n\ninput.pipe(decipher).pipe(output);\n</code></pre>\n<p>Example: Using the <a href=\"#crypto_decipher_update_data_inputencoding_outputencoding\"><code>decipher.update()</code></a> and <a href=\"#crypto_decipher_final_outputencoding\"><code>decipher.final()</code></a> methods:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = crypto.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 = crypto.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</code></pre>", "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.", "optional": true } ] } ], "desc": "<p>Once the <code>decipher.final()</code> method has been called, the <code>Decipher</code> object can\nno longer be used to decrypt data. Attempts to call <code>decipher.final()</code> more\nthan once will result in an error being thrown.</p>" }, { "textRaw": "decipher.setAAD(buffer[, options])", "type": "method", "name": "setAAD", "meta": { "added": [ "v1.0.0" ], "changes": [ { "version": "v7.2.0", "pr-url": "https://github.com/nodejs/node/pull/9398", "description": "This method now returns a reference to `decipher`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Decipher} for method chaining.", "name": "return", "type": "Decipher", "desc": "for method chaining." }, "params": [ { "textRaw": "`buffer` {Buffer | TypedArray | DataView}", "name": "buffer", "type": "Buffer | TypedArray | DataView" }, { "textRaw": "`options` {Object} [`stream.transform` options][]", "name": "options", "type": "Object", "desc": "[`stream.transform` options][]", "options": [ { "textRaw": "`plaintextLength` {number}", "name": "plaintextLength", "type": "number" } ], "optional": true } ] } ], "desc": "<p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code> and <code>OCB</code> are\ncurrently supported), the <code>decipher.setAAD()</code> method sets the value used for the\n<em>additional authenticated data</em> (AAD) input parameter.</p>\n<p>The <code>options</code> argument is optional for <code>GCM</code>. When using <code>CCM</code>, the\n<code>plaintextLength</code> option must be specified and its value must match the length\nof the plaintext in bytes. See <a href=\"#crypto_ccm_mode\">CCM mode</a>.</p>\n<p>The <code>decipher.setAAD()</code> method must be called before <a href=\"#crypto_decipher_update_data_inputencoding_outputencoding\"><code>decipher.update()</code></a>.</p>" }, { "textRaw": "decipher.setAuthTag(buffer)", "type": "method", "name": "setAuthTag", "meta": { "added": [ "v1.0.0" ], "changes": [ { "version": "v7.2.0", "pr-url": "https://github.com/nodejs/node/pull/9398", "description": "This method now returns a reference to `decipher`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Decipher} for method chaining.", "name": "return", "type": "Decipher", "desc": "for method chaining." }, "params": [ { "textRaw": "`buffer` {Buffer | TypedArray | DataView}", "name": "buffer", "type": "Buffer | TypedArray | DataView" } ] } ], "desc": "<p>When using an authenticated encryption mode (<code>GCM</code>, <code>CCM</code> and <code>OCB</code> are\ncurrently supported), the <code>decipher.setAuthTag()</code> method is used to pass in the\nreceived <em>authentication tag</em>. If no tag is provided, or if the cipher text\nhas been tampered with, <a href=\"#crypto_decipher_final_outputencoding\"><code>decipher.final()</code></a> will throw, indicating that the\ncipher text should be discarded due to failed authentication.</p>\n<p>Note that this Node.js version does not verify the length of GCM authentication\ntags. Such a check <em>must</em> be implemented by applications and is crucial to the\nauthenticity of the encrypted data, otherwise, an attacker can use an\narbitrarily short authentication tag to increase the chances of successfully\npassing authentication (up to 0.39%). It is highly recommended to associate one\nof the values 16, 15, 14, 13, 12, 8 or 4 bytes with each key, and to only permit\nauthentication tags of that length, see <a href=\"https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf\">NIST SP 800-38D</a>.</p>\n<p>The <code>decipher.setAuthTag()</code> method must be called before\n<a href=\"#crypto_decipher_final_outputencoding\"><code>decipher.final()</code></a>.</p>" }, { "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`", "optional": true } ] } ], "desc": "<p>When data has been encrypted without standard block padding, calling\n<code>decipher.setAutoPadding(false)</code> will disable automatic padding to prevent\n<a href=\"#crypto_decipher_final_outputencoding\"><code>decipher.final()</code></a> from checking for and removing padding.</p>\n<p>Turning auto padding off will only work if the input data's length is a\nmultiple of the ciphers block size.</p>\n<p>The <code>decipher.setAutoPadding()</code> method must be called before\n<a href=\"#crypto_decipher_final_outputencoding\"><code>decipher.final()</code></a>.</p>" }, { "textRaw": "decipher.update(data[, inputEncoding][, outputEncoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`data` {string | Buffer | TypedArray | DataView}", "name": "data", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string.", "optional": true }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value.", "optional": true } ] } ], "desc": "<p>Updates the decipher with <code>data</code>. If the <code>inputEncoding</code> argument is given,\nthe <code>data</code>\nargument is a string using the specified encoding. If the <code>inputEncoding</code>\nargument is not given, <code>data</code> must be a <a href=\"buffer.html\"><code>Buffer</code></a>. If <code>data</code> is a\n<a href=\"buffer.html\"><code>Buffer</code></a> then <code>inputEncoding</code> is ignored.</p>\n<p>The <code>outputEncoding</code> specifies the output format of the enciphered\ndata. If the <code>outputEncoding</code>\nis specified, a string using the specified encoding is returned. If no\n<code>outputEncoding</code> is provided, a <a href=\"buffer.html\"><code>Buffer</code></a> is returned.</p>\n<p>The <code>decipher.update()</code> method can be called multiple times with new data until\n<a href=\"#crypto_decipher_final_outputencoding\"><code>decipher.final()</code></a> is called. Calling <code>decipher.update()</code> after\n<a href=\"#crypto_decipher_final_outputencoding\"><code>decipher.final()</code></a> will result in an error being thrown.</p>" } ] }, { "textRaw": "Class: DiffieHellman", "type": "class", "name": "DiffieHellman", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "desc": "<p>The <code>DiffieHellman</code> class is a utility for creating Diffie-Hellman key\nexchanges.</p>\n<p>Instances of the <code>DiffieHellman</code> class can be created using the\n<a href=\"#crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding\"><code>crypto.createDiffieHellman()</code></a> function.</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst assert = require('assert');\n\n// Generate Alice's keys...\nconst alice = crypto.createDiffieHellman(2048);\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = crypto.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</code></pre>", "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 | Buffer | TypedArray | DataView}", "name": "otherPublicKey", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of an `otherPublicKey` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of an `otherPublicKey` string.", "optional": true }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value.", "optional": true } ] } ], "desc": "<p>Computes the shared secret using <code>otherPublicKey</code> as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using the specified <code>inputEncoding</code>, and secret is\nencoded using specified <code>outputEncoding</code>.\nIf the <code>inputEncoding</code> is not\nprovided, <code>otherPublicKey</code> is expected to be a <a href=\"buffer.html\"><code>Buffer</code></a>,\n<code>TypedArray</code>, or <code>DataView</code>.</p>\n<p>If <code>outputEncoding</code> is given a string is returned; otherwise, a\n<a href=\"buffer.html\"><code>Buffer</code></a> is returned.</p>" }, { "textRaw": "diffieHellman.generateKeys([encoding])", "type": "method", "name": "generateKeys", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value.", "optional": true } ] } ], "desc": "<p>Generates private and public Diffie-Hellman key values, and returns\nthe public key in the specified <code>encoding</code>. This key should be\ntransferred to the other party.\nIf <code>encoding</code> is provided a string is returned; otherwise a\n<a href=\"buffer.html\"><code>Buffer</code></a> is returned.</p>" }, { "textRaw": "diffieHellman.getGenerator([encoding])", "type": "method", "name": "getGenerator", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value.", "optional": true } ] } ], "desc": "<p>Returns the Diffie-Hellman generator in the specified <code>encoding</code>.\nIf <code>encoding</code> is provided a string is\nreturned; otherwise a <a href=\"buffer.html\"><code>Buffer</code></a> is returned.</p>" }, { "textRaw": "diffieHellman.getPrime([encoding])", "type": "method", "name": "getPrime", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value.", "optional": true } ] } ], "desc": "<p>Returns the Diffie-Hellman prime in the specified <code>encoding</code>.\nIf <code>encoding</code> is provided a string is\nreturned; otherwise a <a href=\"buffer.html\"><code>Buffer</code></a> is returned.</p>" }, { "textRaw": "diffieHellman.getPrivateKey([encoding])", "type": "method", "name": "getPrivateKey", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value.", "optional": true } ] } ], "desc": "<p>Returns the Diffie-Hellman private key in the specified <code>encoding</code>.\nIf <code>encoding</code> is provided a\nstring is returned; otherwise a <a href=\"buffer.html\"><code>Buffer</code></a> is returned.</p>" }, { "textRaw": "diffieHellman.getPublicKey([encoding])", "type": "method", "name": "getPublicKey", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value.", "optional": true } ] } ], "desc": "<p>Returns the Diffie-Hellman public key in the specified <code>encoding</code>.\nIf <code>encoding</code> is provided a\nstring is returned; otherwise a <a href=\"buffer.html\"><code>Buffer</code></a> is returned.</p>" }, { "textRaw": "diffieHellman.setPrivateKey(privateKey[, encoding])", "type": "method", "name": "setPrivateKey", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`privateKey` {string | Buffer | TypedArray | DataView}", "name": "privateKey", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `privateKey` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `privateKey` string.", "optional": true } ] } ], "desc": "<p>Sets the Diffie-Hellman private key. If the <code>encoding</code> argument is provided,\n<code>privateKey</code> is expected\nto be a string. If no <code>encoding</code> is provided, <code>privateKey</code> is expected\nto be a <a href=\"buffer.html\"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>.</p>" }, { "textRaw": "diffieHellman.setPublicKey(publicKey[, encoding])", "type": "method", "name": "setPublicKey", "meta": { "added": [ "v0.5.0" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`publicKey` {string | Buffer | TypedArray | DataView}", "name": "publicKey", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `publicKey` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `publicKey` string.", "optional": true } ] } ], "desc": "<p>Sets the Diffie-Hellman public key. If the <code>encoding</code> argument is provided,\n<code>publicKey</code> is expected\nto be a string. If no <code>encoding</code> is provided, <code>publicKey</code> is expected\nto be a <a href=\"buffer.html\"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code>.</p>" } ], "properties": [ { "textRaw": "diffieHellman.verifyError", "name": "verifyError", "meta": { "added": [ "v0.11.12" ], "changes": [] }, "desc": "<p>A bit field containing any warnings and/or errors resulting from a check\nperformed during initialization of the <code>DiffieHellman</code> object.</p>\n<p>The following values are valid for this property (as defined in <code>constants</code>\nmodule):</p>\n<ul>\n<li><code>DH_CHECK_P_NOT_SAFE_PRIME</code></li>\n<li><code>DH_CHECK_P_NOT_PRIME</code></li>\n<li><code>DH_UNABLE_TO_CHECK_GENERATOR</code></li>\n<li><code>DH_NOT_SUITABLE_GENERATOR</code></li>\n</ul>" } ] }, { "textRaw": "Class: ECDH", "type": "class", "name": "ECDH", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "desc": "<p>The <code>ECDH</code> class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)\nkey exchanges.</p>\n<p>Instances of the <code>ECDH</code> class can be created using the\n<a href=\"#crypto_crypto_createecdh_curvename\"><code>crypto.createECDH()</code></a> function.</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst assert = require('assert');\n\n// Generate Alice's keys...\nconst alice = crypto.createECDH('secp521r1');\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = crypto.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</code></pre>", "classMethods": [ { "textRaw": "Class 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 | Buffer | TypedArray | DataView}", "name": "key", "type": "string | 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.", "optional": true }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value.", "optional": true }, { "textRaw": "`format` {string} **Default:** `'uncompressed'`", "name": "format", "type": "string", "default": "`'uncompressed'`", "optional": true } ] } ], "desc": "<p>Converts the EC Diffie-Hellman public key specified by <code>key</code> and <code>curve</code> to the\nformat specified by <code>format</code>. The <code>format</code> argument specifies point encoding\nand can be <code>'compressed'</code>, <code>'uncompressed'</code> or <code>'hybrid'</code>. The supplied key is\ninterpreted using the specified <code>inputEncoding</code>, and the returned key is encoded\nusing the specified <code>outputEncoding</code>.</p>\n<p>Use <a href=\"#crypto_crypto_getcurves\"><code>crypto.getCurves()</code></a> to obtain a list of available curve names.\nOn recent OpenSSL releases, <code>openssl ecparam -list_curves</code> will also display\nthe name and description of each available elliptic curve.</p>\n<p>If <code>format</code> is not specified the point will be returned in <code>'uncompressed'</code>\nformat.</p>\n<p>If the <code>inputEncoding</code> is not provided, <code>key</code> is expected to be a <a href=\"buffer.html\"><code>Buffer</code></a>,\n<code>TypedArray</code>, or <code>DataView</code>.</p>\n<p>Example (uncompressing a key):</p>\n<pre><code class=\"language-js\">const { createECDH, ECDH } = require('crypto');\n\nconst ecdh = createECDH('secp256k1');\necdh.generateKeys();\n\nconst compressedKey = ecdh.getPublicKey('hex', 'compressed');\n\nconst uncompressedKey = ECDH.convertKey(compressedKey,\n 'secp256k1',\n 'hex',\n 'hex',\n 'uncompressed');\n\n// the converted key and the uncompressed public key should be the same\nconsole.log(uncompressedKey === ecdh.getPublicKey('hex'));\n</code></pre>" } ], "methods": [ { "textRaw": "ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])", "type": "method", "name": "computeSecret", "meta": { "added": [ "v0.11.14" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`" }, { "version": "v10.0.0", "pr-url": "https://github.com/nodejs/node/pull/16849", "description": "Changed error format to better support invalid public key error" } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`otherPublicKey` {string | Buffer | TypedArray | DataView}", "name": "otherPublicKey", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `otherPublicKey` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `otherPublicKey` string.", "optional": true }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value.", "optional": true } ] } ], "desc": "<p>Computes the shared secret using <code>otherPublicKey</code> as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using specified <code>inputEncoding</code>, and the returned secret\nis encoded using the specified <code>outputEncoding</code>.\nIf the <code>inputEncoding</code> is not\nprovided, <code>otherPublicKey</code> is expected to be a <a href=\"buffer.html\"><code>Buffer</code></a>, <code>TypedArray</code>, or\n<code>DataView</code>.</p>\n<p>If <code>outputEncoding</code> is given a string will be returned; otherwise a\n<a href=\"buffer.html\"><code>Buffer</code></a> is returned.</p>\n<p><code>ecdh.computeSecret</code> will throw an\n<code>ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY</code> error when <code>otherPublicKey</code>\nlies outside of the elliptic curve. Since <code>otherPublicKey</code> is\nusually supplied from a remote user over an insecure network,\nits recommended for developers to handle this exception accordingly.</p>" }, { "textRaw": "ecdh.generateKeys([encoding[, format]])", "type": "method", "name": "generateKeys", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value.", "optional": true }, { "textRaw": "`format` {string} **Default:** `'uncompressed'`", "name": "format", "type": "string", "default": "`'uncompressed'`", "optional": true } ] } ], "desc": "<p>Generates private and public EC Diffie-Hellman key values, and returns\nthe public key in the specified <code>format</code> and <code>encoding</code>. This key should be\ntransferred to the other party.</p>\n<p>The <code>format</code> argument specifies point encoding and can be <code>'compressed'</code> or\n<code>'uncompressed'</code>. If <code>format</code> is not specified, the point will be returned in\n<code>'uncompressed'</code> format.</p>\n<p>If <code>encoding</code> is provided a string is returned; otherwise a <a href=\"buffer.html\"><code>Buffer</code></a>\nis returned.</p>" }, { "textRaw": "ecdh.getPrivateKey([encoding])", "type": "method", "name": "getPrivateKey", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string} The EC Diffie-Hellman in the specified `encoding`.", "name": "return", "type": "Buffer | string", "desc": "The EC Diffie-Hellman in the specified `encoding`." }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value.", "optional": true } ] } ], "desc": "<p>If <code>encoding</code> is specified, a string is returned; otherwise a <a href=\"buffer.html\"><code>Buffer</code></a> is\nreturned.</p>" }, { "textRaw": "ecdh.getPublicKey([encoding][, format])", "type": "method", "name": "getPublicKey", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string} The EC Diffie-Hellman public key in the specified `encoding` and `format`.", "name": "return", "type": "Buffer | string", "desc": "The EC Diffie-Hellman public key in the specified `encoding` and `format`." }, "params": [ { "textRaw": "`encoding` {string} The [encoding][] of the return value.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the return value.", "optional": true }, { "textRaw": "`format` {string} **Default:** `'uncompressed'`", "name": "format", "type": "string", "default": "`'uncompressed'`", "optional": true } ] } ], "desc": "<p>The <code>format</code> argument specifies point encoding and can be <code>'compressed'</code> or\n<code>'uncompressed'</code>. If <code>format</code> is not specified the point will be returned in\n<code>'uncompressed'</code> format.</p>\n<p>If <code>encoding</code> is specified, a string is returned; otherwise a <a href=\"buffer.html\"><code>Buffer</code></a> is\nreturned.</p>" }, { "textRaw": "ecdh.setPrivateKey(privateKey[, encoding])", "type": "method", "name": "setPrivateKey", "meta": { "added": [ "v0.11.14" ], "changes": [] }, "signatures": [ { "params": [ { "textRaw": "`privateKey` {string | Buffer | TypedArray | DataView}", "name": "privateKey", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `privateKey` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `privateKey` string.", "optional": true } ] } ], "desc": "<p>Sets the EC Diffie-Hellman private key.\nIf <code>encoding</code> is provided, <code>privateKey</code> is expected\nto be a string; otherwise <code>privateKey</code> is expected to be a <a href=\"buffer.html\"><code>Buffer</code></a>,\n<code>TypedArray</code>, or <code>DataView</code>.</p>\n<p>If <code>privateKey</code> is not valid for the curve specified when the <code>ECDH</code> object was\ncreated, an error is thrown. Upon setting the private key, the associated\npublic point (key) is also generated and set in the <code>ECDH</code> object.</p>" }, { "textRaw": "ecdh.setPublicKey(publicKey[, encoding])", "type": "method", "name": "setPublicKey", "meta": { "added": [ "v0.11.14" ], "deprecated": [ "v5.2.0" ], "changes": [] }, "stability": 0, "stabilityText": "Deprecated", "signatures": [ { "params": [ { "textRaw": "`publicKey` {string | Buffer | TypedArray | DataView}", "name": "publicKey", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`encoding` {string} The [encoding][] of the `publicKey` string.", "name": "encoding", "type": "string", "desc": "The [encoding][] of the `publicKey` string.", "optional": true } ] } ], "desc": "<p>Sets the EC Diffie-Hellman public key.\nIf <code>encoding</code> is provided <code>publicKey</code> is expected to\nbe a string; otherwise a <a href=\"buffer.html\"><code>Buffer</code></a>, <code>TypedArray</code>, or <code>DataView</code> is expected.</p>\n<p>Note that there is not normally a reason to call this method because <code>ECDH</code>\nonly requires a private key and the other party's public key to compute the\nshared secret. Typically either <a href=\"#crypto_ecdh_generatekeys_encoding_format\"><code>ecdh.generateKeys()</code></a> or\n<a href=\"#crypto_ecdh_setprivatekey_privatekey_encoding\"><code>ecdh.setPrivateKey()</code></a> will be called. The <a href=\"#crypto_ecdh_setprivatekey_privatekey_encoding\"><code>ecdh.setPrivateKey()</code></a> method\nattempts to generate the public point/key associated with the private key being\nset.</p>\n<p>Example (obtaining a shared secret):</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst alice = crypto.createECDH('secp256k1');\nconst bob = crypto.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 crypto.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</code></pre>" } ] }, { "textRaw": "Class: Hash", "type": "class", "name": "Hash", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "desc": "<p>The <code>Hash</code> class is a utility for creating hash digests of data. It can be\nused in one of two ways:</p>\n<ul>\n<li>As a <a href=\"stream.html\">stream</a> that is both readable and writable, where data is written\nto produce a computed hash digest on the readable side, or</li>\n<li>Using the <a href=\"#crypto_hash_update_data_inputencoding\"><code>hash.update()</code></a> and <a href=\"#crypto_hash_digest_encoding\"><code>hash.digest()</code></a> methods to produce the\ncomputed hash.</li>\n</ul>\n<p>The <a href=\"#crypto_crypto_createhash_algorithm_options\"><code>crypto.createHash()</code></a> method is used to create <code>Hash</code> instances. <code>Hash</code>\nobjects are not to be created directly using the <code>new</code> keyword.</p>\n<p>Example: Using <code>Hash</code> objects as streams:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst hash = crypto.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</code></pre>\n<p>Example: Using <code>Hash</code> and piped streams:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst fs = require('fs');\nconst hash = crypto.createHash('sha256');\n\nconst input = fs.createReadStream('test.js');\ninput.pipe(hash).pipe(process.stdout);\n</code></pre>\n<p>Example: Using the <a href=\"#crypto_hash_update_data_inputencoding\"><code>hash.update()</code></a> and <a href=\"#crypto_hash_digest_encoding\"><code>hash.digest()</code></a> methods:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst hash = crypto.createHash('sha256');\n\nhash.update('some data to hash');\nconsole.log(hash.digest('hex'));\n// Prints:\n// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n</code></pre>", "methods": [ { "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.", "optional": true } ] } ], "desc": "<p>Calculates the digest of all of the data passed to be hashed (using the\n<a href=\"#crypto_hash_update_data_inputencoding\"><code>hash.update()</code></a> method).\nIf <code>encoding</code> is provided a string will be returned; otherwise\na <a href=\"buffer.html\"><code>Buffer</code></a> is returned.</p>\n<p>The <code>Hash</code> object can not be used again after <code>hash.digest()</code> method has been\ncalled. Multiple calls will cause an error to be thrown.</p>" }, { "textRaw": "hash.update(data[, inputEncoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "params": [ { "textRaw": "`data` {string | Buffer | TypedArray | DataView}", "name": "data", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string.", "optional": true } ] } ], "desc": "<p>Updates the hash content with the given <code>data</code>, the encoding of which\nis given in <code>inputEncoding</code>.\nIf <code>encoding</code> is not provided, and the <code>data</code> is a string, an\nencoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href=\"buffer.html\"><code>Buffer</code></a>, <code>TypedArray</code>, or\n<code>DataView</code>, then <code>inputEncoding</code> is ignored.</p>\n<p>This can be called many times with new data as it is streamed.</p>" } ] }, { "textRaw": "Class: Hmac", "type": "class", "name": "Hmac", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "desc": "<p>The <code>Hmac</code> Class is a utility for creating cryptographic HMAC digests. It can\nbe used in one of two ways:</p>\n<ul>\n<li>As a <a href=\"stream.html\">stream</a> that is both readable and writable, where data is written\nto produce a computed HMAC digest on the readable side, or</li>\n<li>Using the <a href=\"#crypto_hmac_update_data_inputencoding\"><code>hmac.update()</code></a> and <a href=\"#crypto_hmac_digest_encoding\"><code>hmac.digest()</code></a> methods to produce the\ncomputed HMAC digest.</li>\n</ul>\n<p>The <a href=\"#crypto_crypto_createhmac_algorithm_key_options\"><code>crypto.createHmac()</code></a> method is used to create <code>Hmac</code> instances. <code>Hmac</code>\nobjects are not to be created directly using the <code>new</code> keyword.</p>\n<p>Example: Using <code>Hmac</code> objects as streams:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst hmac = crypto.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</code></pre>\n<p>Example: Using <code>Hmac</code> and piped streams:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst fs = require('fs');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nconst input = fs.createReadStream('test.js');\ninput.pipe(hmac).pipe(process.stdout);\n</code></pre>\n<p>Example: Using the <a href=\"#crypto_hmac_update_data_inputencoding\"><code>hmac.update()</code></a> and <a href=\"#crypto_hmac_digest_encoding\"><code>hmac.digest()</code></a> methods:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nhmac.update('some data to hash');\nconsole.log(hmac.digest('hex'));\n// Prints:\n// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n</code></pre>", "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.", "optional": true } ] } ], "desc": "<p>Calculates the HMAC digest of all of the data passed using <a href=\"#crypto_hmac_update_data_inputencoding\"><code>hmac.update()</code></a>.\nIf <code>encoding</code> is\nprovided a string is returned; otherwise a <a href=\"buffer.html\"><code>Buffer</code></a> is returned;</p>\n<p>The <code>Hmac</code> object can not be used again after <code>hmac.digest()</code> has been\ncalled. Multiple calls to <code>hmac.digest()</code> will result in an error being thrown.</p>" }, { "textRaw": "hmac.update(data[, inputEncoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "params": [ { "textRaw": "`data` {string | Buffer | TypedArray | DataView}", "name": "data", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string.", "optional": true } ] } ], "desc": "<p>Updates the <code>Hmac</code> content with the given <code>data</code>, the encoding of which\nis given in <code>inputEncoding</code>.\nIf <code>encoding</code> is not provided, and the <code>data</code> is a string, an\nencoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href=\"buffer.html\"><code>Buffer</code></a>, <code>TypedArray</code>, or\n<code>DataView</code>, then <code>inputEncoding</code> is ignored.</p>\n<p>This can be called many times with new data as it is streamed.</p>" } ] }, { "textRaw": "Class: Sign", "type": "class", "name": "Sign", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "desc": "<p>The <code>Sign</code> Class is a utility for generating signatures. It can be used in one\nof two ways:</p>\n<ul>\n<li>As a writable <a href=\"stream.html\">stream</a>, where data to be signed is written and the\n<a href=\"#crypto_sign_sign_privatekey_outputencoding\"><code>sign.sign()</code></a> method is used to generate and return the signature, or</li>\n<li>Using the <a href=\"#crypto_sign_update_data_inputencoding\"><code>sign.update()</code></a> and <a href=\"#crypto_sign_sign_privatekey_outputencoding\"><code>sign.sign()</code></a> methods to produce the\nsignature.</li>\n</ul>\n<p>The <a href=\"#crypto_crypto_createsign_algorithm_options\"><code>crypto.createSign()</code></a> method is used to create <code>Sign</code> instances. The\nargument is the string name of the hash function to use. <code>Sign</code> objects are not\nto be created directly using the <code>new</code> keyword.</p>\n<p>Example: Using <code>Sign</code> objects as streams:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst sign = crypto.createSign('SHA256');\n\nsign.write('some data to sign');\nsign.end();\n\nconst privateKey = getPrivateKeySomehow();\nconsole.log(sign.sign(privateKey, 'hex'));\n// Prints: the calculated signature using the specified private key and\n// SHA-256. For RSA keys, the algorithm is RSASSA-PKCS1-v1_5 (see padding\n// parameter below for RSASSA-PSS). For EC keys, the algorithm is ECDSA.\n</code></pre>\n<p>Example: Using the <a href=\"#crypto_sign_update_data_inputencoding\"><code>sign.update()</code></a> and <a href=\"#crypto_sign_sign_privatekey_outputencoding\"><code>sign.sign()</code></a> methods:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst sign = crypto.createSign('SHA256');\n\nsign.update('some data to sign');\n\nconst privateKey = getPrivateKeySomehow();\nconsole.log(sign.sign(privateKey, 'hex'));\n// Prints: the calculated signature\n</code></pre>\n<p>In some cases, a <code>Sign</code> instance can also be created by passing in a signature\nalgorithm name, such as 'RSA-SHA256'. This will use the corresponding digest\nalgorithm. This does not work for all signature algorithms, such as\n'ecdsa-with-SHA256'. Use digest names instead.</p>\n<p>Example: signing using legacy signature algorithm name</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst sign = crypto.createSign('RSA-SHA256');\n\nsign.update('some data to sign');\n\nconst privateKey = getPrivateKeySomehow();\nconsole.log(sign.sign(privateKey, 'hex'));\n// Prints: the calculated signature\n</code></pre>", "methods": [ { "textRaw": "sign.sign(privateKey[, outputEncoding])", "type": "method", "name": "sign", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11705", "description": "Support for RSASSA-PSS and additional options was added." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {Buffer | string}", "name": "return", "type": "Buffer | string" }, "params": [ { "textRaw": "`privateKey` {string | Object}", "name": "privateKey", "type": "string | Object", "options": [ { "textRaw": "`key` {string}", "name": "key", "type": "string" }, { "textRaw": "`passphrase` {string}", "name": "passphrase", "type": "string" }, { "textRaw": "`padding` {integer}", "name": "padding", "type": "integer" }, { "textRaw": "`saltLength` {integer}", "name": "saltLength", "type": "integer" } ] }, { "textRaw": "`outputEncoding` {string} The [encoding][] of the return value.", "name": "outputEncoding", "type": "string", "desc": "The [encoding][] of the return value.", "optional": true } ] } ], "desc": "<p>Calculates the signature on all the data passed through using either\n<a href=\"#crypto_sign_update_data_inputencoding\"><code>sign.update()</code></a> or <a href=\"stream.html#stream_writable_write_chunk_encoding_callback\"><code>sign.write()</code></a>.</p>\n<p>The <code>privateKey</code> argument can be an object or a string. If <code>privateKey</code> is a\nstring, it is treated as a raw key with no passphrase. If <code>privateKey</code> is an\nobject, it must contain one or more of the following properties:</p>\n<ul>\n<li>\n<p><code>key</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\"><string></a> - PEM encoded private key (required)</p>\n</li>\n<li>\n<p><code>passphrase</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\"><string></a> - passphrase for the private key</p>\n</li>\n<li>\n<p><code>padding</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><integer></a> - Optional padding value for RSA, one of the following:</p>\n<ul>\n<li><code>crypto.constants.RSA_PKCS1_PADDING</code> (default)</li>\n<li><code>crypto.constants.RSA_PKCS1_PSS_PADDING</code></li>\n</ul>\n<p>Note that <code>RSA_PKCS1_PSS_PADDING</code> will use MGF1 with the same hash function\nused to sign the message as specified in section 3.1 of <a href=\"https://www.rfc-editor.org/rfc/rfc4055.txt\">RFC 4055</a>.</p>\n</li>\n<li>\n<p><code>saltLength</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><integer></a> - salt length for when padding is\n<code>RSA_PKCS1_PSS_PADDING</code>. The special value\n<code>crypto.constants.RSA_PSS_SALTLEN_DIGEST</code> sets the salt length to the digest\nsize, <code>crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN</code> (default) sets it to the\nmaximum permissible value.</p>\n</li>\n</ul>\n<p>If <code>outputEncoding</code> is provided a string is returned; otherwise a <a href=\"buffer.html\"><code>Buffer</code></a>\nis returned.</p>\n<p>The <code>Sign</code> object can not be again used after <code>sign.sign()</code> method has been\ncalled. Multiple calls to <code>sign.sign()</code> will result in an error being thrown.</p>" }, { "textRaw": "sign.update(data[, inputEncoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "params": [ { "textRaw": "`data` {string | Buffer | TypedArray | DataView}", "name": "data", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string.", "optional": true } ] } ], "desc": "<p>Updates the <code>Sign</code> content with the given <code>data</code>, the encoding of which\nis given in <code>inputEncoding</code>.\nIf <code>encoding</code> is not provided, and the <code>data</code> is a string, an\nencoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href=\"buffer.html\"><code>Buffer</code></a>, <code>TypedArray</code>, or\n<code>DataView</code>, then <code>inputEncoding</code> is ignored.</p>\n<p>This can be called many times with new data as it is streamed.</p>" } ] }, { "textRaw": "Class: Verify", "type": "class", "name": "Verify", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "desc": "<p>The <code>Verify</code> class is a utility for verifying signatures. It can be used in one\nof two ways:</p>\n<ul>\n<li>As a writable <a href=\"stream.html\">stream</a> where written data is used to validate against the\nsupplied signature, or</li>\n<li>Using the <a href=\"#crypto_verify_update_data_inputencoding\"><code>verify.update()</code></a> and <a href=\"#crypto_verify_verify_object_signature_signatureencoding\"><code>verify.verify()</code></a> methods to verify\nthe signature.</li>\n</ul>\n<p>The <a href=\"#crypto_crypto_createverify_algorithm_options\"><code>crypto.createVerify()</code></a> method is used to create <code>Verify</code> instances.\n<code>Verify</code> objects are not to be created directly using the <code>new</code> keyword.</p>\n<p>Example: Using <code>Verify</code> objects as streams:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst verify = crypto.createVerify('SHA256');\n\nverify.write('some data to sign');\nverify.end();\n\nconst publicKey = getPublicKeySomehow();\nconst signature = getSignatureToVerify();\nconsole.log(verify.verify(publicKey, signature));\n// Prints: true or false\n</code></pre>\n<p>Example: Using the <a href=\"#crypto_verify_update_data_inputencoding\"><code>verify.update()</code></a> and <a href=\"#crypto_verify_verify_object_signature_signatureencoding\"><code>verify.verify()</code></a> methods:</p>\n<pre><code class=\"language-js\">const crypto = require('crypto');\nconst verify = crypto.createVerify('SHA256');\n\nverify.update('some data to sign');\n\nconst publicKey = getPublicKeySomehow();\nconst signature = getSignatureToVerify();\nconsole.log(verify.verify(publicKey, signature));\n// Prints: true or false\n</code></pre>", "methods": [ { "textRaw": "verify.update(data[, inputEncoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v6.0.0", "pr-url": "https://github.com/nodejs/node/pull/5522", "description": "The default `inputEncoding` changed from `binary` to `utf8`." } ] }, "signatures": [ { "params": [ { "textRaw": "`data` {string | Buffer | TypedArray | DataView}", "name": "data", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`inputEncoding` {string} The [encoding][] of the `data` string.", "name": "inputEncoding", "type": "string", "desc": "The [encoding][] of the `data` string.", "optional": true } ] } ], "desc": "<p>Updates the <code>Verify</code> content with the given <code>data</code>, the encoding of which\nis given in <code>inputEncoding</code>.\nIf <code>inputEncoding</code> is not provided, and the <code>data</code> is a string, an\nencoding of <code>'utf8'</code> is enforced. If <code>data</code> is a <a href=\"buffer.html\"><code>Buffer</code></a>, <code>TypedArray</code>, or\n<code>DataView</code>, then <code>inputEncoding</code> is ignored.</p>\n<p>This can be called many times with new data as it is streamed.</p>" }, { "textRaw": "verify.verify(object, signature[, signatureEncoding])", "type": "method", "name": "verify", "meta": { "added": [ "v0.1.92" ], "changes": [ { "version": "v8.0.0", "pr-url": "https://github.com/nodejs/node/pull/11705", "description": "Support for RSASSA-PSS and additional options was added." } ] }, "signatures": [ { "return": { "textRaw": "Returns: {boolean} `true` or `false` depending on the validity of the signature for the data and public key.", "name": "return", "type": "boolean", "desc": "`true` or `false` depending on the validity of the signature for the data and public key." }, "params": [ { "textRaw": "`object` {string | Object}", "name": "object", "type": "string | Object" }, { "textRaw": "`signature` {string | Buffer | TypedArray | DataView}", "name": "signature", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`signatureEncoding` {string} The [encoding][] of the `signature` string.", "name": "signatureEncoding", "type": "string", "desc": "The [encoding][] of the `signature` string.", "optional": true } ] } ], "desc": "<p>Verifies the provided data using the given <code>object</code> and <code>signature</code>.\nThe <code>object</code> argument can be either a string containing a PEM encoded object,\nwhich can be an RSA public key, a DSA public key, or an X.509 certificate,\nor an object with one or more of the following properties:</p>\n<ul>\n<li>\n<p><code>key</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type\" class=\"type\"><string></a> - PEM encoded public key (required)</p>\n</li>\n<li>\n<p><code>padding</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><integer></a> - Optional padding value for RSA, one of the following:</p>\n<ul>\n<li><code>crypto.constants.RSA_PKCS1_PADDING</code> (default)</li>\n<li><code>crypto.constants.RSA_PKCS1_PSS_PADDING</code></li>\n</ul>\n<p>Note that <code>RSA_PKCS1_PSS_PADDING</code> will use MGF1 with the same hash function\nused to verify the message as specified in section 3.1 of <a href=\"https://www.rfc-editor.org/rfc/rfc4055.txt\">RFC 4055</a>.</p>\n</li>\n<li>\n<p><code>saltLength</code>: <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type\" class=\"type\"><integer></a> - salt length for when padding is\n<code>RSA_PKCS1_PSS_PADDING</code>. The special value\n<code>crypto.constants.RSA_PSS_SALTLEN_DIGEST</code> sets the salt length to the digest\nsize, <code>crypto.constants.RSA_PSS_SALTLEN_AUTO</code> (default) causes it to be\ndetermined automatically.</p>\n</li>\n</ul>\n<p>The <code>signature</code> argument is the previously calculated signature for the data, in\nthe <code>signatureEncoding</code>.\nIf a <code>signatureEncoding</code> is specified, the <code>signature</code> is expected to be a\nstring; otherwise <code>signature</code> is expected to be a <a href=\"buffer.html\"><code>Buffer</code></a>,\n<code>TypedArray</code>, or <code>DataView</code>.</p>\n<p>The <code>verify</code> object can not be used again after <code>verify.verify()</code> has been\ncalled. Multiple calls to <code>verify.verify()</code> will result in an error being\nthrown.</p>" } ] } ], "type": "module", "displayName": "Crypto" } ] }