{ "source": "doc/api/crypto.md", "modules": [ { "textRaw": "Crypto", "name": "crypto", "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.

\n

Use require('crypto') to access this module.

\n
const crypto = require('crypto');\n\nconst secret = 'abcdefg';\nconst hash = crypto.createHmac('sha256', secret)\n                   .update('I love cupcakes')\n                   .digest('hex');\nconsole.log(hash);\n  // Prints:\n  //   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e\n
\n", "classes": [ { "textRaw": "Class: Certificate", "type": "class", "name": "Certificate", "meta": { "added": [ "v0.11.8" ] }, "desc": "

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

\n

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

\n", "methods": [ { "textRaw": "new crypto.Certificate()", "type": "method", "name": "Certificate", "desc": "

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

\n
const crypto = require('crypto');\n\nconst cert1 = new crypto.Certificate();\nconst cert2 = crypto.Certificate();\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "certificate.exportChallenge(spkac)", "type": "method", "name": "exportChallenge", "meta": { "added": [ "v0.11.8" ] }, "desc": "

The spkac data structure includes a public key and a challenge. The\ncertificate.exportChallenge() returns the challenge component in the\nform of a Node.js Buffer. The spkac argument can be either a string\nor a Buffer.

\n
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", "signatures": [ { "params": [ { "name": "spkac" } ] } ] }, { "textRaw": "certificate.exportPublicKey(spkac)", "type": "method", "name": "exportPublicKey", "meta": { "added": [ "v0.11.8" ] }, "desc": "

The spkac data structure includes a public key and a challenge. The\ncertificate.exportPublicKey() returns the public key component in the\nform of a Node.js Buffer. The spkac argument can be either a string\nor a Buffer.

\n
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", "signatures": [ { "params": [ { "name": "spkac" } ] } ] }, { "textRaw": "certificate.verifySpkac(spkac)", "type": "method", "name": "verifySpkac", "meta": { "added": [ "v0.11.8" ] }, "desc": "

Returns true if the given spkac data structure is valid, false otherwise.\nThe spkac argument must be a Node.js Buffer.

\n
const cert = require('crypto').Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(new Buffer(spkac)));\n  // Prints true or false\n
\n", "signatures": [ { "params": [ { "name": "spkac" } ] } ] } ] }, { "textRaw": "Class: Cipher", "type": "class", "name": "Cipher", "meta": { "added": [ "v0.1.94" ] }, "desc": "

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

\n\n

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

\n

Example: Using Cipher objects as streams:

\n
const crypto = require('crypto');\nconst cipher = crypto.createCipher('aes192', 'a password');\n\nvar encrypted = '';\ncipher.on('readable', () => {\n  var 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
\n

Example: Using Cipher and piped streams:

\n
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
\n

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

\n
const crypto = require('crypto');\nconst cipher = crypto.createCipher('aes192', 'a password');\n\nvar 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([output_encoding])", "type": "method", "name": "final", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Returns any remaining enciphered contents. If output_encoding\nparameter is one of 'binary', 'base64' or 'hex', a string is returned.\nIf an output_encoding is not provided, a Buffer is returned.

\n

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.

\n", "signatures": [ { "params": [ { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "cipher.setAAD(buffer)", "type": "method", "name": "setAAD", "meta": { "added": [ "v1.0.0" ] }, "desc": "

When using an authenticated encryption mode (only GCM is currently\nsupported), the cipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.

\n", "signatures": [ { "params": [ { "name": "buffer" } ] } ] }, { "textRaw": "cipher.getAuthTag()", "type": "method", "name": "getAuthTag", "meta": { "added": [ "v1.0.0" ] }, "desc": "

When using an authenticated encryption mode (only GCM is currently\nsupported), the cipher.getAuthTag() method returns a Buffer containing\nthe authentication tag that has been computed from the given data.

\n

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

\n", "signatures": [ { "params": [] } ] }, { "textRaw": "cipher.setAutoPadding(auto_padding=true)", "type": "method", "name": "setAutoPadding", "meta": { "added": [ "v0.7.1" ] }, "desc": "

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

\n

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

\n

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

\n", "signatures": [ { "params": [ { "name": "auto_padding", "default": "true" } ] } ] }, { "textRaw": "cipher.update(data[, input_encoding][, output_encoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Updates the cipher with data. If the input_encoding argument is given,\nit's value must be one of 'utf8', 'ascii', or 'binary' and the data\nargument is a string using the specified encoding. If the input_encoding\nargument is not given, data must be a Buffer. If data is a\nBuffer then input_encoding is ignored.

\n

The output_encoding specifies the output format of the enciphered\ndata, and can be 'binary', 'base64' or 'hex'. If the output_encoding\nis specified, a string using the specified encoding is returned. If no\noutput_encoding is provided, a Buffer is returned.

\n

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

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Decipher", "type": "class", "name": "Decipher", "meta": { "added": [ "v0.1.94" ] }, "desc": "

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

\n\n

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

\n

Example: Using Decipher objects as streams:

\n
const crypto = require('crypto');\nconst decipher = crypto.createDecipher('aes192', 'a password');\n\nvar decrypted = '';\ndecipher.on('readable', () => {\n  var 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\nvar encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';\ndecipher.write(encrypted, 'hex');\ndecipher.end();\n
\n

Example: Using Decipher and piped streams:

\n
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
\n

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

\n
const crypto = require('crypto');\nconst decipher = crypto.createDecipher('aes192', 'a password');\n\nvar encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';\nvar 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([output_encoding])", "type": "method", "name": "final", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Returns any remaining deciphered contents. If output_encoding\nparameter is one of 'binary', 'base64' or 'hex', a string is returned.\nIf an output_encoding is not provided, a Buffer is returned.

\n

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.

\n", "signatures": [ { "params": [ { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "decipher.setAAD(buffer)", "type": "method", "name": "setAAD", "meta": { "added": [ "v1.0.0" ] }, "desc": "

When using an authenticated encryption mode (only GCM is currently\nsupported), the decipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.

\n", "signatures": [ { "params": [ { "name": "buffer" } ] } ] }, { "textRaw": "decipher.setAuthTag(buffer)", "type": "method", "name": "setAuthTag", "meta": { "added": [ "v1.0.0" ] }, "desc": "

When using an authenticated encryption mode (only GCM is 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() with throw, indicating that the\ncipher text should be discarded due to failed authentication.

\n", "signatures": [ { "params": [ { "name": "buffer" } ] } ] }, { "textRaw": "decipher.setAutoPadding(auto_padding=true)", "type": "method", "name": "setAutoPadding", "meta": { "added": [ "v0.7.1" ] }, "desc": "

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

\n

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

\n

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

\n", "signatures": [ { "params": [ { "name": "auto_padding", "default": "true" } ] } ] }, { "textRaw": "decipher.update(data[, input_encoding][, output_encoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Updates the decipher with data. If the input_encoding argument is given,\nit's value must be one of 'binary', 'base64', or 'hex' and the data\nargument is a string using the specified encoding. If the input_encoding\nargument is not given, data must be a Buffer. If data is a\nBuffer then input_encoding is ignored.

\n

The output_encoding specifies the output format of the enciphered\ndata, and can be 'binary', 'ascii' or 'utf8'. If the output_encoding\nis specified, a string using the specified encoding is returned. If no\noutput_encoding is provided, a Buffer is returned.

\n

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

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: DiffieHellman", "type": "class", "name": "DiffieHellman", "meta": { "added": [ "v0.5.0" ] }, "desc": "

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

\n

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

\n
const crypto = require('crypto');\nconst assert = require('assert');\n\n// Generate Alice's keys...\nconst alice = crypto.createDiffieHellman(2048);\nconst alice_key = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());\nconst bob_key = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst alice_secret = alice.computeSecret(bob_key);\nconst bob_secret = bob.computeSecret(alice_key);\n\n// OK\nassert.equal(alice_secret.toString('hex'), bob_secret.toString('hex'));\n
\n", "methods": [ { "textRaw": "diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding])", "type": "method", "name": "computeSecret", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Computes the shared secret using other_public_key as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using the specified input_encoding, and secret is\nencoded using specified output_encoding. Encodings can be\n'binary', 'hex', or 'base64'. If the input_encoding is not\nprovided, other_public_key is expected to be a Buffer.

\n

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

\n", "signatures": [ { "params": [ { "name": "other_public_key" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.generateKeys([encoding])", "type": "method", "name": "generateKeys", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Generates private and public Diffie-Hellman key values, and returns\nthe public key in the specified encoding. This key should be\ntransferred to the other party. Encoding can be 'binary', 'hex',\nor 'base64'. If encoding is provided a string is returned; otherwise a\nBuffer is returned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getGenerator([encoding])", "type": "method", "name": "getGenerator", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Returns the Diffie-Hellman generator in the specified encoding, which can\nbe 'binary', 'hex', or 'base64'. If encoding is provided a string is\nreturned; otherwise a Buffer is returned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPrime([encoding])", "type": "method", "name": "getPrime", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Returns the Diffie-Hellman prime in the specified encoding, which can\nbe 'binary', 'hex', or 'base64'. If encoding is provided a string is\nreturned; otherwise a Buffer is returned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPrivateKey([encoding])", "type": "method", "name": "getPrivateKey", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Returns the Diffie-Hellman private key in the specified encoding,\nwhich can be 'binary', 'hex', or 'base64'. If encoding is provided a\nstring is returned; otherwise a Buffer is returned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.getPublicKey([encoding])", "type": "method", "name": "getPublicKey", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Returns the Diffie-Hellman public key in the specified encoding, which\ncan be 'binary', 'hex', or 'base64'. If encoding is provided a\nstring is returned; otherwise a Buffer is returned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.setPrivateKey(private_key[, encoding])", "type": "method", "name": "setPrivateKey", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Sets the Diffie-Hellman private key. If the encoding argument is provided\nand is either 'binary', 'hex', or 'base64', private_key is expected\nto be a string. If no encoding is provided, private_key is expected\nto be a Buffer.

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "diffieHellman.setPublicKey(public_key[, encoding])", "type": "method", "name": "setPublicKey", "meta": { "added": [ "v0.5.0" ] }, "desc": "

Sets the Diffie-Hellman public key. If the encoding argument is provided\nand is either 'binary', 'hex' or 'base64', public_key is expected\nto be a string. If no encoding is provided, public_key is expected\nto be a Buffer.

\n", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "encoding", "optional": true } ] } ] } ], "properties": [ { "textRaw": "diffieHellman.verifyError", "name": "verifyError", "meta": { "added": [ "v0.11.12" ] }, "desc": "

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

\n

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

\n\n" } ] }, { "textRaw": "Class: ECDH", "type": "class", "name": "ECDH", "meta": { "added": [ "v0.11.14" ] }, "desc": "

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

\n

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

\n
const crypto = require('crypto');\nconst assert = require('assert');\n\n// Generate Alice's keys...\nconst alice = crypto.createECDH('secp521r1');\nconst alice_key = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = crypto.createECDH('secp521r1');\nconst bob_key = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst alice_secret = alice.computeSecret(bob_key);\nconst bob_secret = bob.computeSecret(alice_key);\n\nassert(alice_secret, bob_secret);\n  // OK\n
\n", "methods": [ { "textRaw": "ecdh.computeSecret(other_public_key[, input_encoding][, output_encoding])", "type": "method", "name": "computeSecret", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Computes the shared secret using other_public_key as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using specified input_encoding, and the returned secret\nis encoded using the specified output_encoding. Encodings can be\n'binary', 'hex', or 'base64'. If the input_encoding is not\nprovided, other_public_key is expected to be a Buffer.

\n

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

\n", "signatures": [ { "params": [ { "name": "other_public_key" }, { "name": "input_encoding", "optional": true }, { "name": "output_encoding", "optional": true } ] } ] }, { "textRaw": "ecdh.generateKeys([encoding[, format]])", "type": "method", "name": "generateKeys", "meta": { "added": [ "v0.11.14" ] }, "desc": "

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

\n

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

\n

The encoding argument can be 'binary', 'hex', or 'base64'. If\nencoding is provided a string is returned; otherwise a Buffer\nis returned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true }, { "name": "format", "optional": true } ] } ] }, { "textRaw": "ecdh.getPrivateKey([encoding])", "type": "method", "name": "getPrivateKey", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Returns the EC Diffie-Hellman private key in the specified encoding,\nwhich can be 'binary', 'hex', or 'base64'. If encoding is provided\na string is returned; otherwise a Buffer is returned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "ecdh.getPublicKey([encoding[, format]])", "type": "method", "name": "getPublicKey", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Returns the EC Diffie-Hellman public key in the specified encoding and\nformat.

\n

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

\n

The encoding argument can be 'binary', 'hex', or 'base64'. If\nencoding is specified, a string is returned; otherwise a Buffer is\nreturned.

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true }, { "name": "format", "optional": true } ] } ] }, { "textRaw": "ecdh.setPrivateKey(private_key[, encoding])", "type": "method", "name": "setPrivateKey", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Sets the EC Diffie-Hellman private key. The encoding can be 'binary',\n'hex' or 'base64'. If encoding is provided, private_key is expected\nto be a string; otherwise private_key is expected to be a Buffer. If\nprivate_key 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.

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "ecdh.setPublicKey(public_key[, encoding])", "type": "method", "name": "setPublicKey", "meta": { "added": [ "v0.11.14" ], "deprecated": [ "v5.2.0" ] }, "stability": 0, "stabilityText": "Deprecated", "desc": "

Sets the EC Diffie-Hellman public key. Key encoding can be 'binary',\n'hex' or 'base64'. If encoding is provided public_key is expected to\nbe a string; otherwise a Buffer is expected.

\n

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.

\n

Example (obtaining a shared secret):

\n
const 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 bob.generateKeys();\n\nconst alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n// alice_secret and bob_secret should be the same shared secret value\nconsole.log(alice_secret === bob_secret);\n
\n", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Hash", "type": "class", "name": "Hash", "meta": { "added": [ "v0.1.92" ] }, "desc": "

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

\n\n

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

\n

Example: Using Hash objects as streams:

\n
const crypto = require('crypto');\nconst hash = crypto.createHash('sha256');\n\nhash.on('readable', () => {\n  var data = hash.read();\n  if (data)\n    console.log(data.toString('hex'));\n    // Prints:\n    //   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n});\n\nhash.write('some data to hash');\nhash.end();\n
\n

Example: Using Hash and piped streams:

\n
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
\n

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

\n
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" ] }, "desc": "

Calculates the digest of all of the data passed to be hashed (using the\nhash.update() method). The encoding can be 'hex', 'binary' or\n'base64'. If encoding is provided a string will be returned; otherwise\na Buffer is returned.

\n

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

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "hash.update(data[, input_encoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ] }, "desc": "

Updates the hash content with the given data, the encoding of which\nis given in input_encoding and can be 'utf8', 'ascii' or\n'binary'. If encoding is not provided, and the data is a string, an\nencoding of 'binary' is enforced. If data is a Buffer then\ninput_encoding is ignored.

\n

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

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Hmac", "type": "class", "name": "Hmac", "meta": { "added": [ "v0.1.94" ] }, "desc": "

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

\n\n

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

\n

Example: Using Hmac objects as streams:

\n
const crypto = require('crypto');\nconst hmac = crypto.createHmac('sha256', 'a secret');\n\nhmac.on('readable', () => {\n  var data = hmac.read();\n  if (data)\n    console.log(data.toString('hex'));\n    // Prints:\n    //   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n});\n\nhmac.write('some data to hash');\nhmac.end();\n
\n

Example: Using Hmac and piped streams:

\n
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
\n

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

\n
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" ] }, "desc": "

Calculates the HMAC digest of all of the data passed using hmac.update().\nThe encoding can be 'hex', 'binary' or 'base64'. If encoding is\nprovided a string is returned; otherwise a Buffer is returned;

\n

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

\n", "signatures": [ { "params": [ { "name": "encoding", "optional": true } ] } ] }, { "textRaw": "hmac.update(data[, input_encoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Updates the Hmac content with the given data, the encoding of which\nis given in input_encoding and can be 'utf8', 'ascii' or\n'binary'. If encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer then\ninput_encoding is ignored.

\n

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

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Sign", "type": "class", "name": "Sign", "meta": { "added": [ "v0.1.92" ] }, "desc": "

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

\n\n

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

\n

Example: Using Sign objects as streams:

\n
const crypto = require('crypto');\nconst sign = crypto.createSign('RSA-SHA256');\n\nsign.write('some data to sign');\nsign.end();\n\nconst private_key = getPrivateKeySomehow();\nconsole.log(sign.sign(private_key, 'hex'));\n  // Prints the calculated signature\n
\n

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

\n
const crypto = require('crypto');\nconst sign = crypto.createSign('RSA-SHA256');\n\nsign.update('some data to sign');\n\nconst private_key = getPrivateKeySomehow();\nconsole.log(sign.sign(private_key, 'hex'));\n  // Prints the calculated signature\n
\n

A Sign instance can also be created by just passing in the digest\nalgorithm name, in which case OpenSSL will infer the full signature algorithm\nfrom the type of the PEM-formatted private key, including algorithms that\ndo not have directly exposed name constants, e.g. 'ecdsa-with-SHA256'.

\n

Example: signing using ECDSA with SHA256

\n
const crypto = require('crypto');\nconst sign = crypto.createSign('sha256');\n\nsign.update('some data to sign');\n\nconst private_key = '-----BEGIN EC PRIVATE KEY-----\\n' +\n        'MHcCAQEEIF+jnWY1D5kbVYDNvxxo/Y+ku2uJPDwS0r/VuPZQrjjVoAoGCCqGSM49\\n' +\n        'AwEHoUQDQgAEurOxfSxmqIRYzJVagdZfMMSjRNNhB8i3mXyIMq704m2m52FdfKZ2\\n' +\n        'pQhByd5eyj3lgZ7m7jbchtdgyOF8Io/1ng==\\n' +\n        '-----END EC PRIVATE KEY-----\\n';\n\nconsole.log(sign.sign(private_key).toString('hex'));\n
\n", "methods": [ { "textRaw": "sign.sign(private_key[, output_format])", "type": "method", "name": "sign", "meta": { "added": [ "v0.1.92" ] }, "desc": "

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

\n

The private_key argument can be an object or a string. If private_key is a\nstring, it is treated as a raw key with no passphrase. If private_key is an\nobject, it is interpreted as a hash containing two properties:

\n\n

The output_format can specify one of 'binary', 'hex' or 'base64'. If\noutput_format is provided a string is returned; otherwise a Buffer is\nreturned.

\n

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

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "output_format", "optional": true } ] } ] }, { "textRaw": "sign.update(data[, input_encoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ] }, "desc": "

Updates the Sign content with the given data, the encoding of which\nis given in input_encoding and can be 'utf8', 'ascii' or\n'binary'. If encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer then\ninput_encoding is ignored.

\n

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

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] } ] }, { "textRaw": "Class: Verify", "type": "class", "name": "Verify", "meta": { "added": [ "v0.1.92" ] }, "desc": "

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

\n\n

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

\n

Example: Using Verify objects as streams:

\n
const crypto = require('crypto');\nconst verify = crypto.createVerify('RSA-SHA256');\n\nverify.write('some data to sign');\nverify.end();\n\nconst public_key = getPublicKeySomehow();\nconst signature = getSignatureToVerify();\nconsole.log(verify.verify(public_key, signature));\n  // Prints true or false\n
\n

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

\n
const crypto = require('crypto');\nconst verify = crypto.createVerify('RSA-SHA256');\n\nverify.update('some data to sign');\n\nconst public_key = getPublicKeySomehow();\nconst signature = getSignatureToVerify();\nconsole.log(verify.verify(public_key, signature));\n  // Prints true or false\n
\n", "methods": [ { "textRaw": "verifier.update(data[, input_encoding])", "type": "method", "name": "update", "meta": { "added": [ "v0.1.92" ] }, "desc": "

Updates the Verify content with the given data, the encoding of which\nis given in input_encoding and can be 'utf8', 'ascii' or\n'binary'. If encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer then\ninput_encoding is ignored.

\n

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

\n", "signatures": [ { "params": [ { "name": "data" }, { "name": "input_encoding", "optional": true } ] } ] }, { "textRaw": "verifier.verify(object, signature[, signature_format])", "type": "method", "name": "verify", "meta": { "added": [ "v0.1.92" ] }, "desc": "

Verifies the provided data using the given object and signature.\nThe object argument is a string containing a PEM encoded object, which can be\none an RSA public key, a DSA public key, or an X.509 certificate.\nThe signature argument is the previously calculated signature for the data, in\nthe signature_format which can be 'binary', 'hex' or 'base64'.\nIf a signature_format is specified, the signature is expected to be a\nstring; otherwise signature is expected to be a Buffer.

\n

Returns true or false depending on the validity of the signature for\nthe data and public key.

\n

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

\n", "signatures": [ { "params": [ { "name": "object" }, { "name": "signature" }, { "name": "signature_format", "optional": true } ] } ] } ] } ], "modules": [ { "textRaw": "`crypto` module methods and properties", "name": "`crypto`_module_methods_and_properties", "properties": [ { "textRaw": "crypto.DEFAULT_ENCODING", "name": "DEFAULT_ENCODING", "meta": { "added": [ "v0.9.3" ] }, "desc": "

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

\n

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

\n

New applications should expect the default to be 'buffer'. This property may\nbecome deprecated in a future Node.js release.

\n" } ], "methods": [ { "textRaw": "crypto.createCipher(algorithm, password)", "type": "method", "name": "createCipher", "meta": { "added": [ "v0.1.94" ] }, "desc": "

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

\n

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list-cipher-algorithms will display the\navailable cipher algorithms.

\n

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

\n

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

\n

In line with OpenSSL's recommendation to use pbkdf2 instead of\nEVP_BytesToKey it is recommended that developers derive a key and IV on\ntheir own using crypto.pbkdf2() and to use crypto.createCipheriv()\nto create the Cipher object.

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "password" } ] } ] }, { "textRaw": "crypto.createCipheriv(algorithm, key, iv)", "type": "method", "name": "createCipheriv", "desc": "

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

\n

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list-cipher-algorithms will display the\navailable cipher algorithms.

\n

The key is the raw key used by the algorithm and iv is an\ninitialization vector. Both arguments must be 'binary' encoded strings or\nbuffers.

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" }, { "name": "iv" } ] } ] }, { "textRaw": "crypto.createCredentials(details)", "type": "method", "name": "createCredentials", "meta": { "added": [ "v0.1.92" ], "deprecated": [ "v0.11.13" ] }, "stability": 0, "stabilityText": "Deprecated: Use [`tls.createSecureContext()`][] instead.", "desc": "

The crypto.createCredentials() method is a deprecated alias for creating\nand returning a tls.SecureContext object. The crypto.createCredentials()\nmethod should not be used.

\n

The optional details argument is a hash object with keys:

\n\n

If no 'ca' details are given, Node.js will use Mozilla's default\npublicly trusted list of CAs.

\n", "signatures": [ { "params": [ { "name": "details" } ] } ] }, { "textRaw": "crypto.createDecipher(algorithm, password)", "type": "method", "name": "createDecipher", "meta": { "added": [ "v0.1.94" ] }, "desc": "

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

\n

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

\n

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

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "password" } ] } ] }, { "textRaw": "crypto.createDecipheriv(algorithm, key, iv)", "type": "method", "name": "createDecipheriv", "meta": { "added": [ "v0.1.94" ] }, "desc": "

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

\n

The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list-cipher-algorithms will display the\navailable cipher algorithms.

\n

The key is the raw key used by the algorithm and iv is an\ninitialization vector. Both arguments must be 'binary' encoded strings or\nbuffers.

\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" }, { "name": "iv" } ] } ] }, { "textRaw": "crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding])", "type": "method", "name": "createDiffieHellman", "meta": { "added": [ "v0.11.12" ] }, "desc": "

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

\n

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

\n

The prime_encoding and generator_encoding arguments can be 'binary',\n'hex', or 'base64'.

\n

If prime_encoding is specified, prime is expected to be a string; otherwise\na Buffer is expected.

\n

If generator_encoding is specified, generator is expected to be a string;\notherwise either a number or Buffer is expected.

\n", "signatures": [ { "params": [ { "name": "prime" }, { "name": "prime_encoding", "optional": true }, { "name": "generator", "optional": true }, { "name": "generator_encoding", "optional": true } ] } ] }, { "textRaw": "crypto.createDiffieHellman(prime_length[, generator])", "type": "method", "name": "createDiffieHellman", "meta": { "added": [ "v0.5.0" ] }, "desc": "

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

\n", "signatures": [ { "params": [ { "name": "prime_length" }, { "name": "generator", "optional": true } ] } ] }, { "textRaw": "crypto.createECDH(curve_name)", "type": "method", "name": "createECDH", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Creates an Elliptic Curve Diffie-Hellman (ECDH) key exchange object using a\npredefined curve specified by the curve_name 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.

\n", "signatures": [ { "params": [ { "name": "curve_name" } ] } ] }, { "textRaw": "crypto.createHash(algorithm)", "type": "method", "name": "createHash", "meta": { "added": [ "v0.1.92" ] }, "desc": "

Creates and returns a Hash object that can be used to generate hash digests\nusing the given algorithm.

\n

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

\n

Example: generating the sha256 sum of a file

\n
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  var data = input.read();\n  if (data)\n    hash.update(data);\n  else {\n    console.log(`${hash.digest('hex')} ${filename}`);\n  }\n});\n
\n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createHmac(algorithm, key)", "type": "method", "name": "createHmac", "meta": { "added": [ "v0.1.94" ] }, "desc": "

Creates and returns an Hmac object that uses the given algorithm and key.

\n

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

\n

The key is the HMAC key used to generate the cryptographic HMAC hash.

\n

Example: generating the sha256 HMAC of a file

\n
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  var data = input.read();\n  if (data)\n    hmac.update(data);\n  else {\n    console.log(`${hmac.digest('hex')} ${filename}`);\n  }\n});\n
\n", "signatures": [ { "params": [ { "name": "algorithm" }, { "name": "key" } ] } ] }, { "textRaw": "crypto.createSign(algorithm)", "type": "method", "name": "createSign", "meta": { "added": [ "v0.1.92" ] }, "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.

\n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.createVerify(algorithm)", "type": "method", "name": "createVerify", "meta": { "added": [ "v0.1.92" ] }, "desc": "

Creates and returns a Verify object that uses the given algorithm.\nUse crypto.getHashes() to obtain an array of names of the available\nsigning algorithms.

\n", "signatures": [ { "params": [ { "name": "algorithm" } ] } ] }, { "textRaw": "crypto.getCiphers()", "type": "method", "name": "getCiphers", "meta": { "added": [ "v0.9.3" ] }, "desc": "

Returns an array with the names of the supported cipher algorithms.

\n

Example:

\n
const ciphers = crypto.getCiphers();\nconsole.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.getCurves()", "type": "method", "name": "getCurves", "meta": { "added": [ "v2.3.0" ] }, "desc": "

Returns an array with the names of the supported elliptic curves.

\n

Example:

\n
const curves = crypto.getCurves();\nconsole.log(curves); // ['secp256k1', 'secp384r1', ...]\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.getDiffieHellman(group_name)", "type": "method", "name": "getDiffieHellman", "meta": { "added": [ "v0.7.5" ] }, "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.

\n

Example (obtaining a shared secret):

\n
const crypto = require('crypto');\nconst alice = crypto.getDiffieHellman('modp14');\nconst bob = crypto.getDiffieHellman('modp14');\n\nalice.generateKeys();\nbob.generateKeys();\n\nconst alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n/* alice_secret and bob_secret should be the same */\nconsole.log(alice_secret == bob_secret);\n
\n", "signatures": [ { "params": [ { "name": "group_name" } ] } ] }, { "textRaw": "crypto.getHashes()", "type": "method", "name": "getHashes", "meta": { "added": [ "v0.9.3" ] }, "desc": "

Returns an array of the names of the supported hash algorithms,\nsuch as RSA-SHA256.

\n

Example:

\n
const hashes = crypto.getHashes();\nconsole.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]\n
\n", "signatures": [ { "params": [] } ] }, { "textRaw": "crypto.pbkdf2(password, salt, iterations, keylen[, digest], callback)", "type": "method", "name": "pbkdf2", "meta": { "added": [ "v0.5.5" ] }, "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. If the digest algorithm is not specified,\na default of 'sha1' is used.

\n

The supplied callback function is called with two arguments: err and\nderivedKey. If an error occurs, err will be set; otherwise err will be\nnull. The successfully generated derivedKey will be passed as a Buffer.

\n

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

\n

The salt should also be as unique as possible. It is recommended that the\nsalts are random and their lengths are greater than 16 bytes. See\nNIST SP 800-132 for details.

\n

Example:

\n
const crypto = require('crypto');\ncrypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, key) => {\n  if (err) throw err;\n  console.log(key.toString('hex'));  // 'c5e478d...1469e50'\n});\n
\n

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

\n", "signatures": [ { "params": [ { "name": "password" }, { "name": "salt" }, { "name": "iterations" }, { "name": "keylen" }, { "name": "digest", "optional": true }, { "name": "callback" } ] } ] }, { "textRaw": "crypto.pbkdf2Sync(password, salt, iterations, keylen[, digest])", "type": "method", "name": "pbkdf2Sync", "meta": { "added": [ "v0.9.3" ] }, "desc": "

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

\n

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

\n

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

\n

The salt should also be as unique as possible. It is recommended that the\nsalts are random and their lengths are greater than 16 bytes. See\nNIST SP 800-132 for details.

\n

Example:

\n
const crypto = require('crypto');\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');\nconsole.log(key.toString('hex'));  // 'c5e478d...1469e50'\n
\n

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

\n", "signatures": [ { "params": [ { "name": "password" }, { "name": "salt" }, { "name": "iterations" }, { "name": "keylen" }, { "name": "digest", "optional": true } ] } ] }, { "textRaw": "crypto.privateDecrypt(private_key, buffer)", "type": "method", "name": "privateDecrypt", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Decrypts buffer with private_key.

\n

private_key can be an object or a string. If private_key is a string, it is\ntreated as the key with no passphrase and will use RSA_PKCS1_OAEP_PADDING.\nIf private_key is an object, it is interpreted as a hash object with the\nkeys:

\n\n

All paddings are defined in the constants module.

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "buffer" } ] } ] }, { "textRaw": "crypto.privateEncrypt(private_key, buffer)", "type": "method", "name": "privateEncrypt", "meta": { "added": [ "v1.1.0" ] }, "desc": "

Encrypts buffer with private_key.

\n

private_key can be an object or a string. If private_key is a string, it is\ntreated as the key with no passphrase and will use RSA_PKCS1_PADDING.\nIf private_key is an object, it is interpreted as a hash object with the\nkeys:

\n\n

All paddings are defined in the constants module.

\n", "signatures": [ { "params": [ { "name": "private_key" }, { "name": "buffer" } ] } ] }, { "textRaw": "crypto.publicDecrypt(public_key, buffer)", "type": "method", "name": "publicDecrypt", "meta": { "added": [ "v1.1.0" ] }, "desc": "

Decrypts buffer with public_key.

\n

public_key can be an object or a string. If public_key is a string, it is\ntreated as the key with no passphrase and will use RSA_PKCS1_PADDING.\nIf public_key is an object, it is interpreted as a hash object with the\nkeys:

\n\n

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

\n

All paddings are defined in the constants module.

\n", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "buffer" } ] } ] }, { "textRaw": "crypto.publicEncrypt(public_key, buffer)", "type": "method", "name": "publicEncrypt", "meta": { "added": [ "v0.11.14" ] }, "desc": "

Encrypts buffer with public_key.

\n

public_key can be an object or a string. If public_key is a string, it is\ntreated as the key with no passphrase and will use RSA_PKCS1_OAEP_PADDING.\nIf public_key is an object, it is interpreted as a hash object with the\nkeys:

\n\n

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

\n

All paddings are defined in the constants module.

\n", "signatures": [ { "params": [ { "name": "public_key" }, { "name": "buffer" } ] } ] }, { "textRaw": "crypto.randomBytes(size[, callback])", "type": "method", "name": "randomBytes", "meta": { "added": [ "v0.5.8" ] }, "desc": "

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

\n

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

\n
// Asynchronous\nconst 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
\n

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

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

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

\n", "signatures": [ { "params": [ { "name": "size" }, { "name": "callback", "optional": true } ] } ] }, { "textRaw": "crypto.setEngine(engine[, flags])", "type": "method", "name": "setEngine", "meta": { "added": [ "v0.11.11" ] }, "desc": "

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

\n

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

\n

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

\n\n", "signatures": [ { "params": [ { "name": "engine" }, { "name": "flags", "optional": true } ] } ] } ], "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": "

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 'binary' encoded strings by default rather than Buffers. This\ndefault was changed after Node.js v0.8 to use Buffer objects by default\ninstead.

\n", "type": "module", "displayName": "Legacy Streams API (pre Node.js v0.10)" }, { "textRaw": "Recent ECDH Changes", "name": "recent_ecdh_changes", "desc": "

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

\n

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

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

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

\n

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

\n

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

\n\n

See the reference for other recommendations and details.

\n", "type": "module", "displayName": "Support for weak or compromised algorithms" } ], "type": "module", "displayName": "Notes" } ], "type": "module", "displayName": "Crypto" } ] }