Source Code: lib/crypto.js
The node:crypto module provides cryptographic functionality that includes a\nset of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify\nfunctions.
node:crypto
const { createHmac } = await import('node:crypto');\n\nconst secret = 'abcdefg';\nconst hash = createHmac('sha256', secret)\n .update('I love cupcakes')\n .digest('hex');\nconsole.log(hash);\n// Prints:\n// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e\n
const crypto = require('node: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
It is possible for Node.js to be built without including support for the\nnode:crypto module. In such cases, attempting to import from crypto or\ncalling require('node:crypto') will result in an error being thrown.
import
crypto
require('node:crypto')
When using CommonJS, the error thrown can be caught using try/catch:
let crypto;\ntry {\n crypto = require('node:crypto');\n} catch (err) {\n console.log('crypto support is disabled!');\n}\n
When using the lexical ESM import keyword, the error can only be\ncaught if a handler for process.on('uncaughtException') is registered\nbefore any attempt to load the module is made (using, for instance,\na preload module).
process.on('uncaughtException')
When using ESM, if there is a chance that the code may be run on a build\nof Node.js where crypto support is not enabled, consider using the\nimport() function instead of the lexical import keyword:
import()
let crypto;\ntry {\n crypto = await import('node:crypto');\n} catch (err) {\n console.log('crypto support is disabled!');\n}\n
An object containing commonly used constants for crypto and security related\noperations. The specific constants currently defined are described in\nCrypto constants.
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.
'buffer'
Buffer
The crypto.DEFAULT_ENCODING mechanism is provided for backward compatibility\nwith legacy programs that expect 'latin1' to be the default encoding.
crypto.DEFAULT_ENCODING
'latin1'
New applications should expect the default to be 'buffer'.
This property is deprecated.
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.
This property is deprecated. Please use crypto.setFips() and\ncrypto.getFips() instead.
crypto.setFips()
crypto.getFips()
Type: <Crypto> An implementation of the Web Crypto API standard.
See the Web Crypto API documentation for details.
Checks the primality of the candidate.
candidate
Creates and returns a Cipher object that uses the given algorithm and\npassword.
Cipher
algorithm
password
The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode (e.g. 'aes-128-ccm') is used. In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength\noption is not required but can be used to set the length of the authentication\ntag that will be returned by getAuthTag() and defaults to 16 bytes.\nFor chacha20-poly1305, the authTagLength option defaults to 16 bytes.
options
'aes-128-ccm'
authTagLength
getAuthTag()
chacha20-poly1305
The algorithm is dependent on OpenSSL, examples are 'aes192', etc. On\nrecent OpenSSL releases, openssl list -cipher-algorithms will\ndisplay the available cipher algorithms.
'aes192'
openssl list -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.
TypedArray
DataView
This function is semantically insecure for all\nsupported ciphers and fatally flawed for ciphers in counter mode (such as CTR,\nGCM, or CCM).
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.
crypto.createCipher()
EVP_BytesToKey
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.
crypto.scrypt()
crypto.createCipheriv()
Creates and returns a Cipher object, with the given algorithm, key and\ninitialization vector (iv).
key
iv
The key is the raw key used by the algorithm and iv is an\ninitialization vector. Both arguments must be 'utf8' encoded strings,\nBuffers, TypedArray, or DataViews. The key may optionally be\na KeyObject of type secret. If the cipher does not need\nan initialization vector, iv may be null.
'utf8'
KeyObject
secret
null
When passing strings for key or iv, please consider\ncaveats when using strings as inputs to cryptographic APIs.
Initialization vectors should be unpredictable and unique; ideally, they will be\ncryptographically random. They do not have to be secret: IVs are typically just\nadded to ciphertext messages unencrypted. It may sound contradictory that\nsomething has to be unpredictable and unique, but does not have to be secret;\nremember that an attacker must not be able to predict ahead of time what a\ngiven IV will be.
Creates and returns a Decipher object that uses the given algorithm and\npassword (key).
Decipher
The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode (e.g. 'aes-128-ccm') is used. In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode.\nFor chacha20-poly1305, the authTagLength option defaults to 16 bytes.
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.
crypto.createDecipher()
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.
crypto.createDecipheriv()
Creates and returns a Decipher object that uses the given algorithm, key\nand initialization vector (iv).
The options argument controls stream behavior and is optional except when a\ncipher in CCM or OCB mode (e.g. 'aes-128-ccm') is used. In that case, the\nauthTagLength option is required and specifies the length of the\nauthentication tag in bytes, see CCM mode. In GCM mode, the authTagLength\noption is not required but can be used to restrict accepted authentication tags\nto those with the specified length.\nFor chacha20-poly1305, the authTagLength option defaults to 16 bytes.
Initialization vectors should be unpredictable and unique; ideally, they will be\ncryptographically random. They do not have to be secret: IVs are typically just\nadded to ciphertext messages unencrypted. It may sound contradictory that\nsomething has to be unpredictable and unique, but does not have to be secret;\nremember that an attacker must not be able to predict ahead of time what a given\nIV will be.
Creates a DiffieHellman key exchange object using the supplied prime and an\noptional specific generator.
DiffieHellman
prime
generator
The generator argument can be a number, string, or Buffer. If\ngenerator is not specified, the value 2 is used.
2
If primeEncoding is specified, prime is expected to be a string; otherwise\na Buffer, TypedArray, or DataView is expected.
primeEncoding
If generatorEncoding is specified, generator is expected to be a string;\notherwise a number, Buffer, TypedArray, or DataView is expected.
generatorEncoding
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.
primeLength
An alias for crypto.getDiffieHellman()
crypto.getDiffieHellman()
Creates an Elliptic Curve Diffie-Hellman (ECDH) key exchange object using a\npredefined curve specified by the curveName string. Use\ncrypto.getCurves() to obtain a list of available curve names. On recent\nOpenSSL releases, openssl ecparam -list_curves will also display the name\nand description of each available elliptic curve.
ECDH
curveName
crypto.getCurves()
openssl ecparam -list_curves
Creates and returns a Hash object that can be used to generate hash digests\nusing the given algorithm. Optional options argument controls stream\nbehavior. For XOF hash functions such as 'shake256', the outputLength option\ncan be used to specify the desired output length in bytes.
Hash
'shake256'
outputLength
The algorithm is dependent on the available algorithms supported by the\nversion of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc.\nOn recent releases of OpenSSL, openssl list -digest-algorithms will\ndisplay the available digest algorithms.
'sha256'
'sha512'
openssl list -digest-algorithms
Example: generating the sha256 sum of a file
import {\n createReadStream\n} from 'node:fs';\nimport { argv } from 'node:process';\nconst {\n createHash\n} = await import('node:crypto');\n\nconst filename = argv[2];\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream(filename);\ninput.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = input.read();\n if (data)\n hash.update(data);\n else {\n console.log(`${hash.digest('hex')} ${filename}`);\n }\n});\n
const {\n createReadStream,\n} = require('node:fs');\nconst {\n createHash,\n} = require('node:crypto');\nconst { argv } = require('node:process');\n\nconst filename = argv[2];\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream(filename);\ninput.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = input.read();\n if (data)\n hash.update(data);\n else {\n console.log(`${hash.digest('hex')} ${filename}`);\n }\n});\n
Creates and returns an Hmac object that uses the given algorithm and key.\nOptional options argument controls stream behavior.
Hmac
The key is the HMAC key used to generate the cryptographic HMAC hash. If it is\na KeyObject, its type must be secret.
Example: generating the sha256 HMAC of a file
import {\n createReadStream\n} from 'node:fs';\nimport { argv } from 'node:process';\nconst {\n createHmac\n} = await import('node:crypto');\n\nconst filename = argv[2];\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream(filename);\ninput.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = input.read();\n if (data)\n hmac.update(data);\n else {\n console.log(`${hmac.digest('hex')} ${filename}`);\n }\n});\n
const {\n createReadStream,\n} = require('node:fs');\nconst {\n createHmac,\n} = require('node:crypto');\nconst { argv } = require('node:process');\n\nconst filename = argv[2];\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream(filename);\ninput.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = input.read();\n if (data)\n hmac.update(data);\n else {\n console.log(`${hmac.digest('hex')} ${filename}`);\n }\n});\n
format
'pem'
'der'
'jwk'
type
'pkcs1'
'pkcs8'
'sec1'
passphrase
encoding
Creates and returns a new key object containing a private key. If key is a\nstring or Buffer, format is assumed to be 'pem'; otherwise, key\nmust be an object with the properties described above.
If the private key is encrypted, a passphrase must be specified. The length\nof the passphrase is limited to 1024 bytes.
'spki'
Creates and returns a new key object containing a public key. If key is a\nstring or Buffer, format is assumed to be 'pem'; if key is a KeyObject\nwith type 'private', the public key is derived from the given private key;\notherwise, key must be an object with the properties described above.
'private'
If the format is 'pem', the 'key' may also be an X.509 certificate.
'key'
Because public keys can be derived from private keys, a private key may be\npassed instead of a public key. In that case, this function behaves as if\ncrypto.createPrivateKey() had been called, except that the type of the\nreturned KeyObject will be 'public' and that the private key cannot be\nextracted from the returned KeyObject. Similarly, if a KeyObject with type\n'private' is given, a new KeyObject with type 'public' will be returned\nand it will be impossible to extract the private key from the returned object.
crypto.createPrivateKey()
'public'
Creates and returns a new key object containing a secret key for symmetric\nencryption or Hmac.
Creates and returns a Sign object that uses the given algorithm. Use\ncrypto.getHashes() to obtain the names of the available digest algorithms.\nOptional options argument controls the stream.Writable behavior.
Sign
crypto.getHashes()
stream.Writable
In some cases, a Sign instance can be created using the name of a signature\nalgorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use\nthe corresponding digest algorithm. This does not work for all signature\nalgorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest\nalgorithm names.
'RSA-SHA256'
'ecdsa-with-SHA256'
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.
Verify
In some cases, a Verify instance can be created using the name of a signature\nalgorithm, such as 'RSA-SHA256', instead of a digest algorithm. This will use\nthe corresponding digest algorithm. This does not work for all signature\nalgorithms, such as 'ecdsa-with-SHA256', so it is best to always use digest\nalgorithm names.
Computes the Diffie-Hellman secret based on a privateKey and a publicKey.\nBoth keys must have the same asymmetricKeyType, which must be one of 'dh'\n(for Diffie-Hellman), 'ec' (for ECDH), 'x448', or 'x25519' (for ECDH-ES).
privateKey
publicKey
asymmetricKeyType
'dh'
'ec'
'x448'
'x25519'
Asynchronously generates a new random secret key of the given length. The\ntype will determine which validations will be performed on the length.
length
const {\n generateKey\n} = await import('node:crypto');\n\ngenerateKey('hmac', { length: 64 }, (err, key) => {\n if (err) throw err;\n console.log(key.export().toString('hex')); // 46e..........620\n});\n
const {\n generateKey,\n} = require('node:crypto');\n\ngenerateKey('hmac', { length: 64 }, (err, key) => {\n if (err) throw err;\n console.log(key.export().toString('hex')); // 46e..........620\n});\n
Generates a new asymmetric key pair of the given type. RSA, RSA-PSS, DSA, EC,\nEd25519, Ed448, X25519, X448, and DH are currently supported.
If a publicKeyEncoding or privateKeyEncoding was specified, this function\nbehaves as if keyObject.export() had been called on its result. Otherwise,\nthe respective part of the key is returned as a KeyObject.
publicKeyEncoding
privateKeyEncoding
keyObject.export()
It is recommended to encode public keys as 'spki' and private keys as\n'pkcs8' with encryption for long-term storage:
const {\n generateKeyPair\n} = await import('node:crypto');\n\ngenerateKeyPair('rsa', {\n modulusLength: 4096,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: 'top secret'\n }\n}, (err, publicKey, privateKey) => {\n // Handle errors and use the generated key pair.\n});\n
const {\n generateKeyPair,\n} = require('node:crypto');\n\ngenerateKeyPair('rsa', {\n modulusLength: 4096,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: 'top secret'\n }\n}, (err, publicKey, privateKey) => {\n // Handle errors and use the generated key pair.\n});\n
On completion, callback will be called with err set to undefined and\npublicKey / privateKey representing the generated key pair.
callback
err
undefined
If this method is invoked as its util.promisify()ed version, it returns\na Promise for an Object with publicKey and privateKey properties.
util.promisify()
Promise
Object
When encoding public keys, it is recommended to use 'spki'. When encoding\nprivate keys, it is recommended to use 'pkcs8' with a strong passphrase,\nand to keep the passphrase confidential.
const {\n generateKeyPairSync\n} = await import('node:crypto');\n\nconst {\n publicKey,\n privateKey,\n} = generateKeyPairSync('rsa', {\n modulusLength: 4096,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: 'top secret'\n }\n});\n
const {\n generateKeyPairSync,\n} = require('node:crypto');\n\nconst {\n publicKey,\n privateKey,\n} = generateKeyPairSync('rsa', {\n modulusLength: 4096,\n publicKeyEncoding: {\n type: 'spki',\n format: 'pem'\n },\n privateKeyEncoding: {\n type: 'pkcs8',\n format: 'pem',\n cipher: 'aes-256-cbc',\n passphrase: 'top secret'\n }\n});\n
The return value { publicKey, privateKey } represents the generated key pair.\nWhen PEM encoding was selected, the respective key will be a string, otherwise\nit will be a buffer containing the data encoded as DER.
{ publicKey, privateKey }
Synchronously generates a new random secret key of the given length. The\ntype will determine which validations will be performed on the length.
const {\n generateKeySync\n} = await import('node:crypto');\n\nconst key = generateKeySync('hmac', { length: 64 });\nconsole.log(key.export().toString('hex')); // e89..........41e\n
const {\n generateKeySync,\n} = require('node:crypto');\n\nconst key = generateKeySync('hmac', { length: 64 });\nconsole.log(key.export().toString('hex')); // e89..........41e\n
Generates a pseudorandom prime of size bits.
size
If options.safe is true, the prime will be a safe prime -- that is,\n(prime - 1) / 2 will also be a prime.
options.safe
true
(prime - 1) / 2
The options.add and options.rem parameters can be used to enforce additional\nrequirements, e.g., for Diffie-Hellman:
options.add
options.rem
prime % add = rem
prime % add = 1
prime % add = 3
options.add > 2
Both options.add and options.rem must be encoded as big-endian sequences\nif given as an ArrayBuffer, SharedArrayBuffer, TypedArray, Buffer, or\nDataView.
ArrayBuffer
SharedArrayBuffer
By default, the prime is encoded as a big-endian sequence of octets\nin an <ArrayBuffer>. If the bigint option is true, then a <bigint>\nis provided.
bigint
Returns information about a given cipher.
Some ciphers accept variable length keys and initialization vectors. By default,\nthe crypto.getCipherInfo() method will return the default values for these\nciphers. To test if a given key length or iv length is acceptable for given\ncipher, use the keyLength and ivLength options. If the given values are\nunacceptable, undefined will be returned.
crypto.getCipherInfo()
keyLength
ivLength
const {\n getCiphers\n} = await import('node:crypto');\n\nconsole.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]\n
const {\n getCiphers,\n} = require('node:crypto');\n\nconsole.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]\n
const {\n getCurves\n} = await import('node:crypto');\n\nconsole.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n
const {\n getCurves,\n} = require('node:crypto');\n\nconsole.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]\n
Creates a predefined DiffieHellmanGroup key exchange object. The\nsupported groups are listed in the documentation for DiffieHellmanGroup.
DiffieHellmanGroup
The returned object mimics the interface of objects created by\ncrypto.createDiffieHellman(), but will not allow changing\nthe keys (with diffieHellman.setPublicKey(), for example). The\nadvantage of using this method is that the parties do not have to\ngenerate nor exchange a group modulus beforehand, saving both processor\nand communication time.
crypto.createDiffieHellman()
diffieHellman.setPublicKey()
Example (obtaining a shared secret):
const {\n getDiffieHellman\n} = await import('node:crypto');\nconst alice = getDiffieHellman('modp14');\nconst bob = getDiffieHellman('modp14');\n\nalice.generateKeys();\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n/* aliceSecret and bobSecret should be the same */\nconsole.log(aliceSecret === bobSecret);\n
const {\n getDiffieHellman,\n} = require('node:crypto');\n\nconst alice = getDiffieHellman('modp14');\nconst bob = getDiffieHellman('modp14');\n\nalice.generateKeys();\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n/* aliceSecret and bobSecret should be the same */\nconsole.log(aliceSecret === bobSecret);\n
const {\n getHashes\n} = await import('node:crypto');\n\nconsole.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n
const {\n getHashes,\n} = require('node:crypto');\n\nconsole.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]\n
HKDF is a simple key derivation function defined in RFC 5869. The given ikm,\nsalt and info are used with the digest to derive a key of keylen bytes.
ikm
salt
info
digest
keylen
The supplied callback function is called with two arguments: err and\nderivedKey. If an errors occurs while deriving the key, err will be set;\notherwise err will be null. The successfully generated derivedKey will\nbe passed to the callback as an <ArrayBuffer>. An error will be thrown if any\nof the input arguments specify invalid values or types.
derivedKey
import { Buffer } from 'node:buffer';\nconst {\n hkdf\n} = await import('node:crypto');\n\nhkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {\n if (err) throw err;\n console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'\n});\n
const {\n hkdf,\n} = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nhkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {\n if (err) throw err;\n console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'\n});\n
Provides a synchronous HKDF key derivation function as defined in RFC 5869. The\ngiven ikm, salt and info are used with the digest to derive a key of\nkeylen bytes.
The successfully generated derivedKey will be returned as an <ArrayBuffer>.
An error will be thrown if any of the input arguments specify invalid values or\ntypes, or if the derived key cannot be generated.
import { Buffer } from 'node:buffer';\nconst {\n hkdfSync\n} = await import('node:crypto');\n\nconst derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);\nconsole.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'\n
const {\n hkdfSync,\n} = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);\nconsole.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'\n
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.
iterations
The supplied callback function is called with two arguments: err and\nderivedKey. If an error occurs while deriving the key, err will be set;\notherwise err will be null. By default, the successfully generated\nderivedKey will be passed to the callback as a Buffer. An error will be\nthrown if any of the input arguments specify invalid values or types.
The iterations argument must be a number set as high as possible. The\nhigher the number of iterations, the more secure the derived key will be,\nbut will take a longer amount of time to complete.
The salt should be as unique as possible. It is recommended that a salt is\nrandom and at least 16 bytes long. See NIST SP 800-132 for details.
When passing strings for password or salt, please consider\ncaveats when using strings as inputs to cryptographic APIs.
const {\n pbkdf2\n} = await import('node:crypto');\n\npbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'\n});\n
const {\n pbkdf2,\n} = require('node:crypto');\n\npbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'\n});\n
The crypto.DEFAULT_ENCODING property can be used to change the way the\nderivedKey is passed to the callback. This property, however, has been\ndeprecated and use should be avoided.
import crypto from 'node: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
const crypto = require('node: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
An array of supported digest functions can be retrieved using\ncrypto.getHashes().
This API uses libuv's threadpool, which can have surprising and\nnegative performance implications for some applications; see the\nUV_THREADPOOL_SIZE documentation for more information.
UV_THREADPOOL_SIZE
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.
Error
const {\n pbkdf2Sync\n} = await import('node:crypto');\n\nconst key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');\nconsole.log(key.toString('hex')); // '3745e48...08d59ae'\n
const {\n pbkdf2Sync,\n} = require('node:crypto');\n\nconst key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');\nconsole.log(key.toString('hex')); // '3745e48...08d59ae'\n
The crypto.DEFAULT_ENCODING property may be used to change the way the\nderivedKey is returned. This property, however, is deprecated and use\nshould be avoided.
import crypto from 'node:crypto';\ncrypto.DEFAULT_ENCODING = 'hex';\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');\nconsole.log(key); // '3745e48...aa39b34'\n
const crypto = require('node:crypto');\ncrypto.DEFAULT_ENCODING = 'hex';\nconst key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');\nconsole.log(key); // '3745e48...aa39b34'\n
oaepHash
'sha1'
oaepLabel
padding
crypto.constants
crypto.constants.RSA_NO_PADDING
crypto.constants.RSA_PKCS1_PADDING
crypto.constants.RSA_PKCS1_OAEP_PADDING
buffer
Decrypts buffer with privateKey. buffer was previously encrypted using\nthe corresponding public key, for example using crypto.publicEncrypt().
crypto.publicEncrypt()
If privateKey is not a KeyObject, this function behaves as if\nprivateKey had been passed to crypto.createPrivateKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_OAEP_PADDING.
RSA_PKCS1_OAEP_PADDING
Encrypts buffer with privateKey. The returned data can be decrypted using\nthe corresponding public key, for example using crypto.publicDecrypt().
crypto.publicDecrypt()
If privateKey is not a KeyObject, this function behaves as if\nprivateKey had been passed to crypto.createPrivateKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_PADDING.
RSA_PKCS1_PADDING
Decrypts buffer with key.buffer was previously encrypted using\nthe corresponding private key, for example using crypto.privateEncrypt().
crypto.privateEncrypt()
If key is not a KeyObject, this function behaves as if\nkey had been passed to crypto.createPublicKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_PADDING.
crypto.createPublicKey()
Because RSA public keys can be derived from private keys, a private key may\nbe passed instead of a public key.
Encrypts the content of buffer with key and returns a new\nBuffer with encrypted content. The returned data can be decrypted using\nthe corresponding private key, for example using crypto.privateDecrypt().
crypto.privateDecrypt()
If key is not a KeyObject, this function behaves as if\nkey had been passed to crypto.createPublicKey(). If it is an\nobject, the padding property can be passed. Otherwise, this function uses\nRSA_PKCS1_OAEP_PADDING.
Generates cryptographically strong pseudorandom data. The size argument\nis a number indicating the number of bytes to generate.
If a callback function is provided, the bytes are generated asynchronously\nand the callback function is invoked with two arguments: err and buf.\nIf an error occurs, err will be an Error object; otherwise it is null. The\nbuf argument is a Buffer containing the generated bytes.
buf
// Asynchronous\nconst {\n randomBytes\n} = await import('node:crypto');\n\nrandomBytes(256, (err, buf) => {\n if (err) throw err;\n console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);\n});\n
// Asynchronous\nconst {\n randomBytes,\n} = require('node:crypto');\n\nrandomBytes(256, (err, buf) => {\n if (err) throw err;\n console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);\n});\n
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.
// Synchronous\nconst {\n randomBytes\n} = await import('node:crypto');\n\nconst buf = randomBytes(256);\nconsole.log(\n `${buf.length} bytes of random data: ${buf.toString('hex')}`);\n
// Synchronous\nconst {\n randomBytes,\n} = require('node:crypto');\n\nconst buf = randomBytes(256);\nconsole.log(\n `${buf.length} bytes of random data: ${buf.toString('hex')}`);\n
The crypto.randomBytes() method will not complete until there is\nsufficient entropy available.\nThis should normally never take longer than a few milliseconds. The only time\nwhen generating the random bytes may conceivably block for a longer period of\ntime is right after boot, when the whole system is still low on entropy.
crypto.randomBytes()
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.
randomBytes
Synchronous version of crypto.randomFill().
crypto.randomFill()
import { Buffer } from 'node:buffer';\nconst { randomFillSync } = await import('node:crypto');\n\nconst buf = Buffer.alloc(10);\nconsole.log(randomFillSync(buf).toString('hex'));\n\nrandomFillSync(buf, 5);\nconsole.log(buf.toString('hex'));\n\n// The above is equivalent to the following:\nrandomFillSync(buf, 5, 5);\nconsole.log(buf.toString('hex'));\n
const { randomFillSync } = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.alloc(10);\nconsole.log(randomFillSync(buf).toString('hex'));\n\nrandomFillSync(buf, 5);\nconsole.log(buf.toString('hex'));\n\n// The above is equivalent to the following:\nrandomFillSync(buf, 5, 5);\nconsole.log(buf.toString('hex'));\n
Any ArrayBuffer, TypedArray or DataView instance may be passed as\nbuffer.
import { Buffer } from 'node:buffer';\nconst { randomFillSync } = await import('node:crypto');\n\nconst a = new Uint32Array(10);\nconsole.log(Buffer.from(randomFillSync(a).buffer,\n a.byteOffset, a.byteLength).toString('hex'));\n\nconst b = new DataView(new ArrayBuffer(10));\nconsole.log(Buffer.from(randomFillSync(b).buffer,\n b.byteOffset, b.byteLength).toString('hex'));\n\nconst c = new ArrayBuffer(10);\nconsole.log(Buffer.from(randomFillSync(c)).toString('hex'));\n
const { randomFillSync } = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst a = new Uint32Array(10);\nconsole.log(Buffer.from(randomFillSync(a).buffer,\n a.byteOffset, a.byteLength).toString('hex'));\n\nconst b = new DataView(new ArrayBuffer(10));\nconsole.log(Buffer.from(randomFillSync(b).buffer,\n b.byteOffset, b.byteLength).toString('hex'));\n\nconst c = new ArrayBuffer(10);\nconsole.log(Buffer.from(randomFillSync(c)).toString('hex'));\n
This function is similar to crypto.randomBytes() but requires the first\nargument to be a Buffer that will be filled. It also\nrequires that a callback is passed in.
If the callback function is not provided, an error will be thrown.
import { Buffer } from 'node:buffer';\nconst { randomFill } = await import('node:crypto');\n\nconst buf = Buffer.alloc(10);\nrandomFill(buf, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n\nrandomFill(buf, 5, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n\n// The above is equivalent to the following:\nrandomFill(buf, 5, 5, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n
const { randomFill } = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst buf = Buffer.alloc(10);\nrandomFill(buf, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n\nrandomFill(buf, 5, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n\n// The above is equivalent to the following:\nrandomFill(buf, 5, 5, (err, buf) => {\n if (err) throw err;\n console.log(buf.toString('hex'));\n});\n
Any ArrayBuffer, TypedArray, or DataView instance may be passed as\nbuffer.
While this includes instances of Float32Array and Float64Array, this\nfunction should not be used to generate random floating-point numbers. The\nresult may contain +Infinity, -Infinity, and NaN, and even if the array\ncontains finite numbers only, they are not drawn from a uniform random\ndistribution and have no meaningful lower or upper bounds.
Float32Array
Float64Array
+Infinity
-Infinity
NaN
import { Buffer } from 'node:buffer';\nconst { randomFill } = await import('node:crypto');\n\nconst a = new Uint32Array(10);\nrandomFill(a, (err, buf) => {\n if (err) throw err;\n console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n .toString('hex'));\n});\n\nconst b = new DataView(new ArrayBuffer(10));\nrandomFill(b, (err, buf) => {\n if (err) throw err;\n console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n .toString('hex'));\n});\n\nconst c = new ArrayBuffer(10);\nrandomFill(c, (err, buf) => {\n if (err) throw err;\n console.log(Buffer.from(buf).toString('hex'));\n});\n
const { randomFill } = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst a = new Uint32Array(10);\nrandomFill(a, (err, buf) => {\n if (err) throw err;\n console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n .toString('hex'));\n});\n\nconst b = new DataView(new ArrayBuffer(10));\nrandomFill(b, (err, buf) => {\n if (err) throw err;\n console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)\n .toString('hex'));\n});\n\nconst c = new ArrayBuffer(10);\nrandomFill(c, (err, buf) => {\n if (err) throw err;\n console.log(Buffer.from(buf).toString('hex'));\n});\n
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.
randomFill
Return a random integer n such that min <= n < max. This\nimplementation avoids modulo bias.
n
min <= n < max
The range (max - min) must be less than 248. min and max must\nbe safe integers.
max - min
min
max
If the callback function is not provided, the random integer is\ngenerated synchronously.
// Asynchronous\nconst {\n randomInt\n} = await import('node:crypto');\n\nrandomInt(3, (err, n) => {\n if (err) throw err;\n console.log(`Random number chosen from (0, 1, 2): ${n}`);\n});\n
// Asynchronous\nconst {\n randomInt,\n} = require('node:crypto');\n\nrandomInt(3, (err, n) => {\n if (err) throw err;\n console.log(`Random number chosen from (0, 1, 2): ${n}`);\n});\n
// Synchronous\nconst {\n randomInt\n} = await import('node:crypto');\n\nconst n = randomInt(3);\nconsole.log(`Random number chosen from (0, 1, 2): ${n}`);\n
// Synchronous\nconst {\n randomInt,\n} = require('node:crypto');\n\nconst n = randomInt(3);\nconsole.log(`Random number chosen from (0, 1, 2): ${n}`);\n
// With `min` argument\nconst {\n randomInt\n} = await import('node:crypto');\n\nconst n = randomInt(1, 7);\nconsole.log(`The dice rolled: ${n}`);\n
// With `min` argument\nconst {\n randomInt,\n} = require('node:crypto');\n\nconst n = randomInt(1, 7);\nconsole.log(`The dice rolled: ${n}`);\n
Generates a random RFC 4122 version 4 UUID. The UUID is generated using a\ncryptographic pseudorandom number generator.
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.
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.
const {\n scrypt\n} = await import('node:crypto');\n\n// Using the factory defaults.\nscrypt('password', 'salt', 64, (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'\n});\n// Using a custom N parameter. Must be a power of two.\nscrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'\n});\n
const {\n scrypt,\n} = require('node:crypto');\n\n// Using the factory defaults.\nscrypt('password', 'salt', 64, (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'\n});\n// Using a custom N parameter. Must be a power of two.\nscrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {\n if (err) throw err;\n console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'\n});\n
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.
An exception is thrown when key derivation fails, otherwise the derived key is\nreturned as a Buffer.
const {\n scryptSync\n} = await import('node:crypto');\n// Using the factory defaults.\n\nconst key1 = scryptSync('password', 'salt', 64);\nconsole.log(key1.toString('hex')); // '3745e48...08d59ae'\n// Using a custom N parameter. Must be a power of two.\nconst key2 = scryptSync('password', 'salt', 64, { N: 1024 });\nconsole.log(key2.toString('hex')); // '3745e48...aa39b34'\n
const {\n scryptSync,\n} = require('node:crypto');\n// Using the factory defaults.\n\nconst key1 = scryptSync('password', 'salt', 64);\nconsole.log(key1.toString('hex')); // '3745e48...08d59ae'\n// Using a custom N parameter. Must be a power of two.\nconst key2 = scryptSync('password', 'salt', 64, { N: 1024 });\nconsole.log(key2.toString('hex')); // '3745e48...aa39b34'\n
Load and set the engine for some or all OpenSSL functions (selected by flags).
engine
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):
flags
ENGINE_METHOD_ALL
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
Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.\nThrows an error if FIPS mode is not available.
data
signature
Calculates and returns the signature for data using the given private key and\nalgorithm. If algorithm is null or undefined, then the algorithm is\ndependent upon the key type (especially Ed25519 and Ed448).
If key is not a KeyObject, this function behaves as if key had been\npassed to crypto.createPrivateKey(). If it is an object, the following\nadditional properties can be passed:
dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the generated signature. It can be one of the following:
dsaEncoding
(r, s)
'ieee-p1363'
r || s
padding <integer> Optional padding value for RSA, one of the following:
crypto.constants.RSA_PKCS1_PSS_PADDING
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.
RSA_PKCS1_PSS_PADDING
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.
saltLength
crypto.constants.RSA_PSS_SALTLEN_DIGEST
crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN
If the callback function is provided this function uses libuv's threadpool.
This function compares the underlying bytes that represent the given\nArrayBuffer, TypedArray, or DataView instances using a constant-time\nalgorithm.
This function does not leak timing information that\nwould allow an attacker to guess one of the values. This is suitable for\ncomparing HMAC digests or secret values like authentication cookies or\ncapability urls.
a and b must both be Buffers, TypedArrays, or DataViews, and they\nmust have the same byte length. An error is thrown if a and b have\ndifferent byte lengths.
a
b
If at least one of a and b is a TypedArray with more than one byte per\nentry, such as Uint16Array, the result will be computed using the platform\nbyte order.
Uint16Array
When both of the inputs are Float32Arrays or\nFloat64Arrays, this function might return unexpected results due to IEEE 754\nencoding of floating-point numbers. In particular, neither x === y nor\nObject.is(x, y) implies that the byte representations of two floating-point\nnumbers x and y are equal.
x === y
Object.is(x, y)
x
y
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.
crypto.timingSafeEqual
result
false
Verifies the given signature for data using the given key and algorithm. If\nalgorithm is null or undefined, then the algorithm is dependent upon the\nkey type (especially Ed25519 and Ed448).
If key is not a KeyObject, this function behaves as if key had been\npassed to crypto.createPublicKey(). If it is an object, the following\nadditional properties can be passed:
dsaEncoding <string> For DSA and ECDSA, this option specifies the\nformat of the signature. It can be one of the following:
The signature argument is the previously calculated signature for the data.
Because public keys can be derived from private keys, a private key or a public\nkey may be passed for key.
For historical reasons, many cryptographic APIs provided by Node.js accept\nstrings as inputs where the underlying cryptographic algorithm works on byte\nsequences. These instances include plaintexts, ciphertexts, symmetric keys,\ninitialization vectors, passphrases, salts, authentication tags,\nand additional authenticated data.
When passing strings to cryptographic APIs, consider the following factors.
Not all byte sequences are valid UTF-8 strings. Therefore, when a byte\nsequence of length n is derived from a string, its entropy is generally\nlower than the entropy of a random or pseudorandom n byte sequence.\nFor example, no UTF-8 string will result in the byte sequence c0 af. Secret\nkeys should almost exclusively be random or pseudorandom byte sequences.
c0 af
Similarly, when converting random or pseudorandom byte sequences to UTF-8\nstrings, subsequences that do not represent valid code points may be replaced\nby the Unicode replacement character (U+FFFD). The byte representation of\nthe resulting Unicode string may, therefore, not be equal to the byte sequence\nthat the string was created from.
U+FFFD
const original = [0xc0, 0xaf];\nconst bytesAsString = Buffer.from(original).toString('utf8');\nconst stringAsBytes = Buffer.from(bytesAsString, 'utf8');\nconsole.log(stringAsBytes);\n// Prints '<Buffer ef bf bd ef bf bd>'.\n
The outputs of ciphers, hash functions, signature algorithms, and key\nderivation functions are pseudorandom byte sequences and should not be\nused as Unicode strings.
When strings are obtained from user input, some Unicode characters can be\nrepresented in multiple equivalent ways that result in different byte\nsequences. For example, when passing a user passphrase to a key derivation\nfunction, such as PBKDF2 or scrypt, the result of the key derivation function\ndepends on whether the string uses composed or decomposed characters. Node.js\ndoes not normalize character representations. Developers should consider using\nString.prototype.normalize() on user inputs before passing them to\ncryptographic APIs.
String.prototype.normalize()
The Crypto module was added to Node.js before there was the concept of a\nunified Stream API, and before there were Buffer objects for handling\nbinary data. As such, the many of the crypto defined classes have methods not\ntypically found on other Node.js classes that implement the streams\nAPI (e.g. update(), final(), or digest()). Also, many methods accepted\nand returned 'latin1' encoded strings by default rather than Buffers. This\ndefault was changed after Node.js v0.8 to use Buffer objects by default\ninstead.
update()
final()
digest()
The node:crypto module still supports some algorithms which are already\ncompromised and are not currently recommended for use. The API also allows\nthe use of ciphers and hashes with a small key size that are too weak for safe\nuse.
Users should take full responsibility for selecting the crypto\nalgorithm and key size according to their security requirements.
Based on the recommendations of NIST SP 800-131A:
modp1
modp2
modp5
See the reference for other recommendations and details.
CCM is one of the supported AEAD algorithms. Applications which use this\nmode must adhere to certain restrictions when using the cipher API:
N
7 ≤ N ≤ 13
2 ** (8 * (15 - N))
setAuthTag()
write(data)
end(data)
pipe()
setAAD()
plaintextLength
plaintextLength + authTagLength
import { Buffer } from 'node:buffer';\nconst {\n createCipheriv,\n createDecipheriv,\n randomBytes\n} = await import('node:crypto');\n\nconst key = 'keykeykeykeykeykeykeykey';\nconst nonce = randomBytes(12);\n\nconst aad = Buffer.from('0123456789', 'hex');\n\nconst cipher = createCipheriv('aes-192-ccm', key, nonce, {\n authTagLength: 16\n});\nconst plaintext = 'Hello world';\ncipher.setAAD(aad, {\n plaintextLength: Buffer.byteLength(plaintext)\n});\nconst ciphertext = cipher.update(plaintext, 'utf8');\ncipher.final();\nconst tag = cipher.getAuthTag();\n\n// Now transmit { ciphertext, nonce, tag }.\n\nconst decipher = createDecipheriv('aes-192-ccm', key, nonce, {\n authTagLength: 16\n});\ndecipher.setAuthTag(tag);\ndecipher.setAAD(aad, {\n plaintextLength: ciphertext.length\n});\nconst receivedPlaintext = decipher.update(ciphertext, null, 'utf8');\n\ntry {\n decipher.final();\n} catch (err) {\n throw new Error('Authentication failed!', { cause: err });\n}\n\nconsole.log(receivedPlaintext);\n
const { Buffer } = require('node:buffer');\nconst {\n createCipheriv,\n createDecipheriv,\n randomBytes,\n} = require('node:crypto');\n\nconst key = 'keykeykeykeykeykeykeykey';\nconst nonce = randomBytes(12);\n\nconst aad = Buffer.from('0123456789', 'hex');\n\nconst cipher = createCipheriv('aes-192-ccm', key, nonce, {\n authTagLength: 16\n});\nconst plaintext = 'Hello world';\ncipher.setAAD(aad, {\n plaintextLength: Buffer.byteLength(plaintext)\n});\nconst ciphertext = cipher.update(plaintext, 'utf8');\ncipher.final();\nconst tag = cipher.getAuthTag();\n\n// Now transmit { ciphertext, nonce, tag }.\n\nconst decipher = createDecipheriv('aes-192-ccm', key, nonce, {\n authTagLength: 16\n});\ndecipher.setAuthTag(tag);\ndecipher.setAAD(aad, {\n plaintextLength: ciphertext.length\n});\nconst receivedPlaintext = decipher.update(ciphertext, null, 'utf8');\n\ntry {\n decipher.final();\n} catch (err) {\n throw new Error('Authentication failed!', { cause: err });\n}\n\nconsole.log(receivedPlaintext);\n
The following constants exported by crypto.constants apply to various uses of\nthe node:crypto, node:tls, and node:https modules and are generally\nspecific to OpenSSL.
node:tls
node:https
See the list of SSL OP Flags for details.
SSL_OP_ALL
SSL_OP_ALLOW_NO_DHE_KEX
SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION
SSL_OP_CIPHER_SERVER_PREFERENCE
SSL_OP_CISCO_ANYCONNECT
SSL_OP_COOKIE_EXCHANGE
SSL_OP_CRYPTOPRO_TLSEXT_BUG
SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS
SSL_OP_EPHEMERAL_RSA
SSL_OP_LEGACY_SERVER_CONNECT
SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
SSL_OP_MICROSOFT_SESS_ID_BUG
SSL_OP_MSIE_SSLV2_RSA_PADDING
SSL_OP_NETSCAPE_CA_DN_BUG
SSL_OP_NETSCAPE_CHALLENGE_BUG
SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG
SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG
SSL_OP_NO_COMPRESSION
SSL_OP_NO_ENCRYPT_THEN_MAC
SSL_OP_NO_QUERY_MTU
SSL_OP_NO_RENEGOTIATION
SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
SSL_OP_NO_SSLv2
SSL_OP_NO_SSLv3
SSL_OP_NO_TICKET
SSL_OP_NO_TLSv1
SSL_OP_NO_TLSv1_1
SSL_OP_NO_TLSv1_2
SSL_OP_NO_TLSv1_3
SSL_OP_PKCS1_CHECK_1
SSL_OP_PKCS1_CHECK_2
SSL_OP_PRIORITIZE_CHACHA
SSL_OP_SINGLE_DH_USE
SSL_OP_SINGLE_ECDH_USE
SSL_OP_SSLEAY_080_CLIENT_DH_BUG
SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG
SSL_OP_TLS_BLOCK_PADDING_BUG
SSL_OP_TLS_D5_BUG
SSL_OP_TLS_ROLLBACK_BUG
ENGINE_METHOD_RSA
ENGINE_METHOD_DSA
ENGINE_METHOD_DH
ENGINE_METHOD_RAND
ENGINE_METHOD_EC
ENGINE_METHOD_CIPHERS
ENGINE_METHOD_DIGESTS
ENGINE_METHOD_PKEY_METHS
ENGINE_METHOD_PKEY_ASN1_METHS
ENGINE_METHOD_NONE
DH_CHECK_P_NOT_SAFE_PRIME
DH_CHECK_P_NOT_PRIME
DH_UNABLE_TO_CHECK_GENERATOR
DH_NOT_SUITABLE_GENERATOR
ALPN_ENABLED
RSA_SSLV23_PADDING
RSA_NO_PADDING
RSA_X931_PADDING
RSA_PSS_SALTLEN_DIGEST
RSA_PSS_SALTLEN_MAX_SIGN
RSA_PSS_SALTLEN_AUTO
POINT_CONVERSION_COMPRESSED
POINT_CONVERSION_UNCOMPRESSED
POINT_CONVERSION_HYBRID
defaultCoreCipherList
defaultCipherList
SPKAC is a Certificate Signing Request mechanism originally implemented by\nNetscape and was specified formally as part of HTML5's keygen element.
keygen
<keygen> is deprecated since HTML 5.2 and new projects\nshould not use this element anymore.
<keygen>
The node:crypto module provides the Certificate class for working with SPKAC\ndata. The most common usage is handling output generated by the HTML5\n<keygen> element. Node.js uses OpenSSL's SPKAC implementation internally.
Certificate
const { Certificate } = await import('node:crypto');\nconst spkac = getSpkacSomehow();\nconst challenge = Certificate.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
const { Certificate } = require('node:crypto');\nconst spkac = getSpkacSomehow();\nconst challenge = Certificate.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
const { Certificate } = await import('node:crypto');\nconst spkac = getSpkacSomehow();\nconst publicKey = Certificate.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
const { Certificate } = require('node:crypto');\nconst spkac = getSpkacSomehow();\nconst publicKey = Certificate.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
import { Buffer } from 'node:buffer';\nconst { Certificate } = await import('node:crypto');\n\nconst spkac = getSpkacSomehow();\nconsole.log(Certificate.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
const { Certificate } = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst spkac = getSpkacSomehow();\nconsole.log(Certificate.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
As a legacy interface, it is possible to create new instances of\nthe crypto.Certificate class as illustrated in the examples below.
crypto.Certificate
Instances of the Certificate class can be created using the new keyword\nor by calling crypto.Certificate() as a function:
new
crypto.Certificate()
const { Certificate } = await import('node:crypto');\n\nconst cert1 = new Certificate();\nconst cert2 = Certificate();\n
const { Certificate } = require('node:crypto');\n\nconst cert1 = new Certificate();\nconst cert2 = Certificate();\n
const { Certificate } = await import('node:crypto');\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconst challenge = cert.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
const { Certificate } = require('node:crypto');\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconst challenge = cert.exportChallenge(spkac);\nconsole.log(challenge.toString('utf8'));\n// Prints: the challenge as a UTF8 string\n
const { Certificate } = await import('node:crypto');\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconst publicKey = cert.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
const { Certificate } = require('node:crypto');\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconst publicKey = cert.exportPublicKey(spkac);\nconsole.log(publicKey);\n// Prints: the public key as <Buffer ...>\n
import { Buffer } from 'node:buffer';\nconst { Certificate } = await import('node:crypto');\n\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
const { Certificate } = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst cert = Certificate();\nconst spkac = getSpkacSomehow();\nconsole.log(cert.verifySpkac(Buffer.from(spkac)));\n// Prints: true or false\n
Instances of the Cipher class are used to encrypt data. The class can be\nused in one of two ways:
cipher.update()
cipher.final()
The crypto.createCipher() or crypto.createCipheriv() methods are\nused to create Cipher instances. Cipher objects are not to be created\ndirectly using the new keyword.
Example: Using Cipher objects as streams:
const {\n scrypt,\n randomFill,\n createCipheriv\n} = await import('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n\n// First, we'll generate the key. The key length is dependent on the algorithm.\n// In this case for aes192, it is 24 bytes (192 bits).\nscrypt(password, 'salt', 24, (err, key) => {\n if (err) throw err;\n // Then, we'll generate a random initialization vector\n randomFill(new Uint8Array(16), (err, iv) => {\n if (err) throw err;\n\n // Once we have the key and iv, we can create and use the cipher...\n const cipher = createCipheriv(algorithm, key, iv);\n\n let encrypted = '';\n cipher.setEncoding('hex');\n\n cipher.on('data', (chunk) => encrypted += chunk);\n cipher.on('end', () => console.log(encrypted));\n\n cipher.write('some clear text data');\n cipher.end();\n });\n});\n
const {\n scrypt,\n randomFill,\n createCipheriv\n} = require('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n\n// First, we'll generate the key. The key length is dependent on the algorithm.\n// In this case for aes192, it is 24 bytes (192 bits).\nscrypt(password, 'salt', 24, (err, key) => {\n if (err) throw err;\n // Then, we'll generate a random initialization vector\n randomFill(new Uint8Array(16), (err, iv) => {\n if (err) throw err;\n\n // Once we have the key and iv, we can create and use the cipher...\n const cipher = createCipheriv(algorithm, key, iv);\n\n let encrypted = '';\n cipher.setEncoding('hex');\n\n cipher.on('data', (chunk) => encrypted += chunk);\n cipher.on('end', () => console.log(encrypted));\n\n cipher.write('some clear text data');\n cipher.end();\n });\n});\n
Example: Using Cipher and piped streams:
import {\n createReadStream,\n createWriteStream,\n} from 'node:fs';\n\nimport {\n pipeline\n} from 'node:stream';\n\nconst {\n scrypt,\n randomFill,\n createCipheriv\n} = await import('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n\n// First, we'll generate the key. The key length is dependent on the algorithm.\n// In this case for aes192, it is 24 bytes (192 bits).\nscrypt(password, 'salt', 24, (err, key) => {\n if (err) throw err;\n // Then, we'll generate a random initialization vector\n randomFill(new Uint8Array(16), (err, iv) => {\n if (err) throw err;\n\n const cipher = createCipheriv(algorithm, key, iv);\n\n const input = createReadStream('test.js');\n const output = createWriteStream('test.enc');\n\n pipeline(input, cipher, output, (err) => {\n if (err) throw err;\n });\n });\n});\n
const {\n createReadStream,\n createWriteStream,\n} = require('node:fs');\n\nconst {\n pipeline\n} = require('node:stream');\n\nconst {\n scrypt,\n randomFill,\n createCipheriv,\n} = require('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n\n// First, we'll generate the key. The key length is dependent on the algorithm.\n// In this case for aes192, it is 24 bytes (192 bits).\nscrypt(password, 'salt', 24, (err, key) => {\n if (err) throw err;\n // Then, we'll generate a random initialization vector\n randomFill(new Uint8Array(16), (err, iv) => {\n if (err) throw err;\n\n const cipher = createCipheriv(algorithm, key, iv);\n\n const input = createReadStream('test.js');\n const output = createWriteStream('test.enc');\n\n pipeline(input, cipher, output, (err) => {\n if (err) throw err;\n });\n });\n});\n
Example: Using the cipher.update() and cipher.final() methods:
const {\n scrypt,\n randomFill,\n createCipheriv\n} = await import('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n\n// First, we'll generate the key. The key length is dependent on the algorithm.\n// In this case for aes192, it is 24 bytes (192 bits).\nscrypt(password, 'salt', 24, (err, key) => {\n if (err) throw err;\n // Then, we'll generate a random initialization vector\n randomFill(new Uint8Array(16), (err, iv) => {\n if (err) throw err;\n\n const cipher = createCipheriv(algorithm, key, iv);\n\n let encrypted = cipher.update('some clear text data', 'utf8', 'hex');\n encrypted += cipher.final('hex');\n console.log(encrypted);\n });\n});\n
const {\n scrypt,\n randomFill,\n createCipheriv,\n} = require('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n\n// First, we'll generate the key. The key length is dependent on the algorithm.\n// In this case for aes192, it is 24 bytes (192 bits).\nscrypt(password, 'salt', 24, (err, key) => {\n if (err) throw err;\n // Then, we'll generate a random initialization vector\n randomFill(new Uint8Array(16), (err, iv) => {\n if (err) throw err;\n\n const cipher = createCipheriv(algorithm, key, iv);\n\n let encrypted = cipher.update('some clear text data', 'utf8', 'hex');\n encrypted += cipher.final('hex');\n console.log(encrypted);\n });\n});\n
Once the cipher.final() method has been called, the Cipher object can no\nlonger be used to encrypt data. Attempts to call cipher.final() more than\nonce will result in an error being thrown.
The cipher.getAuthTag() method should only be called after encryption has\nbeen completed using the cipher.final() method.
cipher.getAuthTag()
If the authTagLength option was set during the cipher instance's creation,\nthis function will return exactly authTagLength bytes.
cipher
When using an authenticated encryption mode (GCM, CCM, OCB, and\nchacha20-poly1305 are\ncurrently supported), the cipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.
GCM
CCM
OCB
cipher.setAAD()
The plaintextLength option is optional for GCM and OCB. When using CCM,\nthe plaintextLength option must be specified and its value must match the\nlength of the plaintext in bytes. See CCM mode.
The cipher.setAAD() method must be called before cipher.update().
When using block encryption algorithms, the Cipher class will automatically\nadd padding to the input data to the appropriate block size. To disable the\ndefault padding call cipher.setAutoPadding(false).
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.
autoPadding
0x0
The cipher.setAutoPadding() method must be called before\ncipher.final().
cipher.setAutoPadding()
Updates the cipher with data. If the inputEncoding argument is given,\nthe data\nargument is a string using the specified encoding. If the inputEncoding\nargument is not given, data must be a Buffer, TypedArray, or\nDataView. If data is a Buffer, TypedArray, or DataView, then\ninputEncoding is ignored.
inputEncoding
The outputEncoding specifies the output format of the enciphered\ndata. If the outputEncoding\nis specified, a string using the specified encoding is returned. If no\noutputEncoding is provided, a Buffer is returned.
outputEncoding
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()
decipher.final()
The crypto.createDecipher() or crypto.createDecipheriv() methods are\nused to create Decipher instances. Decipher objects are not to be created\ndirectly using the new keyword.
Example: Using Decipher objects as streams:
import { Buffer } from 'node:buffer';\nconst {\n scryptSync,\n createDecipheriv\n} = await import('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Key length is dependent on the algorithm. In this case for aes192, it is\n// 24 bytes (192 bits).\n// Use the async `crypto.scrypt()` instead.\nconst key = scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = createDecipheriv(algorithm, key, iv);\n\nlet decrypted = '';\ndecipher.on('readable', () => {\n let chunk;\n while (null !== (chunk = decipher.read())) {\n decrypted += chunk.toString('utf8');\n }\n});\ndecipher.on('end', () => {\n console.log(decrypted);\n // Prints: some clear text data\n});\n\n// Encrypted with same algorithm, key and iv.\nconst encrypted =\n 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\ndecipher.write(encrypted, 'hex');\ndecipher.end();\n
const {\n scryptSync,\n createDecipheriv,\n} = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Key length is dependent on the algorithm. In this case for aes192, it is\n// 24 bytes (192 bits).\n// Use the async `crypto.scrypt()` instead.\nconst key = scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = createDecipheriv(algorithm, key, iv);\n\nlet decrypted = '';\ndecipher.on('readable', () => {\n let chunk;\n while (null !== (chunk = decipher.read())) {\n decrypted += chunk.toString('utf8');\n }\n});\ndecipher.on('end', () => {\n console.log(decrypted);\n // Prints: some clear text data\n});\n\n// Encrypted with same algorithm, key and iv.\nconst encrypted =\n 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\ndecipher.write(encrypted, 'hex');\ndecipher.end();\n
Example: Using Decipher and piped streams:
import {\n createReadStream,\n createWriteStream,\n} from 'node:fs';\nimport { Buffer } from 'node:buffer';\nconst {\n scryptSync,\n createDecipheriv\n} = await import('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = createDecipheriv(algorithm, key, iv);\n\nconst input = createReadStream('test.enc');\nconst output = createWriteStream('test.js');\n\ninput.pipe(decipher).pipe(output);\n
const {\n createReadStream,\n createWriteStream,\n} = require('node:fs');\nconst {\n scryptSync,\n createDecipheriv,\n} = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = createDecipheriv(algorithm, key, iv);\n\nconst input = createReadStream('test.enc');\nconst output = createWriteStream('test.js');\n\ninput.pipe(decipher).pipe(output);\n
Example: Using the decipher.update() and decipher.final() methods:
import { Buffer } from 'node:buffer';\nconst {\n scryptSync,\n createDecipheriv\n} = await import('node:crypto');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = createDecipheriv(algorithm, key, iv);\n\n// Encrypted using same algorithm, key and iv.\nconst encrypted =\n 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\nlet decrypted = decipher.update(encrypted, 'hex', 'utf8');\ndecrypted += decipher.final('utf8');\nconsole.log(decrypted);\n// Prints: some clear text data\n
const {\n scryptSync,\n createDecipheriv,\n} = require('node:crypto');\nconst { Buffer } = require('node:buffer');\n\nconst algorithm = 'aes-192-cbc';\nconst password = 'Password used to generate key';\n// Use the async `crypto.scrypt()` instead.\nconst key = scryptSync(password, 'salt', 24);\n// The IV is usually passed along with the ciphertext.\nconst iv = Buffer.alloc(16, 0); // Initialization vector.\n\nconst decipher = createDecipheriv(algorithm, key, iv);\n\n// Encrypted using same algorithm, key and iv.\nconst encrypted =\n 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';\nlet decrypted = decipher.update(encrypted, 'hex', 'utf8');\ndecrypted += decipher.final('utf8');\nconsole.log(decrypted);\n// Prints: some clear text data\n
Once the decipher.final() method has been called, the Decipher object can\nno longer be used to decrypt data. Attempts to call decipher.final() more\nthan once will result in an error being thrown.
When using an authenticated encryption mode (GCM, CCM, OCB, and\nchacha20-poly1305 are\ncurrently supported), the decipher.setAAD() method sets the value used for the\nadditional authenticated data (AAD) input parameter.
decipher.setAAD()
The options argument is optional for GCM. When using CCM, the\nplaintextLength option must be specified and its value must match the length\nof the ciphertext in bytes. See CCM mode.
The decipher.setAAD() method must be called before decipher.update().
When passing a string as the buffer, please consider\ncaveats when using strings as inputs to cryptographic APIs.
When using an authenticated encryption mode (GCM, CCM, OCB, and\nchacha20-poly1305 are\ncurrently supported), the decipher.setAuthTag() method is used to pass in the\nreceived authentication tag. If no tag is provided, or if the cipher text\nhas been tampered with, decipher.final() will throw, indicating that the\ncipher text should be discarded due to failed authentication. If the tag length\nis invalid according to NIST SP 800-38D or does not match the value of the\nauthTagLength option, decipher.setAuthTag() will throw an error.
decipher.setAuthTag()
The decipher.setAuthTag() method must be called before decipher.update()\nfor CCM mode or before decipher.final() for GCM and OCB modes and\nchacha20-poly1305.\ndecipher.setAuthTag() can only be called once.
When passing a string as the authentication tag, please consider\ncaveats when using strings as inputs to cryptographic APIs.
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.
decipher.setAutoPadding(false)
Turning auto padding off will only work if the input data's length is a\nmultiple of the ciphers block size.
The decipher.setAutoPadding() method must be called before\ndecipher.final().
decipher.setAutoPadding()
Updates the decipher with data. If the inputEncoding argument is given,\nthe data\nargument is a string using the specified encoding. If the inputEncoding\nargument is not given, data must be a Buffer. If data is a\nBuffer then inputEncoding is ignored.
The decipher.update() method can be called multiple times with new data until\ndecipher.final() is called. Calling decipher.update() after\ndecipher.final() will result in an error being thrown.
The DiffieHellman class is a utility for creating Diffie-Hellman key\nexchanges.
Instances of the DiffieHellman class can be created using the\ncrypto.createDiffieHellman() function.
import assert from 'node:assert';\n\nconst {\n createDiffieHellman\n} = await import('node:crypto');\n\n// Generate Alice's keys...\nconst alice = createDiffieHellman(2048);\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\n// OK\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n
const assert = require('node:assert');\n\nconst {\n createDiffieHellman,\n} = require('node:crypto');\n\n// Generate Alice's keys...\nconst alice = createDiffieHellman(2048);\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\n// OK\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n
Computes the shared secret using otherPublicKey as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using the specified inputEncoding, and secret is\nencoded using specified outputEncoding.\nIf the inputEncoding is not\nprovided, otherPublicKey is expected to be a Buffer,\nTypedArray, or DataView.
otherPublicKey
If outputEncoding is given a string is returned; otherwise, a\nBuffer is returned.
Generates private and public Diffie-Hellman key values unless they have been\ngenerated or computed already, and returns\nthe public key in the specified encoding. This key should be\ntransferred to the other party.\nIf encoding is provided a string is returned; otherwise a\nBuffer is returned.
This function is a thin wrapper around DH_generate_key(). In particular,\nonce a private key has been generated or set, calling this function only updates\nthe public key but does not generate a new private key.
DH_generate_key()
Returns the Diffie-Hellman generator in the specified encoding.\nIf encoding is provided a string is\nreturned; otherwise a Buffer is returned.
Returns the Diffie-Hellman prime in the specified encoding.\nIf encoding is provided a string is\nreturned; otherwise a Buffer is returned.
Returns the Diffie-Hellman private key in the specified encoding.\nIf encoding is provided a\nstring is returned; otherwise a Buffer is returned.
Returns the Diffie-Hellman public key in the specified encoding.\nIf encoding is provided a\nstring is returned; otherwise a Buffer is returned.
Sets the Diffie-Hellman private key. If the encoding argument is provided,\nprivateKey is expected\nto be a string. If no encoding is provided, privateKey is expected\nto be a Buffer, TypedArray, or DataView.
This function does not automatically compute the associated public key. Either\ndiffieHellman.setPublicKey() or diffieHellman.generateKeys() can be\nused to manually provide the public key or to automatically derive it.
diffieHellman.generateKeys()
Sets the Diffie-Hellman public key. If the encoding argument is provided,\npublicKey is expected\nto be a string. If no encoding is provided, publicKey is expected\nto be a Buffer, TypedArray, or DataView.
A bit field containing any warnings and/or errors resulting from a check\nperformed during initialization of the DiffieHellman object.
The following values are valid for this property (as defined in node:constants module):
node:constants
The DiffieHellmanGroup class takes a well-known modp group as its argument.\nIt works the same as DiffieHellman, except that it does not allow changing\nits keys after creation. In other words, it does not implement setPublicKey()\nor setPrivateKey() methods.
setPublicKey()
setPrivateKey()
const { createDiffieHellmanGroup } = await import('node:crypto');\nconst dh = createDiffieHellmanGroup('modp16');\n
const { createDiffieHellmanGroup } = require('node:crypto');\nconst dh = createDiffieHellmanGroup('modp16');\n
The following groups are supported:
'modp14'
'modp15'
'modp16'
'modp17'
'modp18'
The following groups are still supported but deprecated (see Caveats):
'modp1'
'modp2'
'modp5'
These deprecated groups might be removed in future versions of Node.js.
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.
crypto.createECDH()
import assert from 'node:assert';\n\nconst {\n createECDH\n} = await import('node:crypto');\n\n// Generate Alice's keys...\nconst alice = createECDH('secp521r1');\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = createECDH('secp521r1');\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n// OK\n
const assert = require('node:assert');\n\nconst {\n createECDH,\n} = require('node:crypto');\n\n// Generate Alice's keys...\nconst alice = createECDH('secp521r1');\nconst aliceKey = alice.generateKeys();\n\n// Generate Bob's keys...\nconst bob = createECDH('secp521r1');\nconst bobKey = bob.generateKeys();\n\n// Exchange and generate the secret...\nconst aliceSecret = alice.computeSecret(bobKey);\nconst bobSecret = bob.computeSecret(aliceKey);\n\nassert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));\n// OK\n
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.
curve
'compressed'
'uncompressed'
'hybrid'
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):
const {\n createECDH,\n ECDH\n} = await import('node:crypto');\n\nconst ecdh = createECDH('secp256k1');\necdh.generateKeys();\n\nconst compressedKey = ecdh.getPublicKey('hex', 'compressed');\n\nconst uncompressedKey = ECDH.convertKey(compressedKey,\n 'secp256k1',\n 'hex',\n 'hex',\n 'uncompressed');\n\n// The converted key and the uncompressed public key should be the same\nconsole.log(uncompressedKey === ecdh.getPublicKey('hex'));\n
const {\n createECDH,\n ECDH,\n} = require('node:crypto');\n\nconst ecdh = createECDH('secp256k1');\necdh.generateKeys();\n\nconst compressedKey = ecdh.getPublicKey('hex', 'compressed');\n\nconst uncompressedKey = ECDH.convertKey(compressedKey,\n 'secp256k1',\n 'hex',\n 'hex',\n 'uncompressed');\n\n// The converted key and the uncompressed public key should be the same\nconsole.log(uncompressedKey === ecdh.getPublicKey('hex'));\n
Computes the shared secret using otherPublicKey as the other\nparty's public key and returns the computed shared secret. The supplied\nkey is interpreted using specified inputEncoding, and the returned secret\nis encoded using the specified outputEncoding.\nIf the inputEncoding is not\nprovided, otherPublicKey is expected to be a Buffer, TypedArray, or\nDataView.
If outputEncoding is given a string will be returned; otherwise a\nBuffer is returned.
ecdh.computeSecret will throw an\nERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY error when otherPublicKey\nlies outside of the elliptic curve. Since otherPublicKey is\nusually supplied from a remote user over an insecure network,\nbe sure to handle this exception accordingly.
ecdh.computeSecret
ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY
Generates private and public EC Diffie-Hellman key values, and returns\nthe public key in the specified format and encoding. This key should be\ntransferred to the other party.
The format argument specifies point encoding and can be 'compressed' or\n'uncompressed'. If format is not specified, the point will be returned in\n'uncompressed' format.
If encoding is provided a string is returned; otherwise a Buffer\nis returned.
If encoding is specified, a string is returned; otherwise a Buffer is\nreturned.
The format argument specifies point encoding and can be 'compressed' or\n'uncompressed'. If format is not specified the point will be returned in\n'uncompressed' format.
Sets the EC Diffie-Hellman private key.\nIf encoding is provided, privateKey is expected\nto be a string; otherwise privateKey is expected to be a Buffer,\nTypedArray, or DataView.
If privateKey is not valid for the curve specified when the ECDH object was\ncreated, an error is thrown. Upon setting the private key, the associated\npublic point (key) is also generated and set in the ECDH object.
Sets the EC Diffie-Hellman public key.\nIf encoding is provided publicKey is expected to\nbe a string; otherwise a Buffer, TypedArray, or DataView is expected.
There is not normally a reason to call this method because ECDH\nonly requires a private key and the other party's public key to compute the\nshared secret. Typically either ecdh.generateKeys() or\necdh.setPrivateKey() will be called. The ecdh.setPrivateKey() method\nattempts to generate the public point/key associated with the private key being\nset.
ecdh.generateKeys()
ecdh.setPrivateKey()
const {\n createECDH,\n createHash\n} = await import('node:crypto');\n\nconst alice = createECDH('secp256k1');\nconst bob = createECDH('secp256k1');\n\n// This is a shortcut way of specifying one of Alice's previous private\n// keys. It would be unwise to use such a predictable private key in a real\n// application.\nalice.setPrivateKey(\n createHash('sha256').update('alice', 'utf8').digest()\n);\n\n// Bob uses a newly generated cryptographically strong\n// pseudorandom key pair\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n// aliceSecret and bobSecret should be the same shared secret value\nconsole.log(aliceSecret === bobSecret);\n
const {\n createECDH,\n createHash,\n} = require('node:crypto');\n\nconst alice = createECDH('secp256k1');\nconst bob = createECDH('secp256k1');\n\n// This is a shortcut way of specifying one of Alice's previous private\n// keys. It would be unwise to use such a predictable private key in a real\n// application.\nalice.setPrivateKey(\n createHash('sha256').update('alice', 'utf8').digest()\n);\n\n// Bob uses a newly generated cryptographically strong\n// pseudorandom key pair\nbob.generateKeys();\n\nconst aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');\nconst bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');\n\n// aliceSecret and bobSecret should be the same shared secret value\nconsole.log(aliceSecret === bobSecret);\n
The Hash class is a utility for creating hash digests of data. It can be\nused in one of two ways:
hash.update()
hash.digest()
The crypto.createHash() method is used to create Hash instances. Hash\nobjects are not to be created directly using the new keyword.
crypto.createHash()
Example: Using Hash objects as streams:
const {\n createHash\n} = await import('node:crypto');\n\nconst hash = createHash('sha256');\n\nhash.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = hash.read();\n if (data) {\n console.log(data.toString('hex'));\n // Prints:\n // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n }\n});\n\nhash.write('some data to hash');\nhash.end();\n
const {\n createHash,\n} = require('node:crypto');\n\nconst hash = createHash('sha256');\n\nhash.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = hash.read();\n if (data) {\n console.log(data.toString('hex'));\n // Prints:\n // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n }\n});\n\nhash.write('some data to hash');\nhash.end();\n
Example: Using Hash and piped streams:
import { createReadStream } from 'node:fs';\nimport { stdout } from 'node:process';\nconst { createHash } = await import('node:crypto');\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream('test.js');\ninput.pipe(hash).setEncoding('hex').pipe(stdout);\n
const { createReadStream } = require('node:fs');\nconst { createHash } = require('node:crypto');\nconst { stdout } = require('node:process');\n\nconst hash = createHash('sha256');\n\nconst input = createReadStream('test.js');\ninput.pipe(hash).setEncoding('hex').pipe(stdout);\n
Example: Using the hash.update() and hash.digest() methods:
const {\n createHash\n} = await import('node:crypto');\n\nconst hash = createHash('sha256');\n\nhash.update('some data to hash');\nconsole.log(hash.digest('hex'));\n// Prints:\n// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n
const {\n createHash,\n} = require('node:crypto');\n\nconst hash = createHash('sha256');\n\nhash.update('some data to hash');\nconsole.log(hash.digest('hex'));\n// Prints:\n// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50\n
Creates a new Hash object that contains a deep copy of the internal state\nof the current Hash object.
The optional options argument controls stream behavior. For XOF hash\nfunctions such as 'shake256', the outputLength option can be used to\nspecify the desired output length in bytes.
An error is thrown when an attempt is made to copy the Hash object after\nits hash.digest() method has been called.
// Calculate a rolling hash.\nconst {\n createHash\n} = await import('node:crypto');\n\nconst hash = createHash('sha256');\n\nhash.update('one');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('two');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('three');\nconsole.log(hash.copy().digest('hex'));\n\n// Etc.\n
// Calculate a rolling hash.\nconst {\n createHash,\n} = require('node:crypto');\n\nconst hash = createHash('sha256');\n\nhash.update('one');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('two');\nconsole.log(hash.copy().digest('hex'));\n\nhash.update('three');\nconsole.log(hash.copy().digest('hex'));\n\n// Etc.\n
Calculates the digest of all of the data passed to be hashed (using the\nhash.update() method).\nIf encoding is provided a string will be returned; otherwise\na Buffer is returned.
The Hash object can not be used again after hash.digest() method has been\ncalled. Multiple calls will cause an error to be thrown.
Updates the hash content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.
This can be called many times with new data as it is streamed.
The Hmac class is a utility for creating cryptographic HMAC digests. It can\nbe used in one of two ways:
hmac.update()
hmac.digest()
The crypto.createHmac() method is used to create Hmac instances. Hmac\nobjects are not to be created directly using the new keyword.
crypto.createHmac()
Example: Using Hmac objects as streams:
const {\n createHmac\n} = await import('node:crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nhmac.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = hmac.read();\n if (data) {\n console.log(data.toString('hex'));\n // Prints:\n // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n }\n});\n\nhmac.write('some data to hash');\nhmac.end();\n
const {\n createHmac,\n} = require('node:crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nhmac.on('readable', () => {\n // Only one element is going to be produced by the\n // hash stream.\n const data = hmac.read();\n if (data) {\n console.log(data.toString('hex'));\n // Prints:\n // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n }\n});\n\nhmac.write('some data to hash');\nhmac.end();\n
Example: Using Hmac and piped streams:
import { createReadStream } from 'node:fs';\nimport { stdout } from 'node:process';\nconst {\n createHmac\n} = await import('node:crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream('test.js');\ninput.pipe(hmac).pipe(stdout);\n
const {\n createReadStream,\n} = require('node:fs');\nconst {\n createHmac,\n} = require('node:crypto');\nconst { stdout } = require('node:process');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nconst input = createReadStream('test.js');\ninput.pipe(hmac).pipe(stdout);\n
Example: Using the hmac.update() and hmac.digest() methods:
const {\n createHmac\n} = await import('node:crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nhmac.update('some data to hash');\nconsole.log(hmac.digest('hex'));\n// Prints:\n// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n
const {\n createHmac,\n} = require('node:crypto');\n\nconst hmac = createHmac('sha256', 'a secret');\n\nhmac.update('some data to hash');\nconsole.log(hmac.digest('hex'));\n// Prints:\n// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e\n
Calculates the HMAC digest of all of the data passed using hmac.update().\nIf encoding is\nprovided a string is returned; otherwise a Buffer is returned;
The Hmac object can not be used again after hmac.digest() has been\ncalled. Multiple calls to hmac.digest() will result in an error being thrown.
Updates the Hmac content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.
Node.js uses a KeyObject class to represent a symmetric or asymmetric key,\nand each kind of key exposes different functions. The\ncrypto.createSecretKey(), crypto.createPublicKey() and\ncrypto.createPrivateKey() methods are used to create KeyObject\ninstances. KeyObject objects are not to be created directly using the new\nkeyword.
crypto.createSecretKey()
Most applications should consider using the new KeyObject API instead of\npassing keys as strings or Buffers due to improved security features.
KeyObject instances can be passed to other threads via postMessage().\nThe receiver obtains a cloned KeyObject, and the KeyObject does not need to\nbe listed in the transferList argument.
postMessage()
transferList
Example: Converting a CryptoKey instance to a KeyObject:
CryptoKey
const { webcrypto, KeyObject } = await import('node:crypto');\nconst { subtle } = webcrypto;\n\nconst key = await subtle.generateKey({\n name: 'HMAC',\n hash: 'SHA-256',\n length: 256\n}, true, ['sign', 'verify']);\n\nconst keyObject = KeyObject.from(key);\nconsole.log(keyObject.symmetricKeySize);\n// Prints: 32 (symmetric key size in bytes)\n
const {\n webcrypto: {\n subtle,\n },\n KeyObject,\n} = require('node:crypto');\n\n(async function() {\n const key = await subtle.generateKey({\n name: 'HMAC',\n hash: 'SHA-256',\n length: 256\n }, true, ['sign', 'verify']);\n\n const keyObject = KeyObject.from(key);\n console.log(keyObject.symmetricKeySize);\n // Prints: 32 (symmetric key size in bytes)\n})();\n
This property exists only on asymmetric keys. Depending on the type of the key,\nthis object contains information about the key. None of the information obtained\nthrough this property can be used to uniquely identify a key or to compromise\nthe security of the key.
For RSA-PSS keys, if the key material contains a RSASSA-PSS-params sequence,\nthe hashAlgorithm, mgf1HashAlgorithm, and saltLength properties will be\nset.
RSASSA-PSS-params
hashAlgorithm
mgf1HashAlgorithm
Other key details might be exposed via this API using additional attributes.
For asymmetric keys, this property represents the type of the key. Supported key\ntypes are:
'rsa'
'rsa-pss'
'dsa'
'ed25519'
'ed448'
This property is undefined for unrecognized KeyObject types and symmetric\nkeys.
For secret keys, this property represents the size of the key in bytes. This\nproperty is undefined for asymmetric keys.
Depending on the type of this KeyObject, this property is either\n'secret' for secret (symmetric) keys, 'public' for public (asymmetric) keys\nor 'private' for private (asymmetric) keys.
'secret'
For symmetric keys, the following encoding options can be used:
For public keys, the following encoding options can be used:
For private keys, the following encoding options can be used:
The result type depends on the selected encoding format, when PEM the\nresult is a string, when DER it will be a buffer containing the data\nencoded as DER, when JWK it will be an object.
When JWK encoding format was selected, all other encoding options are\nignored.
PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of\nthe cipher and format options. The PKCS#8 type can be used with any\nformat to encrypt any key algorithm (RSA, EC, or DH) by specifying a\ncipher. PKCS#1 and SEC1 can only be encrypted by specifying a cipher\nwhen the PEM format is used. For maximum compatibility, use PKCS#8 for\nencrypted private keys. Since PKCS#8 defines its own\nencryption mechanism, PEM-level encryption is not supported when encrypting\na PKCS#8 key. See RFC 5208 for PKCS#8 encryption and RFC 1421 for\nPKCS#1 and SEC1 encryption.
Returns true or false depending on whether the keys have exactly the same\ntype, value, and parameters. This method is not\nconstant time.
The Sign class is a utility for generating signatures. It can be used in one\nof two ways:
sign.sign()
sign.update()
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.
crypto.createSign()
Example: Using Sign and Verify objects as streams:
const {\n generateKeyPairSync,\n createSign,\n createVerify\n} = await import('node:crypto');\n\nconst { privateKey, publicKey } = generateKeyPairSync('ec', {\n namedCurve: 'sect239k1'\n});\n\nconst sign = createSign('SHA256');\nsign.write('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey, 'hex');\n\nconst verify = createVerify('SHA256');\nverify.write('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature, 'hex'));\n// Prints: true\n
const {\n generateKeyPairSync,\n createSign,\n createVerify,\n} = require('node:crypto');\n\nconst { privateKey, publicKey } = generateKeyPairSync('ec', {\n namedCurve: 'sect239k1'\n});\n\nconst sign = createSign('SHA256');\nsign.write('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey, 'hex');\n\nconst verify = createVerify('SHA256');\nverify.write('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature, 'hex'));\n// Prints: true\n
Example: Using the sign.update() and verify.update() methods:
verify.update()
const {\n generateKeyPairSync,\n createSign,\n createVerify\n} = await import('node:crypto');\n\nconst { privateKey, publicKey } = generateKeyPairSync('rsa', {\n modulusLength: 2048,\n});\n\nconst sign = createSign('SHA256');\nsign.update('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey);\n\nconst verify = createVerify('SHA256');\nverify.update('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature));\n// Prints: true\n
const {\n generateKeyPairSync,\n createSign,\n createVerify,\n} = require('node:crypto');\n\nconst { privateKey, publicKey } = generateKeyPairSync('rsa', {\n modulusLength: 2048,\n});\n\nconst sign = createSign('SHA256');\nsign.update('some data to sign');\nsign.end();\nconst signature = sign.sign(privateKey);\n\nconst verify = createVerify('SHA256');\nverify.update('some data to sign');\nverify.end();\nconsole.log(verify.verify(publicKey, signature));\n// Prints: true\n
Calculates the signature on all the data passed through using either\nsign.update() or sign.write().
sign.write()
If privateKey is not a KeyObject, this function behaves as if\nprivateKey had been passed to crypto.createPrivateKey(). If it is an\nobject, the following additional properties can be passed:
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, unless\nan MGF1 hash function has been specified as part of the key in compliance with\nsection 3.3 of RFC 4055.
If outputEncoding is provided a string is returned; otherwise a Buffer\nis returned.
The Sign object can not be again used after sign.sign() method has been\ncalled. Multiple calls to sign.sign() will result in an error being thrown.
Updates the Sign content with the given data, the encoding of which\nis given in inputEncoding.\nIf encoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.
The Verify class is a utility for verifying signatures. It can be used in one\nof two ways:
verify.verify()
The crypto.createVerify() method is used to create Verify instances.\nVerify objects are not to be created directly using the new keyword.
crypto.createVerify()
See Sign for examples.
Updates the Verify content with the given data, the encoding of which\nis given in inputEncoding.\nIf inputEncoding is not provided, and the data is a string, an\nencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, or\nDataView, then inputEncoding is ignored.
object
signatureEncoding
Verifies the provided data using the given object and signature.
If object is not a KeyObject, this function behaves as if\nobject had been passed to crypto.createPublicKey(). If it is an\nobject, the following additional properties can be passed:
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, unless\nan MGF1 hash function has been specified as part of the key in compliance with\nsection 3.3 of RFC 4055.
saltLength <integer> Salt length for when padding is\nRSA_PKCS1_PSS_PADDING. The special value\ncrypto.constants.RSA_PSS_SALTLEN_DIGEST sets the salt length to the digest\nsize, crypto.constants.RSA_PSS_SALTLEN_AUTO (default) causes it to be\ndetermined automatically.
crypto.constants.RSA_PSS_SALTLEN_AUTO
The signature argument is the previously calculated signature for the data, in\nthe signatureEncoding.\nIf a signatureEncoding is specified, the signature is expected to be a\nstring; otherwise signature is expected to be a Buffer,\nTypedArray, or DataView.
The verify object can not be used again after verify.verify() has been\ncalled. Multiple calls to verify.verify() will result in an error being\nthrown.
verify
Because public keys can be derived from private keys, a private key may\nbe passed instead of a public key.
Encapsulates an X509 certificate and provides read-only access to\nits information.
const { X509Certificate } = await import('node:crypto');\n\nconst x509 = new X509Certificate('{... pem encoded cert ...}');\n\nconsole.log(x509.subject);\n
const { X509Certificate } = require('node:crypto');\n\nconst x509 = new X509Certificate('{... pem encoded cert ...}');\n\nconsole.log(x509.subject);\n
The SHA-1 fingerprint of this certificate.
Because SHA-1 is cryptographically broken and because the security of SHA-1 is\nsignificantly worse than that of algorithms that are commonly used to sign\ncertificates, consider using x509.fingerprint256 instead.
x509.fingerprint256
The SHA-256 fingerprint of this certificate.
The SHA-512 fingerprint of this certificate.
Because computing the SHA-256 fingerprint is usually faster and because it is\nonly half the size of the SHA-512 fingerprint, x509.fingerprint256 may be\na better choice. While SHA-512 presumably provides a higher level of security in\ngeneral, the security of SHA-256 matches that of most algorithms that are\ncommonly used to sign certificates.
A textual representation of the certificate's authority information access\nextension.
This is a line feed separated list of access descriptions. Each line begins with\nthe access method and the kind of the access location, followed by a colon and\nthe value associated with the access location.
After the prefix denoting the access method and the kind of the access location,\nthe remainder of each line might be enclosed in quotes to indicate that the\nvalue is a JSON string literal. For backward compatibility, Node.js only uses\nJSON string literals within this property when necessary to avoid ambiguity.\nThird-party code should be prepared to handle both possible entry formats.
The issuer identification included in this certificate.
The issuer certificate or undefined if the issuer certificate is not\navailable.
An array detailing the key usages for this certificate.
The public key <KeyObject> for this certificate.
A Buffer containing the DER encoding of this certificate.
The serial number of this certificate.
Serial numbers are assigned by certificate authorities and do not uniquely\nidentify certificates. Consider using x509.fingerprint256 as a unique\nidentifier instead.
The complete subject of this certificate.
The subject alternative name specified for this certificate.
This is a comma-separated list of subject alternative names. Each entry begins\nwith a string identifying the kind of the subject alternative name followed by\na colon and the value associated with the entry.
Earlier versions of Node.js incorrectly assumed that it is safe to split this\nproperty at the two-character sequence ', ' (see CVE-2021-44532). However,\nboth malicious and legitimate certificates can contain subject alternative names\nthat include this sequence when represented as a string.
', '
After the prefix denoting the type of the entry, the remainder of each entry\nmight be enclosed in quotes to indicate that the value is a JSON string literal.\nFor backward compatibility, Node.js only uses JSON string literals within this\nproperty when necessary to avoid ambiguity. Third-party code should be prepared\nto handle both possible entry formats.
The date/time from which this certificate is considered valid.
The date/time until which this certificate is considered valid.
Checks whether the certificate matches the given email address.
If the 'subject' option is set to 'always' and if the subject alternative\nname extension either does not exist or does not contain a matching email\naddress, the certificate subject is considered.
'subject'
'always'
If the 'subject' option is set to 'default', the certificate subject is only\nconsidered if the subject alternative name extension either does not exist or\ndoes not contain any email addresses.
'default'
If the 'subject' option is set to 'never', the certificate subject is never\nconsidered, even if the certificate contains no subject alternative names.
'never'
Checks whether the certificate matches the given host name.
If the certificate matches the given host name, the matching subject name is\nreturned. The returned name might be an exact match (e.g., foo.example.com)\nor it might contain wildcards (e.g., *.example.com). Because host name\ncomparisons are case-insensitive, the returned subject name might also differ\nfrom the given name in capitalization.
foo.example.com
*.example.com
name
If the 'subject' option is set to 'always' and if the subject alternative\nname extension either does not exist or does not contain a matching DNS name,\nthe certificate subject is considered.
If the 'subject' option is set to 'default', the certificate subject is only\nconsidered if the subject alternative name extension either does not exist or\ndoes not contain any DNS names. This behavior is consistent with RFC 2818\n(\"HTTP Over TLS\").
Checks whether the certificate matches the given IP address (IPv4 or IPv6).
Only RFC 5280 iPAddress subject alternative names are considered, and they\nmust match the given ip address exactly. Other subject alternative names as\nwell as the subject field of the certificate are ignored.
iPAddress
ip
Checks whether this certificate was issued by the given otherCert.
otherCert
Checks whether the public key for this certificate is consistent with\nthe given private key.
There is no standard JSON encoding for X509 certificates. The\ntoJSON() method returns a string containing the PEM encoded\ncertificate.
toJSON()
Returns information about this certificate using the legacy\ncertificate object encoding.
Returns the PEM-encoded certificate.
Verifies that this certificate was signed by the given public key.\nDoes not perform any other validation checks on the certificate.