{ "source": "doc/api/crypto.md", "modules": [ { "textRaw": "Crypto", "name": "crypto", "introduced_in": "v0.3.6", "stability": 2, "stabilityText": "Stable", "desc": "
The crypto
module provides cryptographic functionality that includes a set of\nwrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.
Use require('crypto')
to access this module.
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
\n",
"modules": [
{
"textRaw": "Determining if crypto support is unavailable",
"name": "determining_if_crypto_support_is_unavailable",
"desc": "It is possible for Node.js to be built without including support for the\ncrypto
module. In such cases, calling require('crypto')
will result in an\nerror being thrown.
let crypto;\ntry {\n crypto = require('crypto');\n} catch (err) {\n console.log('crypto support is disabled!');\n}\n
\n",
"type": "module",
"displayName": "Determining if crypto support is unavailable"
},
{
"textRaw": "`crypto` module methods and properties",
"name": "`crypto`_module_methods_and_properties",
"properties": [
{
"textRaw": "`constants` Returns: {Object} An object containing commonly used constants for crypto and security related operations. The specific constants currently defined are described in [Crypto Constants][]. ",
"name": "constants",
"meta": {
"added": [
"v6.3.0"
],
"changes": []
},
"desc": "Returns: {Object} 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": []
},
"desc": "The default encoding to use for functions that can take either strings\nor buffers. The default value is 'buffer'
, which makes methods\ndefault to Buffer
objects.
The crypto.DEFAULT_ENCODING
mechanism is provided for backwards compatibility\nwith legacy programs that expect 'latin1'
to be the default encoding.
New applications should expect the default to be 'buffer'
.
This property is deprecated.
\n" }, { "textRaw": "crypto.fips", "name": "fips", "meta": { "added": [ "v6.0.0" ], "deprecated": [ "v10.0.0" ], "changes": [] }, "desc": "Property for checking and controlling whether a FIPS compliant crypto provider\nis currently in use. Setting to true requires a FIPS build of Node.js.
\nThis property is deprecated. Please use crypto.setFips()
and\ncrypto.getFips()
instead.
Creates and returns a Cipher
object that uses the given algorithm
and\npassword
.
The options
argument controls stream behavior and is optional except when a\ncipher in CCM mode is used (e.g. 'aes-128-ccm'
). In that case, the\nauthTagLength
option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength
\noption is not required but can be used to set the length of the authentication\ntag that will be returned by getAuthTag()
and defaults to 16 bytes.
The algorithm
is dependent on OpenSSL, examples are 'aes192'
, etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms
\n(openssl list-cipher-algorithms
for older versions of OpenSSL) will\ndisplay the available cipher algorithms.
The password
is used to derive the cipher key and initialization vector (IV).\nThe value must be either a 'latin1'
encoded string, a Buffer
, a\nTypedArray
, or a DataView
.
The implementation of crypto.createCipher()
derives keys using the OpenSSL\nfunction EVP_BytesToKey
with the digest algorithm set to MD5, one\niteration, and no salt. The lack of salt allows dictionary attacks as the same\npassword always creates the same key. The low iteration count and\nnon-cryptographically secure hash algorithm allow passwords to be tested very\nrapidly.
In line with OpenSSL's recommendation to use a more modern algorithm instead of\nEVP_BytesToKey
it is recommended that developers derive a key and IV on\ntheir own using crypto.scrypt()
and to use crypto.createCipheriv()
\nto create the Cipher
object. Users should not use ciphers with counter mode\n(e.g. CTR, GCM, or CCM) in crypto.createCipher()
. A warning is emitted when\nthey are used in order to avoid the risk of IV reuse that causes\nvulnerabilities. For the case when IV is reused in GCM, see Nonce-Disrespecting\nAdversaries for details.
Creates and returns a Cipher
object, with the given algorithm
, key
and\ninitialization vector (iv
).
The options
argument controls stream behavior and is optional except when a\ncipher in CCM mode is used (e.g. 'aes-128-ccm'
). In that case, the\nauthTagLength
option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength
\noption is not required but can be used to set the length of the authentication\ntag that will be returned by getAuthTag()
and defaults to 16 bytes.
The algorithm
is dependent on OpenSSL, examples are 'aes192'
, etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms
\n(openssl list-cipher-algorithms
for older versions of OpenSSL) will\ndisplay the available cipher algorithms.
The key
is the raw key used by the algorithm
and iv
is an\ninitialization vector. Both arguments must be 'utf8'
encoded strings,\nBuffers, TypedArray
, or DataView
s. If the cipher does not need\nan initialization vector, iv
may be null
.
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.
\n" }, { "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()`][]." } ] }, { "params": [ { "name": "details" } ] } ], "desc": "The crypto.createCredentials()
method is a deprecated function for creating\nand returning a tls.SecureContext
. It should not be used. Replace it with\ntls.createSecureContext()
which has the exact same arguments and return\nvalue.
Returns a tls.SecureContext
, as-if tls.createSecureContext()
had been\ncalled.
Creates and returns a Decipher
object that uses the given algorithm
and\npassword
(key).
The options
argument controls stream behavior and is optional except when a\ncipher in CCM mode is used (e.g. 'aes-128-ccm'
). In that case, the\nauthTagLength
option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode.
The implementation of crypto.createDecipher()
derives keys using the OpenSSL\nfunction EVP_BytesToKey
with the digest algorithm set to MD5, one\niteration, and no salt. The lack of salt allows dictionary attacks as the same\npassword always creates the same key. The low iteration count and\nnon-cryptographically secure hash algorithm allow passwords to be tested very\nrapidly.
In line with OpenSSL's recommendation to use a more modern algorithm instead of\nEVP_BytesToKey
it is recommended that developers derive a key and IV on\ntheir own using crypto.scrypt()
and to use crypto.createDecipheriv()
\nto create the Decipher
object.
Creates and returns a Decipher
object that uses the given algorithm
, key
\nand initialization vector (iv
).
The options
argument controls stream behavior and is optional except when a\ncipher in CCM mode is used (e.g. 'aes-128-ccm'
). In that case, the\nauthTagLength
option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength
\noption is not required but can be used to restrict accepted authentication tags\nto those with the specified length.
The algorithm
is dependent on OpenSSL, examples are 'aes192'
, etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms
\n(openssl list-cipher-algorithms
for older versions of OpenSSL) will\ndisplay the available cipher algorithms.
The key
is the raw key used by the algorithm
and iv
is an\ninitialization vector. Both arguments must be 'utf8'
encoded strings,\nBuffers, TypedArray
, or DataView
s. If the cipher does not need\nan initialization vector, iv
may be null
.
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.
\n" }, { "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": [ { "params": [ { "textRaw": "`prime` {string | Buffer | TypedArray | DataView} ", "name": "prime", "type": "string | Buffer | TypedArray | DataView" }, { "textRaw": "`primeEncoding` {string} ", "name": "primeEncoding", "type": "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} ", "name": "generatorEncoding", "type": "string", "optional": true } ] }, { "params": [ { "name": "prime" }, { "name": "primeEncoding", "optional": true }, { "name": "generator", "optional": true }, { "name": "generatorEncoding", "optional": true } ] } ], "desc": "Creates a DiffieHellman
key exchange object using the supplied prime
and an\noptional specific generator
.
The generator
argument can be a number, string, or Buffer
. If\ngenerator
is not specified, the value 2
is used.
The primeEncoding
and generatorEncoding
arguments can be 'latin1'
,\n'hex'
, or 'base64'
.
If primeEncoding
is specified, prime
is expected to be a string; otherwise\na Buffer
, TypedArray
, or DataView
is expected.
If generatorEncoding
is specified, generator
is expected to be a string;\notherwise a number, Buffer
, TypedArray
, or DataView
is expected.
Creates a DiffieHellman
key exchange object and generates a prime of\nprimeLength
bits using an optional specific numeric generator
.\nIf generator
is not specified, the value 2
is used.
Creates an Elliptic Curve Diffie-Hellman (ECDH
) key exchange object using a\npredefined curve specified by the curveName
string. Use\ncrypto.getCurves()
to obtain a list of available curve names. On recent\nOpenSSL releases, openssl ecparam -list_curves
will also display the name\nand description of each available elliptic curve.
Creates and returns a Hash
object that can be used to generate hash digests\nusing the given algorithm
. Optional options
argument controls stream\nbehavior.
The algorithm
is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha256'
, 'sha512'
, etc.\nOn recent releases of OpenSSL, openssl list -digest-algorithms
\n(openssl list-message-digest-algorithms
for older versions of OpenSSL) will\ndisplay the available digest algorithms.
Example: generating the sha256 sum of a file
\nconst 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 const data = input.read();\n if (data)\n hash.update(data);\n else {\n console.log(`${hash.digest('hex')} ${filename}`);\n }\n});\n
\n"
},
{
"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
}
]
},
{
"params": [
{
"name": "algorithm"
},
{
"name": "key"
},
{
"name": "options",
"optional": true
}
]
}
],
"desc": "Creates and returns an Hmac
object that uses the given algorithm
and key
.\nOptional options
argument controls stream behavior.
The algorithm
is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha256'
, 'sha512'
, etc.\nOn recent releases of OpenSSL, openssl list -digest-algorithms
\n(openssl list-message-digest-algorithms
for older versions of OpenSSL) will\ndisplay the available digest algorithms.
The key
is the HMAC key used to generate the cryptographic HMAC hash.
Example: generating the sha256 HMAC of a file
\nconst 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 const data = input.read();\n if (data)\n hmac.update(data);\n else {\n console.log(`${hmac.digest('hex')} ${filename}`);\n }\n});\n
\n"
},
{
"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
}
]
},
{
"params": [
{
"name": "algorithm"
},
{
"name": "options",
"optional": true
}
]
}
],
"desc": "Creates and returns a Sign
object that uses the given algorithm
.\nUse crypto.getHashes()
to obtain an array of names of the available\nsigning algorithms. Optional options
argument controls the\nstream.Writable
behavior.
Creates and returns a Verify
object that uses the given algorithm.\nUse crypto.getHashes()
to obtain an array of names of the available\nsigning algorithms. Optional options
argument controls the\nstream.Writable
behavior.
Example:
\nconst ciphers = crypto.getCiphers();\nconsole.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]\n
\n"
},
{
"textRaw": "crypto.getCurves()",
"type": "method",
"name": "getCurves",
"meta": {
"added": [
"v2.3.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {string[]} An array with the names of the supported elliptic curves. ",
"name": "return",
"type": "string[]",
"desc": "An array with the names of the supported elliptic curves."
},
"params": []
},
{
"params": []
}
],
"desc": "Example:
\nconst curves = crypto.getCurves();\nconsole.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n
\n"
},
{
"textRaw": "crypto.getDiffieHellman(groupName)",
"type": "method",
"name": "getDiffieHellman",
"meta": {
"added": [
"v0.7.5"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Object} ",
"name": "return",
"type": "Object"
},
"params": [
{
"textRaw": "`groupName` {string} ",
"name": "groupName",
"type": "string"
}
]
},
{
"params": [
{
"name": "groupName"
}
]
}
],
"desc": "Creates a predefined DiffieHellman
key exchange object. The\nsupported groups are: 'modp1'
, 'modp2'
, 'modp5'
(defined in\nRFC 2412, but see Caveats) and 'modp14'
, 'modp15'
,\n'modp16'
, 'modp17'
, 'modp18'
(defined in RFC 3526). The\nreturned object mimics the interface of objects created by\ncrypto.createDiffieHellman()
, but will not allow changing\nthe keys (with diffieHellman.setPublicKey()
for example). The\nadvantage of using this method is that the parties do not have to\ngenerate nor exchange a group modulus beforehand, saving both processor\nand communication time.
Example (obtaining a shared secret):
\nconst 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
\n"
},
{
"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": []
},
{
"params": []
}
],
"desc": "Example:
\nconst hashes = crypto.getHashes();\nconsole.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n
\n"
},
{
"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": []
},
{
"params": []
}
],
"desc": "Example:
\nconst hashes = crypto.getHashes();\nconsole.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n
\n"
},
{
"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} ",
"options": [
{
"textRaw": "`err` {Error} ",
"name": "err",
"type": "Error"
},
{
"textRaw": "`derivedKey` {Buffer} ",
"name": "derivedKey",
"type": "Buffer"
}
],
"name": "callback",
"type": "Function"
}
]
},
{
"params": [
{
"name": "password"
},
{
"name": "salt"
},
{
"name": "iterations"
},
{
"name": "keylen"
},
{
"name": "digest"
},
{
"name": "callback"
}
]
}
],
"desc": "Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)\nimplementation. A selected HMAC digest algorithm specified by digest
is\napplied to derive a key of the requested byte length (keylen
) from the\npassword
, salt
and iterations
.
The supplied callback
function is called with two arguments: err
and\nderivedKey
. If an error occurs while deriving the key, err
will be set;\notherwise err
will be null
. By default, the successfully generated\nderivedKey
will be passed to the callback as a Buffer
. An error will be\nthrown if any of the input arguments specify invalid values or types.
The iterations
argument must be a number set as high as possible. The\nhigher the number of iterations, the more secure the derived key will be,\nbut will take a longer amount of time to complete.
The salt
should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.
Example:
\nconst 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
\nThe crypto.DEFAULT_ENCODING
property can be used to change the way the\nderivedKey
is passed to the callback. This property, however, has been\ndeprecated and use should be avoided.
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
\nAn array of supported digest functions can be retrieved using\ncrypto.getHashes()
.
Note that this API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications, see the\nUV_THREADPOOL_SIZE
documentation for more information.
Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)\nimplementation. A selected HMAC digest algorithm specified by digest
is\napplied to derive a key of the requested byte length (keylen
) from the\npassword
, salt
and iterations
.
If an error occurs an Error
will be thrown, otherwise the derived key will be\nreturned as a Buffer
.
The iterations
argument must be a number set as high as possible. The\nhigher the number of iterations, the more secure the derived key will be,\nbut will take a longer amount of time to complete.
The salt
should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.
Example:
\nconst crypto = require('crypto');\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');\nconsole.log(key.toString('hex')); // '3745e48...08d59ae'\n
\nThe crypto.DEFAULT_ENCODING
property may be used to change the way the\nderivedKey
is returned. This property, however, is deprecated and use\nshould be avoided.
const crypto = require('crypto');\ncrypto.DEFAULT_ENCODING = 'hex';\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');\nconsole.log(key); // '3745e48...aa39b34'\n
\nAn array of supported digest functions can be retrieved using\ncrypto.getHashes()
.
Decrypts buffer
with privateKey
.
privateKey
can be an object or a string. If privateKey
is a string, it is\ntreated as the key with no passphrase and will use RSA_PKCS1_OAEP_PADDING
.
Encrypts buffer
with privateKey
.
privateKey
can be an object or a string. If privateKey
is a string, it is\ntreated as the key with no passphrase and will use RSA_PKCS1_PADDING
.
Decrypts buffer
with key
.
key
can be an object or a string. If key
is a string, it is treated as\nthe key with no passphrase and will use RSA_PKCS1_PADDING
.
Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.
\n" }, { "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} ", "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`." } ], "name": "key", "type": "Object | string" }, { "textRaw": "`buffer` {Buffer | TypedArray | DataView} ", "name": "buffer", "type": "Buffer | TypedArray | DataView" } ] }, { "params": [ { "name": "key" }, { "name": "buffer" } ] } ], "desc": "Encrypts the content of buffer
with key
and returns a new\nBuffer
with encrypted content.
key
can be an object or a string. If key
is a string, it is treated as\nthe key with no passphrase and will use RSA_PKCS1_OAEP_PADDING
.
Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.
\n" }, { "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} ", "options": [ { "textRaw": "`err` {Error} ", "name": "err", "type": "Error" }, { "textRaw": "`buf` {Buffer} ", "name": "buf", "type": "Buffer" } ], "name": "callback", "type": "Function", "optional": true } ] }, { "params": [ { "name": "size" }, { "name": "callback", "optional": true } ] } ], "desc": "Generates cryptographically strong pseudo-random data. The size
argument\nis a number indicating the number of bytes to generate.
If a callback
function is provided, the bytes are generated asynchronously\nand the callback
function is invoked with two arguments: err
and buf
.\nIf an error occurs, err
will be an Error
object; otherwise it is null
. The\nbuf
argument is a Buffer
containing the generated bytes.
// Asynchronous\nconst 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
\nIf the callback
function is not provided, the random bytes are generated\nsynchronously and returned as a Buffer
. An error will be thrown if\nthere is a problem generating the bytes.
// Synchronous\nconst buf = crypto.randomBytes(256);\nconsole.log(\n `${buf.length} bytes of random data: ${buf.toString('hex')}`);\n
\nThe crypto.randomBytes()
method will not complete until there is\nsufficient entropy available.\nThis should normally never take longer than a few milliseconds. The only time\nwhen generating the random bytes may conceivably block for a longer period of\ntime is right after boot, when the whole system is still low on entropy.
Note that this API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications, see the\nUV_THREADPOOL_SIZE
documentation for more information.
The asynchronous version of crypto.randomBytes()
is carried out in a single\nthreadpool request. To minimize threadpool task length variation, partition\nlarge randomBytes
requests when doing so as part of fulfilling a client\nrequest.
Synchronous version of crypto.randomFill()
.
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
\nAny TypedArray
or DataView
instance may be passed as buffer
.
const a = new Uint32Array(10);\nconsole.log(crypto.randomFillSync(a).toString('hex'));\n\nconst b = new Float64Array(10);\nconsole.log(crypto.randomFillSync(b).toString('hex'));\n\nconst c = new DataView(new ArrayBuffer(10));\nconsole.log(crypto.randomFillSync(c).toString('hex'));\n
\n"
},
{
"textRaw": "crypto.randomFill(buffer[, offset][, size], callback)",
"type": "method",
"name": "randomFill",
"meta": {
"added": [
"v7.10.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) {}`."
}
]
},
{
"params": [
{
"name": "buffer"
},
{
"name": "offset",
"optional": true
},
{
"name": "size",
"optional": true
},
{
"name": "callback"
}
]
}
],
"desc": "This function is similar to crypto.randomBytes()
but requires the first\nargument to be a Buffer
that will be filled. It also\nrequires that a callback is passed in.
If the callback
function is not provided, an error will be thrown.
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
\nAny TypedArray
or DataView
instance may be passed as buffer
.
const a = new Uint32Array(10);\ncrypto.randomFill(a, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n\nconst b = new Float64Array(10);\ncrypto.randomFill(b, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n\nconst c = new DataView(new ArrayBuffer(10));\ncrypto.randomFill(c, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n
\nNote that this API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications, see the\nUV_THREADPOOL_SIZE
documentation for more information.
The asynchronous version of crypto.randomFill()
is carried out in a single\nthreadpool request. To minimize threadpool task length variation, partition\nlarge randomFill
requests when doing so as part of fulfilling a client\nrequest.
Provides an asynchronous scrypt implementation. Scrypt is a password-based\nkey derivation function that is designed to be expensive computationally and\nmemory-wise in order to make brute-force attacks unrewarding.
\nThe salt
should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.
The callback
function is called with two arguments: err
and derivedKey
.\nerr
is an exception object when key derivation fails, otherwise err
is\nnull
. derivedKey
is passed to the callback as a Buffer
.
An exception is thrown when any of the input arguments specify invalid values\nor types.
\nconst 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
\n"
},
{
"textRaw": "crypto.scryptSync(password, salt, keylen[, options])",
"type": "method",
"name": "scryptSync",
"meta": {
"added": [
"v10.5.0"
],
"changes": []
},
"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} ",
"options": [
{
"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": "`r` {number} Block size parameter. **Default:** `8`. ",
"name": "r",
"type": "number",
"default": "`8`",
"desc": "Block size parameter."
},
{
"textRaw": "`p` {number} Parallelization parameter. **Default:** `1`. ",
"name": "p",
"type": "number",
"default": "`1`",
"desc": "Parallelization parameter."
},
{
"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`."
}
],
"name": "options",
"type": "Object",
"optional": true
}
]
},
{
"params": [
{
"name": "password"
},
{
"name": "salt"
},
{
"name": "keylen"
},
{
"name": "options",
"optional": true
}
]
}
],
"desc": "Provides a synchronous scrypt implementation. Scrypt is a password-based\nkey derivation function that is designed to be expensive computationally and\nmemory-wise in order to make brute-force attacks unrewarding.
\nThe salt
should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.
An exception is thrown when key derivation fails, otherwise the derived key is\nreturned as a Buffer
.
An exception is thrown when any of the input arguments specify invalid values\nor types.
\nconst 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
\n"
},
{
"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
}
]
},
{
"params": [
{
"name": "engine"
},
{
"name": "flags",
"optional": true
}
]
}
],
"desc": "Load and set the engine
for some or all OpenSSL functions (selected by flags).
engine
could be either an id or a path to the engine's shared library.
The optional flags
argument uses ENGINE_METHOD_ALL
by default. The flags
\nis a bit field taking one of or a mix of the following flags (defined in\ncrypto.constants
):
crypto.constants.ENGINE_METHOD_RSA
crypto.constants.ENGINE_METHOD_DSA
crypto.constants.ENGINE_METHOD_DH
crypto.constants.ENGINE_METHOD_RAND
crypto.constants.ENGINE_METHOD_EC
crypto.constants.ENGINE_METHOD_CIPHERS
crypto.constants.ENGINE_METHOD_DIGESTS
crypto.constants.ENGINE_METHOD_PKEY_METHS
crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS
crypto.constants.ENGINE_METHOD_ALL
crypto.constants.ENGINE_METHOD_NONE
The flags below are deprecated in OpenSSL-1.1.0.
\ncrypto.constants.ENGINE_METHOD_ECDH
crypto.constants.ENGINE_METHOD_ECDSA
crypto.constants.ENGINE_METHOD_STORE
Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.\nThrows an error if FIPS mode is not available.
\n" }, { "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" } ] }, { "params": [ { "name": "a" }, { "name": "b" } ] } ], "desc": "This function is based on a constant-time algorithm.\nReturns true if a
is equal to b
, without leaking timing information that\nwould allow an attacker to guess one of the values. This is suitable for\ncomparing HMAC digests or secret values like authentication cookies or\ncapability urls.
a
and b
must both be Buffer
s, TypedArray
s, or DataView
s, and they\nmust have the same length.
Use of crypto.timingSafeEqual
does not guarantee that the surrounding code\nis timing-safe. Care should be taken to ensure that the surrounding code does\nnot introduce timing vulnerabilities.
The Crypto module was added to Node.js before there was the concept of a\nunified Stream API, and before there were Buffer
objects for handling\nbinary data. As such, the many of the crypto
defined classes have methods not\ntypically found on other Node.js classes that implement the streams\nAPI (e.g. update()
, final()
, or digest()
). Also, many methods accepted\nand returned 'latin1'
encoded strings by default rather than Buffer
s. This\ndefault was changed after Node.js v0.8 to use Buffer
objects by default\ninstead.
Usage of ECDH
with non-dynamically generated key pairs has been simplified.\nNow, ecdh.setPrivateKey()
can be called with a preselected private key\nand the associated public point (key) will be computed and stored in the object.\nThis allows code to only store and provide the private part of the EC key pair.\necdh.setPrivateKey()
now also validates that the private key is valid for\nthe selected curve.
The ecdh.setPublicKey()
method is now deprecated as its inclusion in the\nAPI is not useful. Either a previously stored private key should be set, which\nautomatically generates the associated public key, or ecdh.generateKeys()
\nshould be called. The main drawback of using ecdh.setPublicKey()
is that\nit can be used to put the ECDH key pair into an inconsistent state.
The crypto
module still supports some algorithms which are already\ncompromised and are not currently recommended for use. The API also allows\nthe use of ciphers and hashes with a small key size that are considered to be\ntoo weak for safe use.
Users should take full responsibility for selecting the crypto\nalgorithm and key size according to their security requirements.
\nBased on the recommendations of NIST SP 800-131A:
\nmodp1
, modp2
and modp5
have a key size\nsmaller than 2048 bits and are not recommended.See the reference for other recommendations and details.
\n", "type": "module", "displayName": "Support for weak or compromised algorithms" }, { "textRaw": "CCM mode", "name": "ccm_mode", "desc": "CCM is one of the two supported AEAD algorithms. Applications which use this\nmode must adhere to certain restrictions when using the cipher API:
\nauthTagLength
option and must be one of 4, 6, 8, 10, 12, 14 or\n16 bytes.N
must be between 7 and 13\nbytes (7 ≤ N ≤ 13
).2 ** (8 * (15 - N))
bytes.setAuthTag()
before\nspecifying additional authenticated data or calling update()
.\nOtherwise, decryption will fail and final()
will throw an error in\ncompliance with section 2.6 of RFC 3610.write(data)
, end(data)
or pipe()
in CCM\nmode might fail as CCM cannot handle more than one chunk of data per instance.setAAD()
via the plaintextLength
\noption. This is not necessary if no AAD is used.update()
can only be called\nonce.update()
is sufficient to encrypt/decrypt the message,\napplications must call final()
to compute or verify the\nauthentication tag.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
\n",
"type": "module",
"displayName": "CCM mode"
}
],
"type": "module",
"displayName": "Notes"
},
{
"textRaw": "Crypto Constants",
"name": "crypto_constants",
"desc": "The following constants exported by crypto.constants
apply to various uses of\nthe crypto
, tls
, and https
modules and are generally specific to OpenSSL.
Constant | \nDescription | \n
---|---|
SSL_OP_ALL | \n Applies multiple bug workarounds within OpenSSL. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for\n detail. | \n
SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION | \n Allows legacy insecure renegotiation between OpenSSL and unpatched\n clients or servers. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. | \n
SSL_OP_CIPHER_SERVER_PREFERENCE | \n Attempts to use the server's preferences instead of the client's when\n selecting a cipher. Behavior depends on protocol version. See\n https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. | \n
SSL_OP_CISCO_ANYCONNECT | \n Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. | \n
SSL_OP_COOKIE_EXCHANGE | \n Instructs OpenSSL to turn on cookie exchange. | \n
SSL_OP_CRYPTOPRO_TLSEXT_BUG | \n Instructs OpenSSL to add server-hello extension from an early version\n of the cryptopro draft. | \n
SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS | \n Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability\n workaround added in OpenSSL 0.9.6d. | \n
SSL_OP_EPHEMERAL_RSA | \n Instructs OpenSSL to always use the tmp_rsa key when performing RSA\n operations. | \n
SSL_OP_LEGACY_SERVER_CONNECT | \n Allows initial connection to servers that do not support RI. | \n
SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER | \n \n |
SSL_OP_MICROSOFT_SESS_ID_BUG | \n \n |
SSL_OP_MSIE_SSLV2_RSA_PADDING | \n Instructs OpenSSL to disable the workaround for a man-in-the-middle\n protocol-version vulnerability in the SSL 2.0 server implementation. | \n
SSL_OP_NETSCAPE_CA_DN_BUG | \n \n |
SSL_OP_NETSCAPE_CHALLENGE_BUG | \n \n |
SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG | \n \n |
SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG | \n \n |
SSL_OP_NO_COMPRESSION | \n Instructs OpenSSL to disable support for SSL/TLS compression. | \n
SSL_OP_NO_QUERY_MTU | \n \n |
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION | \n Instructs OpenSSL to always start a new session when performing\n renegotiation. | \n
SSL_OP_NO_SSLv2 | \n Instructs OpenSSL to turn off SSL v2 | \n
SSL_OP_NO_SSLv3 | \n Instructs OpenSSL to turn off SSL v3 | \n
SSL_OP_NO_TICKET | \n Instructs OpenSSL to disable use of RFC4507bis tickets. | \n
SSL_OP_NO_TLSv1 | \n Instructs OpenSSL to turn off TLS v1 | \n
SSL_OP_NO_TLSv1_1 | \n Instructs OpenSSL to turn off TLS v1.1 | \n
SSL_OP_NO_TLSv1_2 | \n Instructs OpenSSL to turn off TLS v1.2 | \nSSL_OP_PKCS1_CHECK_1 | \n \n \n |
SSL_OP_PKCS1_CHECK_2 | \n \n |
SSL_OP_SINGLE_DH_USE | \n Instructs OpenSSL to always create a new key when using\n temporary/ephemeral DH parameters. | \n
SSL_OP_SINGLE_ECDH_USE | \n Instructs OpenSSL to always create a new key when using\n temporary/ephemeral ECDH parameters. | \nSSL_OP_SSLEAY_080_CLIENT_DH_BUG | \n \n \n |
SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG | \n \n |
SSL_OP_TLS_BLOCK_PADDING_BUG | \n \n |
SSL_OP_TLS_D5_BUG | \n \n |
SSL_OP_TLS_ROLLBACK_BUG | \n Instructs OpenSSL to disable version rollback attack detection. | \n
Constant | \nDescription | \n
---|---|
ENGINE_METHOD_RSA | \n Limit engine usage to RSA | \n
ENGINE_METHOD_DSA | \n Limit engine usage to DSA | \n
ENGINE_METHOD_DH | \n Limit engine usage to DH | \n
ENGINE_METHOD_RAND | \n Limit engine usage to RAND | \n
ENGINE_METHOD_EC | \n Limit engine usage to EC | \n
ENGINE_METHOD_CIPHERS | \n Limit engine usage to CIPHERS | \n
ENGINE_METHOD_DIGESTS | \n Limit engine usage to DIGESTS | \n
ENGINE_METHOD_PKEY_METHS | \n Limit engine usage to PKEY_METHDS | \n
ENGINE_METHOD_PKEY_ASN1_METHS | \n Limit engine usage to PKEY_ASN1_METHS | \n
ENGINE_METHOD_ALL | \n \n |
ENGINE_METHOD_NONE | \n \n |
Constant | \nDescription | \n
---|---|
DH_CHECK_P_NOT_SAFE_PRIME | \n \n |
DH_CHECK_P_NOT_PRIME | \n \n |
DH_UNABLE_TO_CHECK_GENERATOR | \n \n |
DH_NOT_SUITABLE_GENERATOR | \n \n |
ALPN_ENABLED | \n \n |
RSA_PKCS1_PADDING | \n \n |
RSA_SSLV23_PADDING | \n \n |
RSA_NO_PADDING | \n \n |
RSA_PKCS1_OAEP_PADDING | \n \n |
RSA_X931_PADDING | \n \n |
RSA_PKCS1_PSS_PADDING | \n \n |
RSA_PSS_SALTLEN_DIGEST | \n Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size\n when signing or verifying. | \n
RSA_PSS_SALTLEN_MAX_SIGN | \n Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum\n permissible value when signing data. | \n
RSA_PSS_SALTLEN_AUTO | \n Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined\n automatically when verifying a signature. | \n
POINT_CONVERSION_COMPRESSED | \n \n |
POINT_CONVERSION_UNCOMPRESSED | \n \n |
POINT_CONVERSION_HYBRID | \n \n |
Constant | \nDescription | \n
---|---|
defaultCoreCipherList | \n Specifies the built-in default cipher list used by Node.js. | \n
defaultCipherList | \n Specifies the active default cipher list used by the current Node.js\n process. | \n
SPKAC is a Certificate Signing Request mechanism originally implemented by\nNetscape and was specified formally as part of HTML5's keygen
element.
Note that <keygen>
is deprecated since HTML 5.2 and new projects\nshould not use this element anymore.
The crypto
module provides the Certificate
class for working with SPKAC\ndata. The most common usage is handling output generated by the HTML5\n<keygen>
element. Node.js uses OpenSSL's SPKAC implementation internally.
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
\n"
},
{
"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} ",
"name": "encoding",
"type": "string",
"optional": true
}
]
},
{
"params": [
{
"name": "spkac"
},
{
"name": "encoding",
"optional": true
}
]
}
],
"desc": "const { Certificate } = require('crypto');\nconst spkac = getSpkacSomehow();\nconst publicKey = Certificate.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
\n"
},
{
"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"
}
]
},
{
"params": [
{
"name": "spkac"
}
]
}
],
"desc": "const { Certificate } = require('crypto');\nconst spkac = getSpkacSomehow();\nconsole.log(Certificate.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
\n"
}
],
"modules": [
{
"textRaw": "Legacy API",
"name": "legacy_api",
"desc": "As a still supported legacy interface, it is possible (but not recommended) to\ncreate new instances of the crypto.Certificate
class as illustrated in the\nexamples below.
Instances of the Certificate
class can be created using the new
keyword\nor by calling crypto.Certificate()
as a function:
const crypto = require('crypto');\n\nconst cert1 = new crypto.Certificate();\nconst cert2 = crypto.Certificate();\n
\n",
"signatures": [
{
"params": []
}
]
}
],
"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"
}
]
},
{
"params": [
{
"name": "spkac"
}
]
}
],
"desc": "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
\n"
},
{
"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"
}
]
},
{
"params": [
{
"name": "spkac"
}
]
}
],
"desc": "const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconst publicKey = cert.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
\n"
},
{
"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"
}
]
},
{
"params": [
{
"name": "spkac"
}
]
}
],
"desc": "const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
\n"
}
],
"type": "module",
"displayName": "Legacy API"
}
]
},
{
"textRaw": "Class: Cipher",
"type": "class",
"name": "Cipher",
"meta": {
"added": [
"v0.1.94"
],
"changes": []
},
"desc": "Instances of the Cipher
class are used to encrypt data. The class can be\nused in one of two ways:
cipher.update()
and cipher.final()
methods to produce\nthe encrypted data.The crypto.createCipher()
or crypto.createCipheriv()
methods are\nused to create Cipher
instances. Cipher
objects are not to be created\ndirectly using the new
keyword.
Example: Using Cipher
objects as streams:
const crypto = require('crypto');\nconst cipher = crypto.createCipher('aes192', 'a password');\n\nlet encrypted = '';\ncipher.on('readable', () => {\n const data = cipher.read();\n if (data)\n encrypted += data.toString('hex');\n});\ncipher.on('end', () => {\n console.log(encrypted);\n // Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504\n});\n\ncipher.write('some clear text data');\ncipher.end();\n
\nExample: Using Cipher
and piped streams:
const crypto = require('crypto');\nconst fs = require('fs');\nconst cipher = crypto.createCipher('aes192', 'a password');\n\nconst input = fs.createReadStream('test.js');\nconst output = fs.createWriteStream('test.enc');\n\ninput.pipe(cipher).pipe(output);\n
\nExample: Using the cipher.update()
and cipher.final()
methods:
const crypto = require('crypto');\nconst cipher = crypto.createCipher('aes192', 'a password');\n\nlet encrypted = cipher.update('some clear text data', 'utf8', 'hex');\nencrypted += cipher.final('hex');\nconsole.log(encrypted);\n// Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504\n
\n",
"methods": [
{
"textRaw": "cipher.final([outputEncoding])",
"type": "method",
"name": "final",
"meta": {
"added": [
"v0.1.94"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Buffer | string} Any remaining enciphered contents. If `outputEncoding` is one of `'latin1'`, `'base64'` or `'hex'`, 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 one of `'latin1'`, `'base64'` or `'hex'`, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned."
},
"params": [
{
"textRaw": "`outputEncoding` {string} ",
"name": "outputEncoding",
"type": "string",
"optional": true
}
]
},
{
"params": [
{
"name": "outputEncoding",
"optional": true
}
]
}
],
"desc": "Once the cipher.final()
method has been called, the Cipher
object can no\nlonger be used to encrypt data. Attempts to call cipher.final()
more than\nonce will result in an error being thrown.
When using an authenticated encryption mode (only GCM
and CCM
are currently\nsupported), the cipher.setAAD()
method sets the value used for the\nadditional authenticated data (AAD) input parameter.
The options
argument is optional for GCM
. When using CCM
, the\nplaintextLength
option must be specified and its value must match the length\nof the plaintext in bytes. See CCM mode.
The cipher.setAAD()
method must be called before cipher.update()
.
The cipher.getAuthTag()
method should only be called after encryption has\nbeen completed using the cipher.final()
method.
When using block encryption algorithms, the Cipher
class will automatically\nadd padding to the input data to the appropriate block size. To disable the\ndefault padding call cipher.setAutoPadding(false)
.
When autoPadding
is false
, the length of the entire input data must be a\nmultiple of the cipher's block size or cipher.final()
will throw an error.\nDisabling automatic padding is useful for non-standard padding, for instance\nusing 0x0
instead of PKCS padding.
The cipher.setAutoPadding()
method must be called before\ncipher.final()
.
Updates the cipher with data
. If the inputEncoding
argument is given,\nits value must be one of 'utf8'
, 'ascii'
, or 'latin1'
and the data
\nargument is a string using the specified encoding. If the inputEncoding
\nargument is not given, data
must be a Buffer
, TypedArray
, or\nDataView
. If data
is a Buffer
, TypedArray
, or DataView
, then\ninputEncoding
is ignored.
The outputEncoding
specifies the output format of the enciphered\ndata, and can be 'latin1'
, 'base64'
or 'hex'
. If the outputEncoding
\nis specified, a string using the specified encoding is returned. If no\noutputEncoding
is provided, a Buffer
is returned.
The cipher.update()
method can be called multiple times with new data until\ncipher.final()
is called. Calling cipher.update()
after\ncipher.final()
will result in an error being thrown.
Instances of the Decipher
class are used to decrypt data. The class can be\nused in one of two ways:
decipher.update()
and decipher.final()
methods to\nproduce the unencrypted data.The crypto.createDecipher()
or crypto.createDecipheriv()
methods are\nused to create Decipher
instances. Decipher
objects are not to be created\ndirectly using the new
keyword.
Example: Using Decipher
objects as streams:
const crypto = require('crypto');\nconst decipher = crypto.createDecipher('aes192', 'a password');\n\nlet decrypted = '';\ndecipher.on('readable', () => {\n const data = decipher.read();\n if (data)\n decrypted += data.toString('utf8');\n});\ndecipher.on('end', () => {\n console.log(decrypted);\n // Prints: some clear text data\n});\n\nconst encrypted =\n 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';\ndecipher.write(encrypted, 'hex');\ndecipher.end();\n
\nExample: Using Decipher
and piped streams:
const crypto = require('crypto');\nconst fs = require('fs');\nconst decipher = crypto.createDecipher('aes192', 'a password');\n\nconst input = fs.createReadStream('test.enc');\nconst output = fs.createWriteStream('test.js');\n\ninput.pipe(decipher).pipe(output);\n
\nExample: Using the decipher.update()
and decipher.final()
methods:
const crypto = require('crypto');\nconst decipher = crypto.createDecipher('aes192', 'a password');\n\nconst encrypted =\n 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';\nlet decrypted = decipher.update(encrypted, 'hex', 'utf8');\ndecrypted += decipher.final('utf8');\nconsole.log(decrypted);\n// Prints: some clear text data\n
\n",
"methods": [
{
"textRaw": "decipher.final([outputEncoding])",
"type": "method",
"name": "final",
"meta": {
"added": [
"v0.1.94"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Buffer | string} Any remaining deciphered contents. If `outputEncoding` is one of `'latin1'`, `'ascii'` or `'utf8'`, 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 one of `'latin1'`, `'ascii'` or `'utf8'`, a string is returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned."
},
"params": [
{
"textRaw": "`outputEncoding` {string} ",
"name": "outputEncoding",
"type": "string",
"optional": true
}
]
},
{
"params": [
{
"name": "outputEncoding",
"optional": true
}
]
}
],
"desc": "Once the decipher.final()
method has been called, the Decipher
object can\nno longer be used to decrypt data. Attempts to call decipher.final()
more\nthan once will result in an error being thrown.
When using an authenticated encryption mode (only GCM
and CCM
are currently\nsupported), the decipher.setAAD()
method sets the value used for the\nadditional authenticated data (AAD) input parameter.
The options
argument is optional for GCM
. When using CCM
, the\nplaintextLength
option must be specified and its value must match the length\nof the plaintext in bytes. See CCM mode.
The decipher.setAAD()
method must be called before decipher.update()
.
When using an authenticated encryption mode (only GCM
and CCM
are currently\nsupported), the decipher.setAuthTag()
method is used to pass in the\nreceived authentication tag. If no tag is provided, or if the cipher text\nhas been tampered with, decipher.final()
will throw, indicating that the\ncipher text should be discarded due to failed authentication.
Note that this Node.js version does not verify the length of GCM authentication\ntags. Such a check must 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 NIST SP 800-38D.
\nThe decipher.setAuthTag()
method must be called before\ndecipher.final()
.
When data has been encrypted without standard block padding, calling\ndecipher.setAutoPadding(false)
will disable automatic padding to prevent\ndecipher.final()
from checking for and removing padding.
Turning auto padding off will only work if the input data's length is a\nmultiple of the ciphers block size.
\nThe decipher.setAutoPadding()
method must be called before\ndecipher.final()
.
Updates the decipher with data
. If the inputEncoding
argument is given,\nits value must be one of 'latin1'
, 'base64'
, or 'hex'
and the data
\nargument is a string using the specified encoding. If the inputEncoding
\nargument is not given, data
must be a Buffer
. If data
is a\nBuffer
then inputEncoding
is ignored.
The outputEncoding
specifies the output format of the enciphered\ndata, and can be 'latin1'
, 'ascii'
or 'utf8'
. If the outputEncoding
\nis specified, a string using the specified encoding is returned. If no\noutputEncoding
is provided, a Buffer
is returned.
The decipher.update()
method can be called multiple times with new data until\ndecipher.final()
is called. Calling decipher.update()
after\ndecipher.final()
will result in an error being thrown.
The DiffieHellman
class is a utility for creating Diffie-Hellman key\nexchanges.
Instances of the DiffieHellman
class can be created using the\ncrypto.createDiffieHellman()
function.
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
\n",
"methods": [
{
"textRaw": "diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])",
"type": "method",
"name": "computeSecret",
"meta": {
"added": [
"v0.5.0"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Buffer | string} ",
"name": "return",
"type": "Buffer | string"
},
"params": [
{
"textRaw": "`otherPublicKey` {string | Buffer | TypedArray | DataView} ",
"name": "otherPublicKey",
"type": "string | Buffer | TypedArray | DataView"
},
{
"textRaw": "`inputEncoding` {string} ",
"name": "inputEncoding",
"type": "string",
"optional": true
},
{
"textRaw": "`outputEncoding` {string} ",
"name": "outputEncoding",
"type": "string",
"optional": true
}
]
},
{
"params": [
{
"name": "otherPublicKey"
},
{
"name": "inputEncoding",
"optional": true
},
{
"name": "outputEncoding",
"optional": true
}
]
}
],
"desc": "Computes the shared secret using otherPublicKey
as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using the specified inputEncoding
, and secret is\nencoded using specified outputEncoding
. Encodings can be\n'latin1'
, 'hex'
, or 'base64'
. If the inputEncoding
is not\nprovided, otherPublicKey
is expected to be a Buffer
,\nTypedArray
, or DataView
.
If outputEncoding
is given a string is returned; otherwise, a\nBuffer
is returned.
Generates private and public Diffie-Hellman key values, and returns\nthe public key in the specified encoding
. This key should be\ntransferred to the other party. Encoding can be 'latin1'
, 'hex'
,\nor 'base64'
. If encoding
is provided a string is returned; otherwise a\nBuffer
is returned.
Returns the Diffie-Hellman generator in the specified encoding
, which can\nbe 'latin1'
, 'hex'
, or 'base64'
. If encoding
is provided a string is\nreturned; otherwise a Buffer
is returned.
Returns the Diffie-Hellman prime in the specified encoding
, which can\nbe 'latin1'
, 'hex'
, or 'base64'
. If encoding
is provided a string is\nreturned; otherwise a Buffer
is returned.
Returns the Diffie-Hellman private key in the specified encoding
,\nwhich can be 'latin1'
, 'hex'
, or 'base64'
. If encoding
is provided a\nstring is returned; otherwise a Buffer
is returned.
Returns the Diffie-Hellman public key in the specified encoding
, which\ncan be 'latin1'
, 'hex'
, or 'base64'
. If encoding
is provided a\nstring is returned; otherwise a Buffer
is returned.
Sets the Diffie-Hellman private key. If the encoding
argument is provided\nand is either 'latin1'
, 'hex'
, or 'base64'
, privateKey
is expected\nto be a string. If no encoding
is provided, privateKey
is expected\nto be a Buffer
, TypedArray
, or DataView
.
Sets the Diffie-Hellman public key. If the encoding
argument is provided\nand is either 'latin1'
, 'hex'
or 'base64'
, publicKey
is expected\nto be a string. If no encoding
is provided, publicKey
is expected\nto be a Buffer
, TypedArray
, or DataView
.
A bit field containing any warnings and/or errors resulting from a check\nperformed during initialization of the DiffieHellman
object.
The following values are valid for this property (as defined in constants
\nmodule):
DH_CHECK_P_NOT_SAFE_PRIME
DH_CHECK_P_NOT_PRIME
DH_UNABLE_TO_CHECK_GENERATOR
DH_NOT_SUITABLE_GENERATOR
The ECDH
class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)\nkey exchanges.
Instances of the ECDH
class can be created using the\ncrypto.createECDH()
function.
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
\n",
"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} ",
"name": "inputEncoding",
"type": "string",
"optional": true
},
{
"textRaw": "`outputEncoding` {string} ",
"name": "outputEncoding",
"type": "string",
"optional": true
},
{
"textRaw": "`format` {string} **Default:** `'uncompressed'` ",
"name": "format",
"type": "string",
"default": "`'uncompressed'`",
"optional": true
}
]
},
{
"params": [
{
"name": "key"
},
{
"name": "curve"
},
{
"name": "inputEncoding",
"optional": true
},
{
"name": "outputEncoding",
"optional": true
},
{
"name": "format",
"optional": true
}
]
}
],
"desc": "Converts the EC Diffie-Hellman public key specified by key
and curve
to the\nformat specified by format
. The format
argument specifies point encoding\nand can be 'compressed'
, 'uncompressed'
or 'hybrid'
. The supplied key is\ninterpreted using the specified inputEncoding
, and the returned key is encoded\nusing the specified outputEncoding
. Encodings can be 'latin1'
, 'hex'
,\nor 'base64'
.
Use crypto.getCurves()
to obtain a list of available curve names.\nOn recent OpenSSL releases, openssl ecparam -list_curves
will also display\nthe name and description of each available elliptic curve.
If format
is not specified the point will be returned in 'uncompressed'
\nformat.
If the inputEncoding
is not provided, key
is expected to be a Buffer
,\nTypedArray
, or DataView
.
Example (uncompressing a key):
\nconst { ECDH } = require('crypto');\n\nconst ecdh = ECDH('secp256k1');\necdh.generateKeys();\n\nconst compressedKey = ecdh.getPublicKey('hex', 'compressed');\n\nconst uncompressedKey = ECDH.convertKey(compressedKey,\n 'secp256k1',\n 'hex',\n 'hex',\n 'uncompressed');\n\n// the converted key and the uncompressed public key should be the same\nconsole.log(uncompressedKey === ecdh.getPublicKey('hex'));\n
\n"
}
],
"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} ",
"name": "inputEncoding",
"type": "string",
"optional": true
},
{
"textRaw": "`outputEncoding` {string} ",
"name": "outputEncoding",
"type": "string",
"optional": true
}
]
},
{
"params": [
{
"name": "otherPublicKey"
},
{
"name": "inputEncoding",
"optional": true
},
{
"name": "outputEncoding",
"optional": true
}
]
}
],
"desc": "Computes the shared secret using otherPublicKey
as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using specified inputEncoding
, and the returned secret\nis encoded using the specified outputEncoding
. Encodings can be\n'latin1'
, 'hex'
, or 'base64'
. If the inputEncoding
is not\nprovided, otherPublicKey
is expected to be a Buffer
, TypedArray
, or\nDataView
.
If outputEncoding
is given a string will be returned; otherwise a\nBuffer
is returned.
ecdh.computeSecret
will throw an\nERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY
error when otherPublicKey
\nlies outside of the elliptic curve. Since otherPublicKey
is\nusually supplied from a remote user over an insecure network,\nits recommended for developers to handle this exception accordingly.
Generates private and public EC Diffie-Hellman key values, and returns\nthe public key in the specified format
and encoding
. This key should be\ntransferred to the other party.
The format
argument specifies point encoding and can be 'compressed'
or\n'uncompressed'
. If format
is not specified, the point will be returned in\n'uncompressed'
format.
The encoding
argument can be 'latin1'
, 'hex'
, or 'base64'
. If\nencoding
is provided a string is returned; otherwise a Buffer
\nis returned.
The format
argument specifies point encoding and can be 'compressed'
or\n'uncompressed'
. If format
is not specified the point will be returned in\n'uncompressed'
format.
The encoding
argument can be 'latin1'
, 'hex'
, or 'base64'
. If\nencoding
is specified, a string is returned; otherwise a Buffer
is\nreturned.
The format
argument specifies point encoding and can be 'compressed'
or\n'uncompressed'
. If format
is not specified the point will be returned in\n'uncompressed'
format.
The encoding
argument can be 'latin1'
, 'hex'
, or 'base64'
. If\nencoding
is specified, a string is returned; otherwise a Buffer
is\nreturned.
Sets the EC Diffie-Hellman private key. The encoding
can be 'latin1'
,\n'hex'
or 'base64'
. If encoding
is provided, privateKey
is expected\nto be a string; otherwise privateKey
is expected to be a Buffer
,\nTypedArray
, or DataView
.
If privateKey
is not valid for the curve specified when the ECDH
object was\ncreated, an error is thrown. Upon setting the private key, the associated\npublic point (key) is also generated and set in the ECDH
object.
Sets the EC Diffie-Hellman public key. Key encoding can be 'latin1'
,\n'hex'
or 'base64'
. If encoding
is provided publicKey
is expected to\nbe a string; otherwise a Buffer
, TypedArray
, or DataView
is expected.
Note that there is not normally a reason to call this method because ECDH
\nonly requires a private key and the other party's public key to compute the\nshared secret. Typically either ecdh.generateKeys()
or\necdh.setPrivateKey()
will be called. The ecdh.setPrivateKey()
method\nattempts to generate the public point/key associated with the private key being\nset.
Example (obtaining a shared secret):
\nconst crypto = require('crypto');\nconst alice = crypto.createECDH('secp256k1');\nconst bob = crypto.createECDH('secp256k1');\n\n// Note: This is a shortcut way to specify 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
\n"
}
]
},
{
"textRaw": "Class: Hash",
"type": "class",
"name": "Hash",
"meta": {
"added": [
"v0.1.92"
],
"changes": []
},
"desc": "The Hash
class is a utility for creating hash digests of data. It can be\nused in one of two ways:
hash.update()
and hash.digest()
methods to produce the\ncomputed hash.The crypto.createHash()
method is used to create Hash
instances. Hash
\nobjects are not to be created directly using the new
keyword.
Example: Using Hash
objects as streams:
const crypto = require('crypto');\nconst hash = crypto.createHash('sha256');\n\nhash.on('readable', () => {\n const data = hash.read();\n if (data) {\n console.log(data.toString('hex'));\n // Prints:\n // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n }\n});\n\nhash.write('some data to hash');\nhash.end();\n
\nExample: Using Hash
and piped streams:
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
\nExample: Using the hash.update()
and hash.digest()
methods:
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
\n",
"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} ",
"name": "encoding",
"type": "string",
"optional": true
}
]
},
{
"params": [
{
"name": "encoding",
"optional": true
}
]
}
],
"desc": "Calculates the digest of all of the data passed to be hashed (using the\nhash.update()
method). The encoding
can be 'hex'
, 'latin1'
or\n'base64'
. If encoding
is provided a string will be returned; otherwise\na Buffer
is returned.
The Hash
object can not be used again after hash.digest()
method has been\ncalled. Multiple calls will cause an error to be thrown.
Updates the hash content with the given data
, the encoding of which\nis given in inputEncoding
and can be 'utf8'
, 'ascii'
or\n'latin1'
. If encoding
is not provided, and the data
is a string, an\nencoding of 'utf8'
is enforced. If data
is a Buffer
, TypedArray
, or\nDataView
, then inputEncoding
is ignored.
This can be called many times with new data as it is streamed.
\n" } ] }, { "textRaw": "Class: Hmac", "type": "class", "name": "Hmac", "meta": { "added": [ "v0.1.94" ], "changes": [] }, "desc": "The Hmac
Class is a utility for creating cryptographic HMAC digests. It can\nbe used in one of two ways:
hmac.update()
and hmac.digest()
methods to produce the\ncomputed HMAC digest.The crypto.createHmac()
method is used to create Hmac
instances. Hmac
\nobjects are not to be created directly using the new
keyword.
Example: Using Hmac
objects as streams:
const crypto = require('crypto');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nhmac.on('readable', () => {\n const data = hmac.read();\n if (data) {\n console.log(data.toString('hex'));\n // Prints:\n // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n }\n});\n\nhmac.write('some data to hash');\nhmac.end();\n
\nExample: Using Hmac
and piped streams:
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
\nExample: Using the hmac.update()
and hmac.digest()
methods:
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
\n",
"methods": [
{
"textRaw": "hmac.digest([encoding])",
"type": "method",
"name": "digest",
"meta": {
"added": [
"v0.1.94"
],
"changes": []
},
"signatures": [
{
"return": {
"textRaw": "Returns: {Buffer | string} ",
"name": "return",
"type": "Buffer | string"
},
"params": [
{
"textRaw": "`encoding` {string} ",
"name": "encoding",
"type": "string",
"optional": true
}
]
},
{
"params": [
{
"name": "encoding",
"optional": true
}
]
}
],
"desc": "Calculates the HMAC digest of all of the data passed using hmac.update()
.\nThe encoding
can be 'hex'
, 'latin1'
or 'base64'
. If encoding
is\nprovided a string is returned; otherwise a Buffer
is returned;
The Hmac
object can not be used again after hmac.digest()
has been\ncalled. Multiple calls to hmac.digest()
will result in an error being thrown.
Updates the Hmac
content with the given data
, the encoding of which\nis given in inputEncoding
and can be 'utf8'
, 'ascii'
or\n'latin1'
. If encoding
is not provided, and the data
is a string, an\nencoding of 'utf8'
is enforced. If data
is a Buffer
, TypedArray
, or\nDataView
, then inputEncoding
is ignored.
This can be called many times with new data as it is streamed.
\n" } ] }, { "textRaw": "Class: Sign", "type": "class", "name": "Sign", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "desc": "The Sign
Class is a utility for generating signatures. It can be used in one\nof two ways:
sign.sign()
method is used to generate and return the signature, orsign.update()
and sign.sign()
methods to produce the\nsignature.The crypto.createSign()
method is used to create Sign
instances. The\nargument is the string name of the hash function to use. Sign
objects are not\nto be created directly using the new
keyword.
Example: Using Sign
objects as streams:
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
\nExample: Using the sign.update()
and sign.sign()
methods:
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
\nIn some cases, a Sign
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.
Example: signing using legacy signature algorithm name
\nconst 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
\n",
"methods": [
{
"textRaw": "sign.sign(privateKey[, outputFormat])",
"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} ",
"options": [
{
"textRaw": "`key` {string} ",
"name": "key",
"type": "string"
},
{
"textRaw": "`passphrase` {string} ",
"name": "passphrase",
"type": "string"
}
],
"name": "privateKey",
"type": "string | Object"
},
{
"textRaw": "`outputFormat` {string} ",
"name": "outputFormat",
"type": "string",
"optional": true
}
]
},
{
"params": [
{
"name": "privateKey"
},
{
"name": "outputFormat",
"optional": true
}
]
}
],
"desc": "Calculates the signature on all the data passed through using either\nsign.update()
or sign.write()
.
The privateKey
argument can be an object or a string. If privateKey
is a\nstring, it is treated as a raw key with no passphrase. If privateKey
is an\nobject, it must contain one or more of the following properties:
key
: {string} - PEM encoded private key (required)passphrase
: {string} - passphrase for the private keypadding
: {integer} - Optional padding value for RSA, one of the following:
crypto.constants.RSA_PKCS1_PADDING
(default)crypto.constants.RSA_PKCS1_PSS_PADDING
Note that RSA_PKCS1_PSS_PADDING
will use MGF1 with the same hash function\nused to sign the message as specified in section 3.1 of RFC 4055.
saltLength
: {integer} - salt length for when padding is\nRSA_PKCS1_PSS_PADDING
. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST
sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN
(default) sets it to the\nmaximum permissible value.The outputFormat
can specify one of 'latin1'
, 'hex'
or 'base64'
. If\noutputFormat
is provided a string is returned; otherwise a Buffer
is\nreturned.
The Sign
object can not be again used after sign.sign()
method has been\ncalled. Multiple calls to sign.sign()
will result in an error being thrown.
Updates the Sign
content with the given data
, the encoding of which\nis given in inputEncoding
and can be 'utf8'
, 'ascii'
or\n'latin1'
. If encoding
is not provided, and the data
is a string, an\nencoding of 'utf8'
is enforced. If data
is a Buffer
, TypedArray
, or\nDataView
, then inputEncoding
is ignored.
This can be called many times with new data as it is streamed.
\n" } ] }, { "textRaw": "Class: Verify", "type": "class", "name": "Verify", "meta": { "added": [ "v0.1.92" ], "changes": [] }, "desc": "The Verify
class is a utility for verifying signatures. It can be used in one\nof two ways:
verify.update()
and verify.verify()
methods to verify\nthe signature.The crypto.createVerify()
method is used to create Verify
instances.\nVerify
objects are not to be created directly using the new
keyword.
Example: Using Verify
objects as streams:
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
\nExample: Using the verify.update()
and verify.verify()
methods:
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
\n",
"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} ",
"name": "inputEncoding",
"type": "string",
"optional": true
}
]
},
{
"params": [
{
"name": "data"
},
{
"name": "inputEncoding",
"optional": true
}
]
}
],
"desc": "Updates the Verify
content with the given data
, the encoding of which\nis given in inputEncoding
and can be 'utf8'
, 'ascii'
or\n'latin1'
. If encoding
is not provided, and the data
is a string, an\nencoding of 'utf8'
is enforced. If data
is a Buffer
, TypedArray
, or\nDataView
, then inputEncoding
is ignored.
This can be called many times with new data as it is streamed.
\n" }, { "textRaw": "verify.verify(object, signature[, signatureFormat])", "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": "`signatureFormat` {string} ", "name": "signatureFormat", "type": "string", "optional": true } ] }, { "params": [ { "name": "object" }, { "name": "signature" }, { "name": "signatureFormat", "optional": true } ] } ], "desc": "Verifies the provided data using the given object
and signature
.\nThe object
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:
key
: {string} - PEM encoded public key (required)padding
: {integer} - Optional padding value for RSA, one of the following:
crypto.constants.RSA_PKCS1_PADDING
(default)crypto.constants.RSA_PKCS1_PSS_PADDING
Note that RSA_PKCS1_PSS_PADDING
will use MGF1 with the same hash function\nused to verify the message as specified in section 3.1 of RFC 4055.
saltLength
: {integer} - salt length for when padding is\nRSA_PKCS1_PSS_PADDING
. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST
sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_AUTO
(default) causes it to be\ndetermined automatically.The signature
argument is the previously calculated signature for the data, in\nthe signatureFormat
which can be 'latin1'
, 'hex'
or 'base64'
.\nIf a signatureFormat
is specified, the signature
is expected to be a\nstring; otherwise signature
is expected to be a Buffer
,\nTypedArray
, or DataView
.
The verify
object can not be used again after verify.verify()
has been\ncalled. Multiple calls to verify.verify()
will result in an error being\nthrown.