• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Crypto
2
3<!--introduced_in=v0.3.6-->
4
5> Stability: 2 - Stable
6
7<!-- source_link=lib/crypto.js -->
8
9The `crypto` module provides cryptographic functionality that includes a set of
10wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.
11
12Use `require('crypto')` to access this module.
13
14```js
15const crypto = require('crypto');
16
17const secret = 'abcdefg';
18const hash = crypto.createHmac('sha256', secret)
19                   .update('I love cupcakes')
20                   .digest('hex');
21console.log(hash);
22// Prints:
23//   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
24```
25
26## Determining if crypto support is unavailable
27
28It is possible for Node.js to be built without including support for the
29`crypto` module. In such cases, calling `require('crypto')` will result in an
30error being thrown.
31
32```js
33let crypto;
34try {
35  crypto = require('crypto');
36} catch (err) {
37  console.log('crypto support is disabled!');
38}
39```
40
41## Class: `Certificate`
42<!-- YAML
43added: v0.11.8
44-->
45
46SPKAC is a Certificate Signing Request mechanism originally implemented by
47Netscape and was specified formally as part of [HTML5's `keygen` element][].
48
49`<keygen>` is deprecated since [HTML 5.2][] and new projects
50should not use this element anymore.
51
52The `crypto` module provides the `Certificate` class for working with SPKAC
53data. The most common usage is handling output generated by the HTML5
54`<keygen>` element. Node.js uses [OpenSSL's SPKAC implementation][] internally.
55
56### `Certificate.exportChallenge(spkac)`
57<!-- YAML
58added: v9.0.0
59-->
60
61* `spkac` {string | Buffer | TypedArray | DataView}
62* Returns: {Buffer} The challenge component of the `spkac` data structure, which
63  includes a public key and a challenge.
64
65```js
66const { Certificate } = require('crypto');
67const spkac = getSpkacSomehow();
68const challenge = Certificate.exportChallenge(spkac);
69console.log(challenge.toString('utf8'));
70// Prints: the challenge as a UTF8 string
71```
72
73### `Certificate.exportPublicKey(spkac[, encoding])`
74<!-- YAML
75added: v9.0.0
76-->
77
78* `spkac` {string | Buffer | TypedArray | DataView}
79* `encoding` {string} The [encoding][] of the `spkac` string.
80* Returns: {Buffer} The public key component of the `spkac` data structure,
81  which includes a public key and a challenge.
82
83```js
84const { Certificate } = require('crypto');
85const spkac = getSpkacSomehow();
86const publicKey = Certificate.exportPublicKey(spkac);
87console.log(publicKey);
88// Prints: the public key as <Buffer ...>
89```
90
91### `Certificate.verifySpkac(spkac)`
92<!-- YAML
93added: v9.0.0
94-->
95
96* `spkac` {Buffer | TypedArray | DataView}
97* Returns: {boolean} `true` if the given `spkac` data structure is valid,
98  `false` otherwise.
99
100```js
101const { Certificate } = require('crypto');
102const spkac = getSpkacSomehow();
103console.log(Certificate.verifySpkac(Buffer.from(spkac)));
104// Prints: true or false
105```
106
107### Legacy API
108
109> Stability: 0 - Deprecated
110
111As a legacy interface, it is possible to create new instances of
112the `crypto.Certificate` class as illustrated in the examples below.
113
114#### `new crypto.Certificate()`
115
116Instances of the `Certificate` class can be created using the `new` keyword
117or by calling `crypto.Certificate()` as a function:
118
119```js
120const crypto = require('crypto');
121
122const cert1 = new crypto.Certificate();
123const cert2 = crypto.Certificate();
124```
125
126#### `certificate.exportChallenge(spkac)`
127<!-- YAML
128added: v0.11.8
129-->
130
131* `spkac` {string | Buffer | TypedArray | DataView}
132* Returns: {Buffer} The challenge component of the `spkac` data structure, which
133  includes a public key and a challenge.
134
135```js
136const cert = require('crypto').Certificate();
137const spkac = getSpkacSomehow();
138const challenge = cert.exportChallenge(spkac);
139console.log(challenge.toString('utf8'));
140// Prints: the challenge as a UTF8 string
141```
142
143#### `certificate.exportPublicKey(spkac)`
144<!-- YAML
145added: v0.11.8
146-->
147
148* `spkac` {string | Buffer | TypedArray | DataView}
149* Returns: {Buffer} The public key component of the `spkac` data structure,
150  which includes a public key and a challenge.
151
152```js
153const cert = require('crypto').Certificate();
154const spkac = getSpkacSomehow();
155const publicKey = cert.exportPublicKey(spkac);
156console.log(publicKey);
157// Prints: the public key as <Buffer ...>
158```
159
160#### `certificate.verifySpkac(spkac)`
161<!-- YAML
162added: v0.11.8
163-->
164
165* `spkac` {Buffer | TypedArray | DataView}
166* Returns: {boolean} `true` if the given `spkac` data structure is valid,
167  `false` otherwise.
168
169```js
170const cert = require('crypto').Certificate();
171const spkac = getSpkacSomehow();
172console.log(cert.verifySpkac(Buffer.from(spkac)));
173// Prints: true or false
174```
175
176## Class: `Cipher`
177<!-- YAML
178added: v0.1.94
179-->
180
181* Extends: {stream.Transform}
182
183Instances of the `Cipher` class are used to encrypt data. The class can be
184used in one of two ways:
185
186* As a [stream][] that is both readable and writable, where plain unencrypted
187  data is written to produce encrypted data on the readable side, or
188* Using the [`cipher.update()`][] and [`cipher.final()`][] methods to produce
189  the encrypted data.
190
191The [`crypto.createCipher()`][] or [`crypto.createCipheriv()`][] methods are
192used to create `Cipher` instances. `Cipher` objects are not to be created
193directly using the `new` keyword.
194
195Example: Using `Cipher` objects as streams:
196
197```js
198const crypto = require('crypto');
199
200const algorithm = 'aes-192-cbc';
201const password = 'Password used to generate key';
202// Key length is dependent on the algorithm. In this case for aes192, it is
203// 24 bytes (192 bits).
204// Use async `crypto.scrypt()` instead.
205const key = crypto.scryptSync(password, 'salt', 24);
206// Use `crypto.randomBytes()` to generate a random iv instead of the static iv
207// shown here.
208const iv = Buffer.alloc(16, 0); // Initialization vector.
209
210const cipher = crypto.createCipheriv(algorithm, key, iv);
211
212let encrypted = '';
213cipher.on('readable', () => {
214  let chunk;
215  while (null !== (chunk = cipher.read())) {
216    encrypted += chunk.toString('hex');
217  }
218});
219cipher.on('end', () => {
220  console.log(encrypted);
221  // Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa
222});
223
224cipher.write('some clear text data');
225cipher.end();
226```
227
228Example: Using `Cipher` and piped streams:
229
230```js
231const crypto = require('crypto');
232const fs = require('fs');
233
234const algorithm = 'aes-192-cbc';
235const password = 'Password used to generate key';
236// Use the async `crypto.scrypt()` instead.
237const key = crypto.scryptSync(password, 'salt', 24);
238// Use `crypto.randomBytes()` to generate a random iv instead of the static iv
239// shown here.
240const iv = Buffer.alloc(16, 0); // Initialization vector.
241
242const cipher = crypto.createCipheriv(algorithm, key, iv);
243
244const input = fs.createReadStream('test.js');
245const output = fs.createWriteStream('test.enc');
246
247input.pipe(cipher).pipe(output);
248```
249
250Example: Using the [`cipher.update()`][] and [`cipher.final()`][] methods:
251
252```js
253const crypto = require('crypto');
254
255const algorithm = 'aes-192-cbc';
256const password = 'Password used to generate key';
257// Use the async `crypto.scrypt()` instead.
258const key = crypto.scryptSync(password, 'salt', 24);
259// Use `crypto.randomBytes` to generate a random iv instead of the static iv
260// shown here.
261const iv = Buffer.alloc(16, 0); // Initialization vector.
262
263const cipher = crypto.createCipheriv(algorithm, key, iv);
264
265let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
266encrypted += cipher.final('hex');
267console.log(encrypted);
268// Prints: e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa
269```
270
271### `cipher.final([outputEncoding])`
272<!-- YAML
273added: v0.1.94
274-->
275
276* `outputEncoding` {string} The [encoding][] of the return value.
277* Returns: {Buffer | string} Any remaining enciphered contents.
278  If `outputEncoding` is specified, a string is
279  returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned.
280
281Once the `cipher.final()` method has been called, the `Cipher` object can no
282longer be used to encrypt data. Attempts to call `cipher.final()` more than
283once will result in an error being thrown.
284
285### `cipher.getAuthTag()`
286<!-- YAML
287added: v1.0.0
288-->
289
290* Returns: {Buffer} When using an authenticated encryption mode (`GCM`, `CCM`
291  and `OCB` are currently supported), the `cipher.getAuthTag()` method returns a
292  [`Buffer`][] containing the _authentication tag_ that has been computed from
293  the given data.
294
295The `cipher.getAuthTag()` method should only be called after encryption has
296been completed using the [`cipher.final()`][] method.
297
298### `cipher.setAAD(buffer[, options])`
299<!-- YAML
300added: v1.0.0
301-->
302
303* `buffer` {Buffer | TypedArray | DataView}
304* `options` {Object} [`stream.transform` options][]
305  * `plaintextLength` {number}
306* Returns: {Cipher} for method chaining.
307
308When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are
309currently supported), the `cipher.setAAD()` method sets the value used for the
310_additional authenticated data_ (AAD) input parameter.
311
312The `options` argument is optional for `GCM` and `OCB`. When using `CCM`, the
313`plaintextLength` option must be specified and its value must match the length
314of the plaintext in bytes. See [CCM mode][].
315
316The `cipher.setAAD()` method must be called before [`cipher.update()`][].
317
318### `cipher.setAutoPadding([autoPadding])`
319<!-- YAML
320added: v0.7.1
321-->
322
323* `autoPadding` {boolean} **Default:** `true`
324* Returns: {Cipher} for method chaining.
325
326When using block encryption algorithms, the `Cipher` class will automatically
327add padding to the input data to the appropriate block size. To disable the
328default padding call `cipher.setAutoPadding(false)`.
329
330When `autoPadding` is `false`, the length of the entire input data must be a
331multiple of the cipher's block size or [`cipher.final()`][] will throw an error.
332Disabling automatic padding is useful for non-standard padding, for instance
333using `0x0` instead of PKCS padding.
334
335The `cipher.setAutoPadding()` method must be called before
336[`cipher.final()`][].
337
338### `cipher.update(data[, inputEncoding][, outputEncoding])`
339<!-- YAML
340added: v0.1.94
341changes:
342  - version: v6.0.0
343    pr-url: https://github.com/nodejs/node/pull/5522
344    description: The default `inputEncoding` changed from `binary` to `utf8`.
345-->
346
347* `data` {string | Buffer | TypedArray | DataView}
348* `inputEncoding` {string} The [encoding][] of the data.
349* `outputEncoding` {string} The [encoding][] of the return value.
350* Returns: {Buffer | string}
351
352Updates the cipher with `data`. If the `inputEncoding` argument is given,
353the `data`
354argument is a string using the specified encoding. If the `inputEncoding`
355argument is not given, `data` must be a [`Buffer`][], `TypedArray`, or
356`DataView`. If `data` is a [`Buffer`][], `TypedArray`, or `DataView`, then
357`inputEncoding` is ignored.
358
359The `outputEncoding` specifies the output format of the enciphered
360data. If the `outputEncoding`
361is specified, a string using the specified encoding is returned. If no
362`outputEncoding` is provided, a [`Buffer`][] is returned.
363
364The `cipher.update()` method can be called multiple times with new data until
365[`cipher.final()`][] is called. Calling `cipher.update()` after
366[`cipher.final()`][] will result in an error being thrown.
367
368## Class: `Decipher`
369<!-- YAML
370added: v0.1.94
371-->
372
373* Extends: {stream.Transform}
374
375Instances of the `Decipher` class are used to decrypt data. The class can be
376used in one of two ways:
377
378* As a [stream][] that is both readable and writable, where plain encrypted
379  data is written to produce unencrypted data on the readable side, or
380* Using the [`decipher.update()`][] and [`decipher.final()`][] methods to
381  produce the unencrypted data.
382
383The [`crypto.createDecipher()`][] or [`crypto.createDecipheriv()`][] methods are
384used to create `Decipher` instances. `Decipher` objects are not to be created
385directly using the `new` keyword.
386
387Example: Using `Decipher` objects as streams:
388
389```js
390const crypto = require('crypto');
391
392const algorithm = 'aes-192-cbc';
393const password = 'Password used to generate key';
394// Key length is dependent on the algorithm. In this case for aes192, it is
395// 24 bytes (192 bits).
396// Use the async `crypto.scrypt()` instead.
397const key = crypto.scryptSync(password, 'salt', 24);
398// The IV is usually passed along with the ciphertext.
399const iv = Buffer.alloc(16, 0); // Initialization vector.
400
401const decipher = crypto.createDecipheriv(algorithm, key, iv);
402
403let decrypted = '';
404decipher.on('readable', () => {
405  while (null !== (chunk = decipher.read())) {
406    decrypted += chunk.toString('utf8');
407  }
408});
409decipher.on('end', () => {
410  console.log(decrypted);
411  // Prints: some clear text data
412});
413
414// Encrypted with same algorithm, key and iv.
415const encrypted =
416  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
417decipher.write(encrypted, 'hex');
418decipher.end();
419```
420
421Example: Using `Decipher` and piped streams:
422
423```js
424const crypto = require('crypto');
425const fs = require('fs');
426
427const algorithm = 'aes-192-cbc';
428const password = 'Password used to generate key';
429// Use the async `crypto.scrypt()` instead.
430const key = crypto.scryptSync(password, 'salt', 24);
431// The IV is usually passed along with the ciphertext.
432const iv = Buffer.alloc(16, 0); // Initialization vector.
433
434const decipher = crypto.createDecipheriv(algorithm, key, iv);
435
436const input = fs.createReadStream('test.enc');
437const output = fs.createWriteStream('test.js');
438
439input.pipe(decipher).pipe(output);
440```
441
442Example: Using the [`decipher.update()`][] and [`decipher.final()`][] methods:
443
444```js
445const crypto = require('crypto');
446
447const algorithm = 'aes-192-cbc';
448const password = 'Password used to generate key';
449// Use the async `crypto.scrypt()` instead.
450const key = crypto.scryptSync(password, 'salt', 24);
451// The IV is usually passed along with the ciphertext.
452const iv = Buffer.alloc(16, 0); // Initialization vector.
453
454const decipher = crypto.createDecipheriv(algorithm, key, iv);
455
456// Encrypted using same algorithm, key and iv.
457const encrypted =
458  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
459let decrypted = decipher.update(encrypted, 'hex', 'utf8');
460decrypted += decipher.final('utf8');
461console.log(decrypted);
462// Prints: some clear text data
463```
464
465### `decipher.final([outputEncoding])`
466<!-- YAML
467added: v0.1.94
468-->
469
470* `outputEncoding` {string} The [encoding][] of the return value.
471* Returns: {Buffer | string} Any remaining deciphered contents.
472  If `outputEncoding` is specified, a string is
473  returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned.
474
475Once the `decipher.final()` method has been called, the `Decipher` object can
476no longer be used to decrypt data. Attempts to call `decipher.final()` more
477than once will result in an error being thrown.
478
479### `decipher.setAAD(buffer[, options])`
480<!-- YAML
481added: v1.0.0
482changes:
483  - version: v7.2.0
484    pr-url: https://github.com/nodejs/node/pull/9398
485    description: This method now returns a reference to `decipher`.
486-->
487
488* `buffer` {Buffer | TypedArray | DataView}
489* `options` {Object} [`stream.transform` options][]
490  * `plaintextLength` {number}
491* Returns: {Decipher} for method chaining.
492
493When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are
494currently supported), the `decipher.setAAD()` method sets the value used for the
495_additional authenticated data_ (AAD) input parameter.
496
497The `options` argument is optional for `GCM`. When using `CCM`, the
498`plaintextLength` option must be specified and its value must match the length
499of the ciphertext in bytes. See [CCM mode][].
500
501The `decipher.setAAD()` method must be called before [`decipher.update()`][].
502
503### `decipher.setAuthTag(buffer)`
504<!-- YAML
505added: v1.0.0
506changes:
507  - version: v11.0.0
508    pr-url: https://github.com/nodejs/node/pull/17825
509    description: This method now throws if the GCM tag length is invalid.
510  - version: v7.2.0
511    pr-url: https://github.com/nodejs/node/pull/9398
512    description: This method now returns a reference to `decipher`.
513-->
514
515* `buffer` {Buffer | TypedArray | DataView}
516* Returns: {Decipher} for method chaining.
517
518When using an authenticated encryption mode (`GCM`, `CCM` and `OCB` are
519currently supported), the `decipher.setAuthTag()` method is used to pass in the
520received _authentication tag_. If no tag is provided, or if the cipher text
521has been tampered with, [`decipher.final()`][] will throw, indicating that the
522cipher text should be discarded due to failed authentication. If the tag length
523is invalid according to [NIST SP 800-38D][] or does not match the value of the
524`authTagLength` option, `decipher.setAuthTag()` will throw an error.
525
526The `decipher.setAuthTag()` method must be called before [`decipher.update()`][]
527for `CCM` mode or before [`decipher.final()`][] for `GCM` and `OCB` modes.
528`decipher.setAuthTag()` can only be called once.
529
530### `decipher.setAutoPadding([autoPadding])`
531<!-- YAML
532added: v0.7.1
533-->
534
535* `autoPadding` {boolean} **Default:** `true`
536* Returns: {Decipher} for method chaining.
537
538When data has been encrypted without standard block padding, calling
539`decipher.setAutoPadding(false)` will disable automatic padding to prevent
540[`decipher.final()`][] from checking for and removing padding.
541
542Turning auto padding off will only work if the input data's length is a
543multiple of the ciphers block size.
544
545The `decipher.setAutoPadding()` method must be called before
546[`decipher.final()`][].
547
548### `decipher.update(data[, inputEncoding][, outputEncoding])`
549<!-- YAML
550added: v0.1.94
551changes:
552  - version: v6.0.0
553    pr-url: https://github.com/nodejs/node/pull/5522
554    description: The default `inputEncoding` changed from `binary` to `utf8`.
555-->
556
557* `data` {string | Buffer | TypedArray | DataView}
558* `inputEncoding` {string} The [encoding][] of the `data` string.
559* `outputEncoding` {string} The [encoding][] of the return value.
560* Returns: {Buffer | string}
561
562Updates the decipher with `data`. If the `inputEncoding` argument is given,
563the `data`
564argument is a string using the specified encoding. If the `inputEncoding`
565argument is not given, `data` must be a [`Buffer`][]. If `data` is a
566[`Buffer`][] then `inputEncoding` is ignored.
567
568The `outputEncoding` specifies the output format of the enciphered
569data. If the `outputEncoding`
570is specified, a string using the specified encoding is returned. If no
571`outputEncoding` is provided, a [`Buffer`][] is returned.
572
573The `decipher.update()` method can be called multiple times with new data until
574[`decipher.final()`][] is called. Calling `decipher.update()` after
575[`decipher.final()`][] will result in an error being thrown.
576
577## Class: `DiffieHellman`
578<!-- YAML
579added: v0.5.0
580-->
581
582The `DiffieHellman` class is a utility for creating Diffie-Hellman key
583exchanges.
584
585Instances of the `DiffieHellman` class can be created using the
586[`crypto.createDiffieHellman()`][] function.
587
588```js
589const crypto = require('crypto');
590const assert = require('assert');
591
592// Generate Alice's keys...
593const alice = crypto.createDiffieHellman(2048);
594const aliceKey = alice.generateKeys();
595
596// Generate Bob's keys...
597const bob = crypto.createDiffieHellman(alice.getPrime(), alice.getGenerator());
598const bobKey = bob.generateKeys();
599
600// Exchange and generate the secret...
601const aliceSecret = alice.computeSecret(bobKey);
602const bobSecret = bob.computeSecret(aliceKey);
603
604// OK
605assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
606```
607
608### `diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])`
609<!-- YAML
610added: v0.5.0
611-->
612
613* `otherPublicKey` {string | Buffer | TypedArray | DataView}
614* `inputEncoding` {string} The [encoding][] of an `otherPublicKey` string.
615* `outputEncoding` {string} The [encoding][] of the return value.
616* Returns: {Buffer | string}
617
618Computes the shared secret using `otherPublicKey` as the other
619party's public key and returns the computed shared secret. The supplied
620key is interpreted using the specified `inputEncoding`, and secret is
621encoded using specified `outputEncoding`.
622If the `inputEncoding` is not
623provided, `otherPublicKey` is expected to be a [`Buffer`][],
624`TypedArray`, or `DataView`.
625
626If `outputEncoding` is given a string is returned; otherwise, a
627[`Buffer`][] is returned.
628
629### `diffieHellman.generateKeys([encoding])`
630<!-- YAML
631added: v0.5.0
632-->
633
634* `encoding` {string} The [encoding][] of the return value.
635* Returns: {Buffer | string}
636
637Generates private and public Diffie-Hellman key values, and returns
638the public key in the specified `encoding`. This key should be
639transferred to the other party.
640If `encoding` is provided a string is returned; otherwise a
641[`Buffer`][] is returned.
642
643### `diffieHellman.getGenerator([encoding])`
644<!-- YAML
645added: v0.5.0
646-->
647
648* `encoding` {string} The [encoding][] of the return value.
649* Returns: {Buffer | string}
650
651Returns the Diffie-Hellman generator in the specified `encoding`.
652If `encoding` is provided a string is
653returned; otherwise a [`Buffer`][] is returned.
654
655### `diffieHellman.getPrime([encoding])`
656<!-- YAML
657added: v0.5.0
658-->
659
660* `encoding` {string} The [encoding][] of the return value.
661* Returns: {Buffer | string}
662
663Returns the Diffie-Hellman prime in the specified `encoding`.
664If `encoding` is provided a string is
665returned; otherwise a [`Buffer`][] is returned.
666
667### `diffieHellman.getPrivateKey([encoding])`
668<!-- YAML
669added: v0.5.0
670-->
671
672* `encoding` {string} The [encoding][] of the return value.
673* Returns: {Buffer | string}
674
675Returns the Diffie-Hellman private key in the specified `encoding`.
676If `encoding` is provided a
677string is returned; otherwise a [`Buffer`][] is returned.
678
679### `diffieHellman.getPublicKey([encoding])`
680<!-- YAML
681added: v0.5.0
682-->
683
684* `encoding` {string} The [encoding][] of the return value.
685* Returns: {Buffer | string}
686
687Returns the Diffie-Hellman public key in the specified `encoding`.
688If `encoding` is provided a
689string is returned; otherwise a [`Buffer`][] is returned.
690
691### `diffieHellman.setPrivateKey(privateKey[, encoding])`
692<!-- YAML
693added: v0.5.0
694-->
695
696* `privateKey` {string | Buffer | TypedArray | DataView}
697* `encoding` {string} The [encoding][] of the `privateKey` string.
698
699Sets the Diffie-Hellman private key. If the `encoding` argument is provided,
700`privateKey` is expected
701to be a string. If no `encoding` is provided, `privateKey` is expected
702to be a [`Buffer`][], `TypedArray`, or `DataView`.
703
704### `diffieHellman.setPublicKey(publicKey[, encoding])`
705<!-- YAML
706added: v0.5.0
707-->
708
709* `publicKey` {string | Buffer | TypedArray | DataView}
710* `encoding` {string} The [encoding][] of the `publicKey` string.
711
712Sets the Diffie-Hellman public key. If the `encoding` argument is provided,
713`publicKey` is expected
714to be a string. If no `encoding` is provided, `publicKey` is expected
715to be a [`Buffer`][], `TypedArray`, or `DataView`.
716
717### `diffieHellman.verifyError`
718<!-- YAML
719added: v0.11.12
720-->
721
722A bit field containing any warnings and/or errors resulting from a check
723performed during initialization of the `DiffieHellman` object.
724
725The following values are valid for this property (as defined in `constants`
726module):
727
728* `DH_CHECK_P_NOT_SAFE_PRIME`
729* `DH_CHECK_P_NOT_PRIME`
730* `DH_UNABLE_TO_CHECK_GENERATOR`
731* `DH_NOT_SUITABLE_GENERATOR`
732
733## Class: `DiffieHellmanGroup`
734<!-- YAML
735added: v0.7.5
736-->
737
738The `DiffieHellmanGroup` class takes a well-known modp group as its argument.
739It works the same as `DiffieHellman`, except that it does not allow changing
740its keys after creation. In other words, it does not implement `setPublicKey()`
741or `setPrivateKey()` methods.
742
743```js
744const name = 'modp1';
745const dh = crypto.createDiffieHellmanGroup(name);
746```
747
748`name` is taken from [RFC 2412][] (modp1 and 2) and [RFC 3526][]:
749
750```console
751$ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h
752modp1  #  768 bits
753modp2  # 1024 bits
754modp5  # 1536 bits
755modp14 # 2048 bits
756modp15 # etc.
757modp16
758modp17
759modp18
760```
761
762## Class: `ECDH`
763<!-- YAML
764added: v0.11.14
765-->
766
767The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)
768key exchanges.
769
770Instances of the `ECDH` class can be created using the
771[`crypto.createECDH()`][] function.
772
773```js
774const crypto = require('crypto');
775const assert = require('assert');
776
777// Generate Alice's keys...
778const alice = crypto.createECDH('secp521r1');
779const aliceKey = alice.generateKeys();
780
781// Generate Bob's keys...
782const bob = crypto.createECDH('secp521r1');
783const bobKey = bob.generateKeys();
784
785// Exchange and generate the secret...
786const aliceSecret = alice.computeSecret(bobKey);
787const bobSecret = bob.computeSecret(aliceKey);
788
789assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
790// OK
791```
792
793### Static method: `ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])`
794<!-- YAML
795added: v10.0.0
796-->
797
798* `key` {string | Buffer | TypedArray | DataView}
799* `curve` {string}
800* `inputEncoding` {string} The [encoding][] of the `key` string.
801* `outputEncoding` {string} The [encoding][] of the return value.
802* `format` {string} **Default:** `'uncompressed'`
803* Returns: {Buffer | string}
804
805Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the
806format specified by `format`. The `format` argument specifies point encoding
807and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is
808interpreted using the specified `inputEncoding`, and the returned key is encoded
809using the specified `outputEncoding`.
810
811Use [`crypto.getCurves()`][] to obtain a list of available curve names.
812On recent OpenSSL releases, `openssl ecparam -list_curves` will also display
813the name and description of each available elliptic curve.
814
815If `format` is not specified the point will be returned in `'uncompressed'`
816format.
817
818If the `inputEncoding` is not provided, `key` is expected to be a [`Buffer`][],
819`TypedArray`, or `DataView`.
820
821Example (uncompressing a key):
822
823```js
824const { createECDH, ECDH } = require('crypto');
825
826const ecdh = createECDH('secp256k1');
827ecdh.generateKeys();
828
829const compressedKey = ecdh.getPublicKey('hex', 'compressed');
830
831const uncompressedKey = ECDH.convertKey(compressedKey,
832                                        'secp256k1',
833                                        'hex',
834                                        'hex',
835                                        'uncompressed');
836
837// The converted key and the uncompressed public key should be the same
838console.log(uncompressedKey === ecdh.getPublicKey('hex'));
839```
840
841### `ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])`
842<!-- YAML
843added: v0.11.14
844changes:
845  - version: v10.0.0
846    pr-url: https://github.com/nodejs/node/pull/16849
847    description: Changed error format to better support invalid public key
848                 error.
849  - version: v6.0.0
850    pr-url: https://github.com/nodejs/node/pull/5522
851    description: The default `inputEncoding` changed from `binary` to `utf8`.
852-->
853
854* `otherPublicKey` {string | Buffer | TypedArray | DataView}
855* `inputEncoding` {string} The [encoding][] of the `otherPublicKey` string.
856* `outputEncoding` {string} The [encoding][] of the return value.
857* Returns: {Buffer | string}
858
859Computes the shared secret using `otherPublicKey` as the other
860party's public key and returns the computed shared secret. The supplied
861key is interpreted using specified `inputEncoding`, and the returned secret
862is encoded using the specified `outputEncoding`.
863If the `inputEncoding` is not
864provided, `otherPublicKey` is expected to be a [`Buffer`][], `TypedArray`, or
865`DataView`.
866
867If `outputEncoding` is given a string will be returned; otherwise a
868[`Buffer`][] is returned.
869
870`ecdh.computeSecret` will throw an
871`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`
872lies outside of the elliptic curve. Since `otherPublicKey` is
873usually supplied from a remote user over an insecure network,
874be sure to handle this exception accordingly.
875
876### `ecdh.generateKeys([encoding[, format]])`
877<!-- YAML
878added: v0.11.14
879-->
880
881* `encoding` {string} The [encoding][] of the return value.
882* `format` {string} **Default:** `'uncompressed'`
883* Returns: {Buffer | string}
884
885Generates private and public EC Diffie-Hellman key values, and returns
886the public key in the specified `format` and `encoding`. This key should be
887transferred to the other party.
888
889The `format` argument specifies point encoding and can be `'compressed'` or
890`'uncompressed'`. If `format` is not specified, the point will be returned in
891`'uncompressed'` format.
892
893If `encoding` is provided a string is returned; otherwise a [`Buffer`][]
894is returned.
895
896### `ecdh.getPrivateKey([encoding])`
897<!-- YAML
898added: v0.11.14
899-->
900
901* `encoding` {string} The [encoding][] of the return value.
902* Returns: {Buffer | string} The EC Diffie-Hellman in the specified `encoding`.
903
904If `encoding` is specified, a string is returned; otherwise a [`Buffer`][] is
905returned.
906
907### `ecdh.getPublicKey([encoding][, format])`
908<!-- YAML
909added: v0.11.14
910-->
911
912* `encoding` {string} The [encoding][] of the return value.
913* `format` {string} **Default:** `'uncompressed'`
914* Returns: {Buffer | string} The EC Diffie-Hellman public key in the specified
915  `encoding` and `format`.
916
917The `format` argument specifies point encoding and can be `'compressed'` or
918`'uncompressed'`. If `format` is not specified the point will be returned in
919`'uncompressed'` format.
920
921If `encoding` is specified, a string is returned; otherwise a [`Buffer`][] is
922returned.
923
924### `ecdh.setPrivateKey(privateKey[, encoding])`
925<!-- YAML
926added: v0.11.14
927-->
928
929* `privateKey` {string | Buffer | TypedArray | DataView}
930* `encoding` {string} The [encoding][] of the `privateKey` string.
931
932Sets the EC Diffie-Hellman private key.
933If `encoding` is provided, `privateKey` is expected
934to be a string; otherwise `privateKey` is expected to be a [`Buffer`][],
935`TypedArray`, or `DataView`.
936
937If `privateKey` is not valid for the curve specified when the `ECDH` object was
938created, an error is thrown. Upon setting the private key, the associated
939public point (key) is also generated and set in the `ECDH` object.
940
941### `ecdh.setPublicKey(publicKey[, encoding])`
942<!-- YAML
943added: v0.11.14
944deprecated: v5.2.0
945-->
946
947> Stability: 0 - Deprecated
948
949* `publicKey` {string | Buffer | TypedArray | DataView}
950* `encoding` {string} The [encoding][] of the `publicKey` string.
951
952Sets the EC Diffie-Hellman public key.
953If `encoding` is provided `publicKey` is expected to
954be a string; otherwise a [`Buffer`][], `TypedArray`, or `DataView` is expected.
955
956There is not normally a reason to call this method because `ECDH`
957only requires a private key and the other party's public key to compute the
958shared secret. Typically either [`ecdh.generateKeys()`][] or
959[`ecdh.setPrivateKey()`][] will be called. The [`ecdh.setPrivateKey()`][] method
960attempts to generate the public point/key associated with the private key being
961set.
962
963Example (obtaining a shared secret):
964
965```js
966const crypto = require('crypto');
967const alice = crypto.createECDH('secp256k1');
968const bob = crypto.createECDH('secp256k1');
969
970// This is a shortcut way of specifying one of Alice's previous private
971// keys. It would be unwise to use such a predictable private key in a real
972// application.
973alice.setPrivateKey(
974  crypto.createHash('sha256').update('alice', 'utf8').digest()
975);
976
977// Bob uses a newly generated cryptographically strong
978// pseudorandom key pair
979bob.generateKeys();
980
981const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
982const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
983
984// aliceSecret and bobSecret should be the same shared secret value
985console.log(aliceSecret === bobSecret);
986```
987
988## Class: `Hash`
989<!-- YAML
990added: v0.1.92
991-->
992
993* Extends: {stream.Transform}
994
995The `Hash` class is a utility for creating hash digests of data. It can be
996used in one of two ways:
997
998* As a [stream][] that is both readable and writable, where data is written
999  to produce a computed hash digest on the readable side, or
1000* Using the [`hash.update()`][] and [`hash.digest()`][] methods to produce the
1001  computed hash.
1002
1003The [`crypto.createHash()`][] method is used to create `Hash` instances. `Hash`
1004objects are not to be created directly using the `new` keyword.
1005
1006Example: Using `Hash` objects as streams:
1007
1008```js
1009const crypto = require('crypto');
1010const hash = crypto.createHash('sha256');
1011
1012hash.on('readable', () => {
1013  // Only one element is going to be produced by the
1014  // hash stream.
1015  const data = hash.read();
1016  if (data) {
1017    console.log(data.toString('hex'));
1018    // Prints:
1019    //   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
1020  }
1021});
1022
1023hash.write('some data to hash');
1024hash.end();
1025```
1026
1027Example: Using `Hash` and piped streams:
1028
1029```js
1030const crypto = require('crypto');
1031const fs = require('fs');
1032const hash = crypto.createHash('sha256');
1033
1034const input = fs.createReadStream('test.js');
1035input.pipe(hash).setEncoding('hex').pipe(process.stdout);
1036```
1037
1038Example: Using the [`hash.update()`][] and [`hash.digest()`][] methods:
1039
1040```js
1041const crypto = require('crypto');
1042const hash = crypto.createHash('sha256');
1043
1044hash.update('some data to hash');
1045console.log(hash.digest('hex'));
1046// Prints:
1047//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
1048```
1049
1050### `hash.copy([options])`
1051<!-- YAML
1052added: v13.1.0
1053-->
1054
1055* `options` {Object} [`stream.transform` options][]
1056* Returns: {Hash}
1057
1058Creates a new `Hash` object that contains a deep copy of the internal state
1059of the current `Hash` object.
1060
1061The optional `options` argument controls stream behavior. For XOF hash
1062functions such as `'shake256'`, the `outputLength` option can be used to
1063specify the desired output length in bytes.
1064
1065An error is thrown when an attempt is made to copy the `Hash` object after
1066its [`hash.digest()`][] method has been called.
1067
1068```js
1069// Calculate a rolling hash.
1070const crypto = require('crypto');
1071const hash = crypto.createHash('sha256');
1072
1073hash.update('one');
1074console.log(hash.copy().digest('hex'));
1075
1076hash.update('two');
1077console.log(hash.copy().digest('hex'));
1078
1079hash.update('three');
1080console.log(hash.copy().digest('hex'));
1081
1082// Etc.
1083```
1084
1085### `hash.digest([encoding])`
1086<!-- YAML
1087added: v0.1.92
1088-->
1089
1090* `encoding` {string} The [encoding][] of the return value.
1091* Returns: {Buffer | string}
1092
1093Calculates the digest of all of the data passed to be hashed (using the
1094[`hash.update()`][] method).
1095If `encoding` is provided a string will be returned; otherwise
1096a [`Buffer`][] is returned.
1097
1098The `Hash` object can not be used again after `hash.digest()` method has been
1099called. Multiple calls will cause an error to be thrown.
1100
1101### `hash.update(data[, inputEncoding])`
1102<!-- YAML
1103added: v0.1.92
1104changes:
1105  - version: v6.0.0
1106    pr-url: https://github.com/nodejs/node/pull/5522
1107    description: The default `inputEncoding` changed from `binary` to `utf8`.
1108-->
1109
1110* `data` {string | Buffer | TypedArray | DataView}
1111* `inputEncoding` {string} The [encoding][] of the `data` string.
1112
1113Updates the hash content with the given `data`, the encoding of which
1114is given in `inputEncoding`.
1115If `encoding` is not provided, and the `data` is a string, an
1116encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or
1117`DataView`, then `inputEncoding` is ignored.
1118
1119This can be called many times with new data as it is streamed.
1120
1121## Class: `Hmac`
1122<!-- YAML
1123added: v0.1.94
1124-->
1125
1126* Extends: {stream.Transform}
1127
1128The `Hmac` class is a utility for creating cryptographic HMAC digests. It can
1129be used in one of two ways:
1130
1131* As a [stream][] that is both readable and writable, where data is written
1132  to produce a computed HMAC digest on the readable side, or
1133* Using the [`hmac.update()`][] and [`hmac.digest()`][] methods to produce the
1134  computed HMAC digest.
1135
1136The [`crypto.createHmac()`][] method is used to create `Hmac` instances. `Hmac`
1137objects are not to be created directly using the `new` keyword.
1138
1139Example: Using `Hmac` objects as streams:
1140
1141```js
1142const crypto = require('crypto');
1143const hmac = crypto.createHmac('sha256', 'a secret');
1144
1145hmac.on('readable', () => {
1146  // Only one element is going to be produced by the
1147  // hash stream.
1148  const data = hmac.read();
1149  if (data) {
1150    console.log(data.toString('hex'));
1151    // Prints:
1152    //   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
1153  }
1154});
1155
1156hmac.write('some data to hash');
1157hmac.end();
1158```
1159
1160Example: Using `Hmac` and piped streams:
1161
1162```js
1163const crypto = require('crypto');
1164const fs = require('fs');
1165const hmac = crypto.createHmac('sha256', 'a secret');
1166
1167const input = fs.createReadStream('test.js');
1168input.pipe(hmac).pipe(process.stdout);
1169```
1170
1171Example: Using the [`hmac.update()`][] and [`hmac.digest()`][] methods:
1172
1173```js
1174const crypto = require('crypto');
1175const hmac = crypto.createHmac('sha256', 'a secret');
1176
1177hmac.update('some data to hash');
1178console.log(hmac.digest('hex'));
1179// Prints:
1180//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
1181```
1182
1183### `hmac.digest([encoding])`
1184<!-- YAML
1185added: v0.1.94
1186-->
1187
1188* `encoding` {string} The [encoding][] of the return value.
1189* Returns: {Buffer | string}
1190
1191Calculates the HMAC digest of all of the data passed using [`hmac.update()`][].
1192If `encoding` is
1193provided a string is returned; otherwise a [`Buffer`][] is returned;
1194
1195The `Hmac` object can not be used again after `hmac.digest()` has been
1196called. Multiple calls to `hmac.digest()` will result in an error being thrown.
1197
1198### `hmac.update(data[, inputEncoding])`
1199<!-- YAML
1200added: v0.1.94
1201changes:
1202  - version: v6.0.0
1203    pr-url: https://github.com/nodejs/node/pull/5522
1204    description: The default `inputEncoding` changed from `binary` to `utf8`.
1205-->
1206
1207* `data` {string | Buffer | TypedArray | DataView}
1208* `inputEncoding` {string} The [encoding][] of the `data` string.
1209
1210Updates the `Hmac` content with the given `data`, the encoding of which
1211is given in `inputEncoding`.
1212If `encoding` is not provided, and the `data` is a string, an
1213encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or
1214`DataView`, then `inputEncoding` is ignored.
1215
1216This can be called many times with new data as it is streamed.
1217
1218## Class: `KeyObject`
1219<!-- YAML
1220added: v11.6.0
1221changes:
1222  - version: v14.5.0
1223    pr-url: https://github.com/nodejs/node/pull/33360
1224    description: Instances of this class can now be passed to worker threads
1225                 using `postMessage`.
1226  - version: v11.13.0
1227    pr-url: https://github.com/nodejs/node/pull/26438
1228    description: This class is now exported.
1229-->
1230
1231Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key,
1232and each kind of key exposes different functions. The
1233[`crypto.createSecretKey()`][], [`crypto.createPublicKey()`][] and
1234[`crypto.createPrivateKey()`][] methods are used to create `KeyObject`
1235instances. `KeyObject` objects are not to be created directly using the `new`
1236keyword.
1237
1238Most applications should consider using the new `KeyObject` API instead of
1239passing keys as strings or `Buffer`s due to improved security features.
1240
1241`KeyObject` instances can be passed to other threads via [`postMessage()`][].
1242The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to
1243be listed in the `transferList` argument.
1244
1245### `keyObject.asymmetricKeyType`
1246<!-- YAML
1247added: v11.6.0
1248changes:
1249  - version: v13.9.0
1250    pr-url: https://github.com/nodejs/node/pull/31178
1251    description: Added support for `'dh'`.
1252  - version: v12.0.0
1253    pr-url: https://github.com/nodejs/node/pull/26960
1254    description: Added support for `'rsa-pss'`.
1255  - version: v12.0.0
1256    pr-url: https://github.com/nodejs/node/pull/26786
1257    description: This property now returns `undefined` for KeyObject
1258                 instances of unrecognized type instead of aborting.
1259  - version: v12.0.0
1260    pr-url: https://github.com/nodejs/node/pull/26774
1261    description: Added support for `'x25519'` and `'x448'`.
1262  - version: v12.0.0
1263    pr-url: https://github.com/nodejs/node/pull/26319
1264    description: Added support for `'ed25519'` and `'ed448'`.
1265-->
1266
1267* {string}
1268
1269For asymmetric keys, this property represents the type of the key. Supported key
1270types are:
1271
1272* `'rsa'` (OID 1.2.840.113549.1.1.1)
1273* `'rsa-pss'` (OID 1.2.840.113549.1.1.10)
1274* `'dsa'` (OID 1.2.840.10040.4.1)
1275* `'ec'` (OID 1.2.840.10045.2.1)
1276* `'x25519'` (OID 1.3.101.110)
1277* `'x448'` (OID 1.3.101.111)
1278* `'ed25519'` (OID 1.3.101.112)
1279* `'ed448'` (OID 1.3.101.113)
1280* `'dh'` (OID 1.2.840.113549.1.3.1)
1281
1282This property is `undefined` for unrecognized `KeyObject` types and symmetric
1283keys.
1284
1285### `keyObject.export([options])`
1286<!-- YAML
1287added: v11.6.0
1288-->
1289
1290* `options`: {Object}
1291* Returns: {string | Buffer}
1292
1293For symmetric keys, this function allocates a `Buffer` containing the key
1294material and ignores any options.
1295
1296For asymmetric keys, the `options` parameter is used to determine the export
1297format.
1298
1299For public keys, the following encoding options can be used:
1300
1301* `type`: {string} Must be one of `'pkcs1'` (RSA only) or `'spki'`.
1302* `format`: {string} Must be `'pem'` or `'der'`.
1303
1304For private keys, the following encoding options can be used:
1305
1306* `type`: {string} Must be one of `'pkcs1'` (RSA only), `'pkcs8'` or
1307  `'sec1'` (EC only).
1308* `format`: {string} Must be `'pem'` or `'der'`.
1309* `cipher`: {string} If specified, the private key will be encrypted with
1310   the given `cipher` and `passphrase` using PKCS#5 v2.0 password based
1311   encryption.
1312* `passphrase`: {string | Buffer} The passphrase to use for encryption, see
1313  `cipher`.
1314
1315When PEM encoding was selected, the result will be a string, otherwise it will
1316be a buffer containing the data encoded as DER.
1317
1318PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of
1319the `cipher` and `format` options. The PKCS#8 `type` can be used with any
1320`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a
1321`cipher`. PKCS#1 and SEC1 can only be encrypted by specifying a `cipher`
1322when the PEM `format` is used. For maximum compatibility, use PKCS#8 for
1323encrypted private keys. Since PKCS#8 defines its own
1324encryption mechanism, PEM-level encryption is not supported when encrypting
1325a PKCS#8 key. See [RFC 5208][] for PKCS#8 encryption and [RFC 1421][] for
1326PKCS#1 and SEC1 encryption.
1327
1328### `keyObject.symmetricKeySize`
1329<!-- YAML
1330added: v11.6.0
1331-->
1332
1333* {number}
1334
1335For secret keys, this property represents the size of the key in bytes. This
1336property is `undefined` for asymmetric keys.
1337
1338### `keyObject.type`
1339<!-- YAML
1340added: v11.6.0
1341-->
1342
1343* {string}
1344
1345Depending on the type of this `KeyObject`, this property is either
1346`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys
1347or `'private'` for private (asymmetric) keys.
1348
1349## Class: `Sign`
1350<!-- YAML
1351added: v0.1.92
1352-->
1353
1354* Extends: {stream.Writable}
1355
1356The `Sign` class is a utility for generating signatures. It can be used in one
1357of two ways:
1358
1359* As a writable [stream][], where data to be signed is written and the
1360  [`sign.sign()`][] method is used to generate and return the signature, or
1361* Using the [`sign.update()`][] and [`sign.sign()`][] methods to produce the
1362  signature.
1363
1364The [`crypto.createSign()`][] method is used to create `Sign` instances. The
1365argument is the string name of the hash function to use. `Sign` objects are not
1366to be created directly using the `new` keyword.
1367
1368Example: Using `Sign` and [`Verify`][] objects as streams:
1369
1370```js
1371const crypto = require('crypto');
1372
1373const { privateKey, publicKey } = crypto.generateKeyPairSync('ec', {
1374  namedCurve: 'sect239k1'
1375});
1376
1377const sign = crypto.createSign('SHA256');
1378sign.write('some data to sign');
1379sign.end();
1380const signature = sign.sign(privateKey, 'hex');
1381
1382const verify = crypto.createVerify('SHA256');
1383verify.write('some data to sign');
1384verify.end();
1385console.log(verify.verify(publicKey, signature, 'hex'));
1386// Prints: true
1387```
1388
1389Example: Using the [`sign.update()`][] and [`verify.update()`][] methods:
1390
1391```js
1392const crypto = require('crypto');
1393
1394const { privateKey, publicKey } = crypto.generateKeyPairSync('rsa', {
1395  modulusLength: 2048,
1396});
1397
1398const sign = crypto.createSign('SHA256');
1399sign.update('some data to sign');
1400sign.end();
1401const signature = sign.sign(privateKey);
1402
1403const verify = crypto.createVerify('SHA256');
1404verify.update('some data to sign');
1405verify.end();
1406console.log(verify.verify(publicKey, signature));
1407// Prints: true
1408```
1409
1410### `sign.sign(privateKey[, outputEncoding])`
1411<!-- YAML
1412added: v0.1.92
1413changes:
1414  - version:
1415     - v13.2.0
1416     - v12.16.0
1417    pr-url: https://github.com/nodejs/node/pull/29292
1418    description: This function now supports IEEE-P1363 DSA and ECDSA signatures.
1419  - version: v12.0.0
1420    pr-url: https://github.com/nodejs/node/pull/26960
1421    description: This function now supports RSA-PSS keys.
1422  - version: v11.6.0
1423    pr-url: https://github.com/nodejs/node/pull/24234
1424    description: This function now supports key objects.
1425  - version: v8.0.0
1426    pr-url: https://github.com/nodejs/node/pull/11705
1427    description: Support for RSASSA-PSS and additional options was added.
1428-->
1429
1430* `privateKey` {Object | string | Buffer | KeyObject}
1431  * `dsaEncoding` {string}
1432  * `padding` {integer}
1433  * `saltLength` {integer}
1434* `outputEncoding` {string} The [encoding][] of the return value.
1435* Returns: {Buffer | string}
1436
1437Calculates the signature on all the data passed through using either
1438[`sign.update()`][] or [`sign.write()`][stream-writable-write].
1439
1440If `privateKey` is not a [`KeyObject`][], this function behaves as if
1441`privateKey` had been passed to [`crypto.createPrivateKey()`][]. If it is an
1442object, the following additional properties can be passed:
1443
1444* `dsaEncoding` {string} For DSA and ECDSA, this option specifies the
1445  format of the generated signature. It can be one of the following:
1446  * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`.
1447  * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363.
1448* `padding` {integer} Optional padding value for RSA, one of the following:
1449  * `crypto.constants.RSA_PKCS1_PADDING` (default)
1450  * `crypto.constants.RSA_PKCS1_PSS_PADDING`
1451
1452  `RSA_PKCS1_PSS_PADDING` will use MGF1 with the same hash function
1453  used to sign the message as specified in section 3.1 of [RFC 4055][], unless
1454  an MGF1 hash function has been specified as part of the key in compliance with
1455  section 3.3 of [RFC 4055][].
1456* `saltLength` {integer} Salt length for when padding is
1457  `RSA_PKCS1_PSS_PADDING`. The special value
1458  `crypto.constants.RSA_PSS_SALTLEN_DIGEST` sets the salt length to the digest
1459  size, `crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN` (default) sets it to the
1460  maximum permissible value.
1461
1462If `outputEncoding` is provided a string is returned; otherwise a [`Buffer`][]
1463is returned.
1464
1465The `Sign` object can not be again used after `sign.sign()` method has been
1466called. Multiple calls to `sign.sign()` will result in an error being thrown.
1467
1468### `sign.update(data[, inputEncoding])`
1469<!-- YAML
1470added: v0.1.92
1471changes:
1472  - version: v6.0.0
1473    pr-url: https://github.com/nodejs/node/pull/5522
1474    description: The default `inputEncoding` changed from `binary` to `utf8`.
1475-->
1476
1477* `data` {string | Buffer | TypedArray | DataView}
1478* `inputEncoding` {string} The [encoding][] of the `data` string.
1479
1480Updates the `Sign` content with the given `data`, the encoding of which
1481is given in `inputEncoding`.
1482If `encoding` is not provided, and the `data` is a string, an
1483encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or
1484`DataView`, then `inputEncoding` is ignored.
1485
1486This can be called many times with new data as it is streamed.
1487
1488## Class: `Verify`
1489<!-- YAML
1490added: v0.1.92
1491-->
1492
1493* Extends: {stream.Writable}
1494
1495The `Verify` class is a utility for verifying signatures. It can be used in one
1496of two ways:
1497
1498* As a writable [stream][] where written data is used to validate against the
1499  supplied signature, or
1500* Using the [`verify.update()`][] and [`verify.verify()`][] methods to verify
1501  the signature.
1502
1503The [`crypto.createVerify()`][] method is used to create `Verify` instances.
1504`Verify` objects are not to be created directly using the `new` keyword.
1505
1506See [`Sign`][] for examples.
1507
1508### `verify.update(data[, inputEncoding])`
1509<!-- YAML
1510added: v0.1.92
1511changes:
1512  - version: v6.0.0
1513    pr-url: https://github.com/nodejs/node/pull/5522
1514    description: The default `inputEncoding` changed from `binary` to `utf8`.
1515-->
1516
1517* `data` {string | Buffer | TypedArray | DataView}
1518* `inputEncoding` {string} The [encoding][] of the `data` string.
1519
1520Updates the `Verify` content with the given `data`, the encoding of which
1521is given in `inputEncoding`.
1522If `inputEncoding` is not provided, and the `data` is a string, an
1523encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or
1524`DataView`, then `inputEncoding` is ignored.
1525
1526This can be called many times with new data as it is streamed.
1527
1528### `verify.verify(object, signature[, signatureEncoding])`
1529<!-- YAML
1530added: v0.1.92
1531changes:
1532  - version:
1533     - v13.2.0
1534     - v12.16.0
1535    pr-url: https://github.com/nodejs/node/pull/29292
1536    description: This function now supports IEEE-P1363 DSA and ECDSA signatures.
1537  - version: v12.0.0
1538    pr-url: https://github.com/nodejs/node/pull/26960
1539    description: This function now supports RSA-PSS keys.
1540  - version: v11.7.0
1541    pr-url: https://github.com/nodejs/node/pull/25217
1542    description: The key can now be a private key.
1543  - version: v8.0.0
1544    pr-url: https://github.com/nodejs/node/pull/11705
1545    description: Support for RSASSA-PSS and additional options was added.
1546-->
1547
1548* `object` {Object | string | Buffer | KeyObject}
1549  * `dsaEncoding` {string}
1550  * `padding` {integer}
1551  * `saltLength` {integer}
1552* `signature` {string | Buffer | TypedArray | DataView}
1553* `signatureEncoding` {string} The [encoding][] of the `signature` string.
1554* Returns: {boolean} `true` or `false` depending on the validity of the
1555  signature for the data and public key.
1556
1557Verifies the provided data using the given `object` and `signature`.
1558
1559If `object` is not a [`KeyObject`][], this function behaves as if
1560`object` had been passed to [`crypto.createPublicKey()`][]. If it is an
1561object, the following additional properties can be passed:
1562
1563* `dsaEncoding` {string} For DSA and ECDSA, this option specifies the
1564  format of the signature. It can be one of the following:
1565  * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`.
1566  * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363.
1567* `padding` {integer} Optional padding value for RSA, one of the following:
1568  * `crypto.constants.RSA_PKCS1_PADDING` (default)
1569  * `crypto.constants.RSA_PKCS1_PSS_PADDING`
1570
1571  `RSA_PKCS1_PSS_PADDING` will use MGF1 with the same hash function
1572  used to verify the message as specified in section 3.1 of [RFC 4055][], unless
1573  an MGF1 hash function has been specified as part of the key in compliance with
1574  section 3.3 of [RFC 4055][].
1575* `saltLength` {integer} Salt length for when padding is
1576  `RSA_PKCS1_PSS_PADDING`. The special value
1577  `crypto.constants.RSA_PSS_SALTLEN_DIGEST` sets the salt length to the digest
1578  size, `crypto.constants.RSA_PSS_SALTLEN_AUTO` (default) causes it to be
1579  determined automatically.
1580
1581The `signature` argument is the previously calculated signature for the data, in
1582the `signatureEncoding`.
1583If a `signatureEncoding` is specified, the `signature` is expected to be a
1584string; otherwise `signature` is expected to be a [`Buffer`][],
1585`TypedArray`, or `DataView`.
1586
1587The `verify` object can not be used again after `verify.verify()` has been
1588called. Multiple calls to `verify.verify()` will result in an error being
1589thrown.
1590
1591Because public keys can be derived from private keys, a private key may
1592be passed instead of a public key.
1593
1594## `crypto` module methods and properties
1595
1596### `crypto.constants`
1597<!-- YAML
1598added: v6.3.0
1599-->
1600
1601* Returns: {Object} An object containing commonly used constants for crypto and
1602  security related operations. The specific constants currently defined are
1603  described in [Crypto constants][].
1604
1605### `crypto.DEFAULT_ENCODING`
1606<!-- YAML
1607added: v0.9.3
1608deprecated: v10.0.0
1609-->
1610
1611> Stability: 0 - Deprecated
1612
1613The default encoding to use for functions that can take either strings
1614or [buffers][`Buffer`]. The default value is `'buffer'`, which makes methods
1615default to [`Buffer`][] objects.
1616
1617The `crypto.DEFAULT_ENCODING` mechanism is provided for backward compatibility
1618with legacy programs that expect `'latin1'` to be the default encoding.
1619
1620New applications should expect the default to be `'buffer'`.
1621
1622This property is deprecated.
1623
1624### `crypto.fips`
1625<!-- YAML
1626added: v6.0.0
1627deprecated: v10.0.0
1628-->
1629
1630> Stability: 0 - Deprecated
1631
1632Property for checking and controlling whether a FIPS compliant crypto provider
1633is currently in use. Setting to true requires a FIPS build of Node.js.
1634
1635This property is deprecated. Please use `crypto.setFips()` and
1636`crypto.getFips()` instead.
1637
1638### `crypto.createCipher(algorithm, password[, options])`
1639<!-- YAML
1640added: v0.1.94
1641deprecated: v10.0.0
1642changes:
1643  - version: v10.10.0
1644    pr-url: https://github.com/nodejs/node/pull/21447
1645    description: Ciphers in OCB mode are now supported.
1646  - version: v10.2.0
1647    pr-url: https://github.com/nodejs/node/pull/20235
1648    description: The `authTagLength` option can now be used to produce shorter
1649                 authentication tags in GCM mode and defaults to 16 bytes.
1650-->
1651
1652> Stability: 0 - Deprecated: Use [`crypto.createCipheriv()`][] instead.
1653
1654* `algorithm` {string}
1655* `password` {string | Buffer | TypedArray | DataView}
1656* `options` {Object} [`stream.transform` options][]
1657* Returns: {Cipher}
1658
1659Creates and returns a `Cipher` object that uses the given `algorithm` and
1660`password`.
1661
1662The `options` argument controls stream behavior and is optional except when a
1663cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the
1664`authTagLength` option is required and specifies the length of the
1665authentication tag in bytes, see [CCM mode][]. In GCM mode, the `authTagLength`
1666option is not required but can be used to set the length of the authentication
1667tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
1668
1669The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
1670recent OpenSSL releases, `openssl list -cipher-algorithms`
1671(`openssl list-cipher-algorithms` for older versions of OpenSSL) will
1672display the available cipher algorithms.
1673
1674The `password` is used to derive the cipher key and initialization vector (IV).
1675The value must be either a `'latin1'` encoded string, a [`Buffer`][], a
1676`TypedArray`, or a `DataView`.
1677
1678The implementation of `crypto.createCipher()` derives keys using the OpenSSL
1679function [`EVP_BytesToKey`][] with the digest algorithm set to MD5, one
1680iteration, and no salt. The lack of salt allows dictionary attacks as the same
1681password always creates the same key. The low iteration count and
1682non-cryptographically secure hash algorithm allow passwords to be tested very
1683rapidly.
1684
1685In line with OpenSSL's recommendation to use a more modern algorithm instead of
1686[`EVP_BytesToKey`][] it is recommended that developers derive a key and IV on
1687their own using [`crypto.scrypt()`][] and to use [`crypto.createCipheriv()`][]
1688to create the `Cipher` object. Users should not use ciphers with counter mode
1689(e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when
1690they are used in order to avoid the risk of IV reuse that causes
1691vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting
1692Adversaries][] for details.
1693
1694### `crypto.createCipheriv(algorithm, key, iv[, options])`
1695<!-- YAML
1696added: v0.1.94
1697changes:
1698  - version: v11.6.0
1699    pr-url: https://github.com/nodejs/node/pull/24234
1700    description: The `key` argument can now be a `KeyObject`.
1701  - version:
1702     - v11.2.0
1703     - v10.17.0
1704    pr-url: https://github.com/nodejs/node/pull/24081
1705    description: The cipher `chacha20-poly1305` is now supported.
1706  - version: v10.10.0
1707    pr-url: https://github.com/nodejs/node/pull/21447
1708    description: Ciphers in OCB mode are now supported.
1709  - version: v10.2.0
1710    pr-url: https://github.com/nodejs/node/pull/20235
1711    description: The `authTagLength` option can now be used to produce shorter
1712                 authentication tags in GCM mode and defaults to 16 bytes.
1713  - version: v9.9.0
1714    pr-url: https://github.com/nodejs/node/pull/18644
1715    description: The `iv` parameter may now be `null` for ciphers which do not
1716                 need an initialization vector.
1717-->
1718
1719* `algorithm` {string}
1720* `key` {string | Buffer | TypedArray | DataView | KeyObject}
1721* `iv` {string | Buffer | TypedArray | DataView | null}
1722* `options` {Object} [`stream.transform` options][]
1723* Returns: {Cipher}
1724
1725Creates and returns a `Cipher` object, with the given `algorithm`, `key` and
1726initialization vector (`iv`).
1727
1728The `options` argument controls stream behavior and is optional except when a
1729cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the
1730`authTagLength` option is required and specifies the length of the
1731authentication tag in bytes, see [CCM mode][]. In GCM mode, the `authTagLength`
1732option is not required but can be used to set the length of the authentication
1733tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
1734
1735The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
1736recent OpenSSL releases, `openssl list -cipher-algorithms`
1737(`openssl list-cipher-algorithms` for older versions of OpenSSL) will
1738display the available cipher algorithms.
1739
1740The `key` is the raw key used by the `algorithm` and `iv` is an
1741[initialization vector][]. Both arguments must be `'utf8'` encoded strings,
1742[Buffers][`Buffer`], `TypedArray`, or `DataView`s. The `key` may optionally be
1743a [`KeyObject`][] of type `secret`. If the cipher does not need
1744an initialization vector, `iv` may be `null`.
1745
1746Initialization vectors should be unpredictable and unique; ideally, they will be
1747cryptographically random. They do not have to be secret: IVs are typically just
1748added to ciphertext messages unencrypted. It may sound contradictory that
1749something has to be unpredictable and unique, but does not have to be secret;
1750remember that an attacker must not be able to predict ahead of time what a
1751given IV will be.
1752
1753### `crypto.createDecipher(algorithm, password[, options])`
1754<!-- YAML
1755added: v0.1.94
1756deprecated: v10.0.0
1757changes:
1758  - version: v10.10.0
1759    pr-url: https://github.com/nodejs/node/pull/21447
1760    description: Ciphers in OCB mode are now supported.
1761-->
1762
1763> Stability: 0 - Deprecated: Use [`crypto.createDecipheriv()`][] instead.
1764
1765* `algorithm` {string}
1766* `password` {string | Buffer | TypedArray | DataView}
1767* `options` {Object} [`stream.transform` options][]
1768* Returns: {Decipher}
1769
1770Creates and returns a `Decipher` object that uses the given `algorithm` and
1771`password` (key).
1772
1773The `options` argument controls stream behavior and is optional except when a
1774cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the
1775`authTagLength` option is required and specifies the length of the
1776authentication tag in bytes, see [CCM mode][].
1777
1778The implementation of `crypto.createDecipher()` derives keys using the OpenSSL
1779function [`EVP_BytesToKey`][] with the digest algorithm set to MD5, one
1780iteration, and no salt. The lack of salt allows dictionary attacks as the same
1781password always creates the same key. The low iteration count and
1782non-cryptographically secure hash algorithm allow passwords to be tested very
1783rapidly.
1784
1785In line with OpenSSL's recommendation to use a more modern algorithm instead of
1786[`EVP_BytesToKey`][] it is recommended that developers derive a key and IV on
1787their own using [`crypto.scrypt()`][] and to use [`crypto.createDecipheriv()`][]
1788to create the `Decipher` object.
1789
1790### `crypto.createDecipheriv(algorithm, key, iv[, options])`
1791<!-- YAML
1792added: v0.1.94
1793changes:
1794  - version: v11.6.0
1795    pr-url: https://github.com/nodejs/node/pull/24234
1796    description: The `key` argument can now be a `KeyObject`.
1797  - version:
1798     - v11.2.0
1799     - v10.17.0
1800    pr-url: https://github.com/nodejs/node/pull/24081
1801    description: The cipher `chacha20-poly1305` is now supported.
1802  - version: v10.10.0
1803    pr-url: https://github.com/nodejs/node/pull/21447
1804    description: Ciphers in OCB mode are now supported.
1805  - version: v10.2.0
1806    pr-url: https://github.com/nodejs/node/pull/20039
1807    description: The `authTagLength` option can now be used to restrict accepted
1808                 GCM authentication tag lengths.
1809  - version: v9.9.0
1810    pr-url: https://github.com/nodejs/node/pull/18644
1811    description: The `iv` parameter may now be `null` for ciphers which do not
1812                 need an initialization vector.
1813-->
1814
1815* `algorithm` {string}
1816* `key` {string | Buffer | TypedArray | DataView | KeyObject}
1817* `iv` {string | Buffer | TypedArray | DataView | null}
1818* `options` {Object} [`stream.transform` options][]
1819* Returns: {Decipher}
1820
1821Creates and returns a `Decipher` object that uses the given `algorithm`, `key`
1822and initialization vector (`iv`).
1823
1824The `options` argument controls stream behavior and is optional except when a
1825cipher in CCM or OCB mode is used (e.g. `'aes-128-ccm'`). In that case, the
1826`authTagLength` option is required and specifies the length of the
1827authentication tag in bytes, see [CCM mode][]. In GCM mode, the `authTagLength`
1828option is not required but can be used to restrict accepted authentication tags
1829to those with the specified length.
1830
1831The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
1832recent OpenSSL releases, `openssl list -cipher-algorithms`
1833(`openssl list-cipher-algorithms` for older versions of OpenSSL) will
1834display the available cipher algorithms.
1835
1836The `key` is the raw key used by the `algorithm` and `iv` is an
1837[initialization vector][]. Both arguments must be `'utf8'` encoded strings,
1838[Buffers][`Buffer`], `TypedArray`, or `DataView`s. The `key` may optionally be
1839a [`KeyObject`][] of type `secret`. If the cipher does not need
1840an initialization vector, `iv` may be `null`.
1841
1842Initialization vectors should be unpredictable and unique; ideally, they will be
1843cryptographically random. They do not have to be secret: IVs are typically just
1844added to ciphertext messages unencrypted. It may sound contradictory that
1845something has to be unpredictable and unique, but does not have to be secret;
1846remember that an attacker must not be able to predict ahead of time what a given
1847IV will be.
1848
1849### `crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])`
1850<!-- YAML
1851added: v0.11.12
1852changes:
1853  - version: v8.0.0
1854    pr-url: https://github.com/nodejs/node/pull/12223
1855    description: The `prime` argument can be any `TypedArray` or `DataView` now.
1856  - version: v8.0.0
1857    pr-url: https://github.com/nodejs/node/pull/11983
1858    description: The `prime` argument can be a `Uint8Array` now.
1859  - version: v6.0.0
1860    pr-url: https://github.com/nodejs/node/pull/5522
1861    description: The default for the encoding parameters changed
1862                 from `binary` to `utf8`.
1863-->
1864
1865* `prime` {string | Buffer | TypedArray | DataView}
1866* `primeEncoding` {string} The [encoding][] of the `prime` string.
1867* `generator` {number | string | Buffer | TypedArray | DataView} **Default:**
1868  `2`
1869* `generatorEncoding` {string} The [encoding][] of the `generator` string.
1870* Returns: {DiffieHellman}
1871
1872Creates a `DiffieHellman` key exchange object using the supplied `prime` and an
1873optional specific `generator`.
1874
1875The `generator` argument can be a number, string, or [`Buffer`][]. If
1876`generator` is not specified, the value `2` is used.
1877
1878If `primeEncoding` is specified, `prime` is expected to be a string; otherwise
1879a [`Buffer`][], `TypedArray`, or `DataView` is expected.
1880
1881If `generatorEncoding` is specified, `generator` is expected to be a string;
1882otherwise a number, [`Buffer`][], `TypedArray`, or `DataView` is expected.
1883
1884### `crypto.createDiffieHellman(primeLength[, generator])`
1885<!-- YAML
1886added: v0.5.0
1887-->
1888
1889* `primeLength` {number}
1890* `generator` {number} **Default:** `2`
1891* Returns: {DiffieHellman}
1892
1893Creates a `DiffieHellman` key exchange object and generates a prime of
1894`primeLength` bits using an optional specific numeric `generator`.
1895If `generator` is not specified, the value `2` is used.
1896
1897### `crypto.createDiffieHellmanGroup(name)`
1898<!-- YAML
1899added: v0.9.3
1900-->
1901
1902* `name` {string}
1903* Returns: {DiffieHellmanGroup}
1904
1905An alias for [`crypto.getDiffieHellman()`][]
1906
1907### `crypto.createECDH(curveName)`
1908<!-- YAML
1909added: v0.11.14
1910-->
1911
1912* `curveName` {string}
1913* Returns: {ECDH}
1914
1915Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a
1916predefined curve specified by the `curveName` string. Use
1917[`crypto.getCurves()`][] to obtain a list of available curve names. On recent
1918OpenSSL releases, `openssl ecparam -list_curves` will also display the name
1919and description of each available elliptic curve.
1920
1921### `crypto.createHash(algorithm[, options])`
1922<!-- YAML
1923added: v0.1.92
1924changes:
1925  - version: v12.8.0
1926    pr-url: https://github.com/nodejs/node/pull/28805
1927    description: The `outputLength` option was added for XOF hash functions.
1928-->
1929
1930* `algorithm` {string}
1931* `options` {Object} [`stream.transform` options][]
1932* Returns: {Hash}
1933
1934Creates and returns a `Hash` object that can be used to generate hash digests
1935using the given `algorithm`. Optional `options` argument controls stream
1936behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option
1937can be used to specify the desired output length in bytes.
1938
1939The `algorithm` is dependent on the available algorithms supported by the
1940version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
1941On recent releases of OpenSSL, `openssl list -digest-algorithms`
1942(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will
1943display the available digest algorithms.
1944
1945Example: generating the sha256 sum of a file
1946
1947```js
1948const filename = process.argv[2];
1949const crypto = require('crypto');
1950const fs = require('fs');
1951
1952const hash = crypto.createHash('sha256');
1953
1954const input = fs.createReadStream(filename);
1955input.on('readable', () => {
1956  // Only one element is going to be produced by the
1957  // hash stream.
1958  const data = input.read();
1959  if (data)
1960    hash.update(data);
1961  else {
1962    console.log(`${hash.digest('hex')} ${filename}`);
1963  }
1964});
1965```
1966
1967### `crypto.createHmac(algorithm, key[, options])`
1968<!-- YAML
1969added: v0.1.94
1970changes:
1971  - version: v11.6.0
1972    pr-url: https://github.com/nodejs/node/pull/24234
1973    description: The `key` argument can now be a `KeyObject`.
1974-->
1975
1976* `algorithm` {string}
1977* `key` {string | Buffer | TypedArray | DataView | KeyObject}
1978* `options` {Object} [`stream.transform` options][]
1979* Returns: {Hmac}
1980
1981Creates and returns an `Hmac` object that uses the given `algorithm` and `key`.
1982Optional `options` argument controls stream behavior.
1983
1984The `algorithm` is dependent on the available algorithms supported by the
1985version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
1986On recent releases of OpenSSL, `openssl list -digest-algorithms`
1987(`openssl list-message-digest-algorithms` for older versions of OpenSSL) will
1988display the available digest algorithms.
1989
1990The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is
1991a [`KeyObject`][], its type must be `secret`.
1992
1993Example: generating the sha256 HMAC of a file
1994
1995```js
1996const filename = process.argv[2];
1997const crypto = require('crypto');
1998const fs = require('fs');
1999
2000const hmac = crypto.createHmac('sha256', 'a secret');
2001
2002const input = fs.createReadStream(filename);
2003input.on('readable', () => {
2004  // Only one element is going to be produced by the
2005  // hash stream.
2006  const data = input.read();
2007  if (data)
2008    hmac.update(data);
2009  else {
2010    console.log(`${hmac.digest('hex')} ${filename}`);
2011  }
2012});
2013```
2014
2015### `crypto.createPrivateKey(key)`
2016<!-- YAML
2017added: v11.6.0
2018-->
2019
2020* `key` {Object | string | Buffer}
2021  * `key`: {string | Buffer} The key material, either in PEM or DER format.
2022  * `format`: {string} Must be `'pem'` or `'der'`. **Default:** `'pem'`.
2023  * `type`: {string} Must be `'pkcs1'`, `'pkcs8'` or `'sec1'`. This option is
2024     required only if the `format` is `'der'` and ignored if it is `'pem'`.
2025  * `passphrase`: {string | Buffer} The passphrase to use for decryption.
2026* Returns: {KeyObject}
2027
2028Creates and returns a new key object containing a private key. If `key` is a
2029string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`
2030must be an object with the properties described above.
2031
2032If the private key is encrypted, a `passphrase` must be specified. The length
2033of the passphrase is limited to 1024 bytes.
2034
2035### `crypto.createPublicKey(key)`
2036<!-- YAML
2037added: v11.6.0
2038changes:
2039  - version: v11.13.0
2040    pr-url: https://github.com/nodejs/node/pull/26278
2041    description: The `key` argument can now be a `KeyObject` with type
2042                 `private`.
2043  - version: v11.7.0
2044    pr-url: https://github.com/nodejs/node/pull/25217
2045    description: The `key` argument can now be a private key.
2046-->
2047
2048* `key` {Object | string | Buffer | KeyObject}
2049  * `key`: {string | Buffer}
2050  * `format`: {string} Must be `'pem'` or `'der'`. **Default:** `'pem'`.
2051  * `type`: {string} Must be `'pkcs1'` or `'spki'`. This option is required
2052    only if the `format` is `'der'`.
2053* Returns: {KeyObject}
2054
2055Creates and returns a new key object containing a public key. If `key` is a
2056string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`
2057with type `'private'`, the public key is derived from the given private key;
2058otherwise, `key` must be an object with the properties described above.
2059
2060If the format is `'pem'`, the `'key'` may also be an X.509 certificate.
2061
2062Because public keys can be derived from private keys, a private key may be
2063passed instead of a public key. In that case, this function behaves as if
2064[`crypto.createPrivateKey()`][] had been called, except that the type of the
2065returned `KeyObject` will be `'public'` and that the private key cannot be
2066extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type
2067`'private'` is given, a new `KeyObject` with type `'public'` will be returned
2068and it will be impossible to extract the private key from the returned object.
2069
2070### `crypto.createSecretKey(key)`
2071<!-- YAML
2072added: v11.6.0
2073-->
2074
2075* `key` {Buffer | TypedArray | DataView}
2076* Returns: {KeyObject}
2077
2078Creates and returns a new key object containing a secret key for symmetric
2079encryption or `Hmac`.
2080
2081### `crypto.createSign(algorithm[, options])`
2082<!-- YAML
2083added: v0.1.92
2084-->
2085
2086* `algorithm` {string}
2087* `options` {Object} [`stream.Writable` options][]
2088* Returns: {Sign}
2089
2090Creates and returns a `Sign` object that uses the given `algorithm`. Use
2091[`crypto.getHashes()`][] to obtain the names of the available digest algorithms.
2092Optional `options` argument controls the `stream.Writable` behavior.
2093
2094In some cases, a `Sign` instance can be created using the name of a signature
2095algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
2096the corresponding digest algorithm. This does not work for all signature
2097algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
2098algorithm names.
2099
2100### `crypto.createVerify(algorithm[, options])`
2101<!-- YAML
2102added: v0.1.92
2103-->
2104
2105* `algorithm` {string}
2106* `options` {Object} [`stream.Writable` options][]
2107* Returns: {Verify}
2108
2109Creates and returns a `Verify` object that uses the given algorithm.
2110Use [`crypto.getHashes()`][] to obtain an array of names of the available
2111signing algorithms. Optional `options` argument controls the
2112`stream.Writable` behavior.
2113
2114In some cases, a `Verify` instance can be created using the name of a signature
2115algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
2116the corresponding digest algorithm. This does not work for all signature
2117algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
2118algorithm names.
2119
2120### `crypto.diffieHellman(options)`
2121<!-- YAML
2122added: v13.9.0
2123-->
2124
2125* `options`: {Object}
2126  * `privateKey`: {KeyObject}
2127  * `publicKey`: {KeyObject}
2128* Returns: {Buffer}
2129
2130Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`.
2131Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`
2132(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES).
2133
2134### `crypto.generateKeyPair(type, options, callback)`
2135<!-- YAML
2136added: v10.12.0
2137changes:
2138  - version: v13.9.0
2139    pr-url: https://github.com/nodejs/node/pull/31178
2140    description: Add support for Diffie-Hellman.
2141  - version: v12.0.0
2142    pr-url: https://github.com/nodejs/node/pull/26774
2143    description: Add ability to generate X25519 and X448 key pairs.
2144  - version: v12.0.0
2145    pr-url: https://github.com/nodejs/node/pull/26554
2146    description: Add ability to generate Ed25519 and Ed448 key pairs.
2147  - version: v11.6.0
2148    pr-url: https://github.com/nodejs/node/pull/24234
2149    description: The `generateKeyPair` and `generateKeyPairSync` functions now
2150                 produce key objects if no encoding was specified.
2151-->
2152
2153* `type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`,
2154  `'x25519'`, `'x448'`, or `'dh'`.
2155* `options`: {Object}
2156  * `modulusLength`: {number} Key size in bits (RSA, DSA).
2157  * `publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.
2158  * `divisorLength`: {number} Size of `q` in bits (DSA).
2159  * `namedCurve`: {string} Name of the curve to use (EC).
2160  * `prime`: {Buffer} The prime parameter (DH).
2161  * `primeLength`: {number} Prime length in bits (DH).
2162  * `generator`: {number} Custom generator (DH). **Default:** `2`.
2163  * `groupName`: {string} Diffie-Hellman group name (DH). See
2164    [`crypto.getDiffieHellman()`][].
2165  * `publicKeyEncoding`: {Object} See [`keyObject.export()`][].
2166  * `privateKeyEncoding`: {Object} See [`keyObject.export()`][].
2167* `callback`: {Function}
2168  * `err`: {Error}
2169  * `publicKey`: {string | Buffer | KeyObject}
2170  * `privateKey`: {string | Buffer | KeyObject}
2171
2172Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519,
2173Ed448, X25519, X448, and DH are currently supported.
2174
2175If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
2176behaves as if [`keyObject.export()`][] had been called on its result. Otherwise,
2177the respective part of the key is returned as a [`KeyObject`][].
2178
2179It is recommended to encode public keys as `'spki'` and private keys as
2180`'pkcs8'` with encryption for long-term storage:
2181
2182```js
2183const { generateKeyPair } = require('crypto');
2184generateKeyPair('rsa', {
2185  modulusLength: 4096,
2186  publicKeyEncoding: {
2187    type: 'spki',
2188    format: 'pem'
2189  },
2190  privateKeyEncoding: {
2191    type: 'pkcs8',
2192    format: 'pem',
2193    cipher: 'aes-256-cbc',
2194    passphrase: 'top secret'
2195  }
2196}, (err, publicKey, privateKey) => {
2197  // Handle errors and use the generated key pair.
2198});
2199```
2200
2201On completion, `callback` will be called with `err` set to `undefined` and
2202`publicKey` / `privateKey` representing the generated key pair.
2203
2204If this method is invoked as its [`util.promisify()`][]ed version, it returns
2205a `Promise` for an `Object` with `publicKey` and `privateKey` properties.
2206
2207### `crypto.generateKeyPairSync(type, options)`
2208<!-- YAML
2209added: v10.12.0
2210changes:
2211  - version: v13.9.0
2212    pr-url: https://github.com/nodejs/node/pull/31178
2213    description: Add support for Diffie-Hellman.
2214  - version: v12.0.0
2215    pr-url: https://github.com/nodejs/node/pull/26554
2216    description: Add ability to generate Ed25519 and Ed448 key pairs.
2217  - version: v11.6.0
2218    pr-url: https://github.com/nodejs/node/pull/24234
2219    description: The `generateKeyPair` and `generateKeyPairSync` functions now
2220                 produce key objects if no encoding was specified.
2221-->
2222
2223* `type`: {string} Must be `'rsa'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`,
2224  `'x25519'`, `'x448'`, or `'dh'`.
2225* `options`: {Object}
2226  * `modulusLength`: {number} Key size in bits (RSA, DSA).
2227  * `publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.
2228  * `divisorLength`: {number} Size of `q` in bits (DSA).
2229  * `namedCurve`: {string} Name of the curve to use (EC).
2230  * `prime`: {Buffer} The prime parameter (DH).
2231  * `primeLength`: {number} Prime length in bits (DH).
2232  * `generator`: {number} Custom generator (DH). **Default:** `2`.
2233  * `groupName`: {string} Diffie-Hellman group name (DH). See
2234    [`crypto.getDiffieHellman()`][].
2235  * `publicKeyEncoding`: {Object} See [`keyObject.export()`][].
2236  * `privateKeyEncoding`: {Object} See [`keyObject.export()`][].
2237* Returns: {Object}
2238  * `publicKey`: {string | Buffer | KeyObject}
2239  * `privateKey`: {string | Buffer | KeyObject}
2240
2241Generates a new asymmetric key pair of the given `type`. RSA, DSA, EC, Ed25519,
2242Ed448, X25519, X448, and DH are currently supported.
2243
2244If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
2245behaves as if [`keyObject.export()`][] had been called on its result. Otherwise,
2246the respective part of the key is returned as a [`KeyObject`][].
2247
2248When encoding public keys, it is recommended to use `'spki'`. When encoding
2249private keys, it is recommended to use `'pkcs8'` with a strong passphrase,
2250and to keep the passphrase confidential.
2251
2252```js
2253const { generateKeyPairSync } = require('crypto');
2254const { publicKey, privateKey } = generateKeyPairSync('rsa', {
2255  modulusLength: 4096,
2256  publicKeyEncoding: {
2257    type: 'spki',
2258    format: 'pem'
2259  },
2260  privateKeyEncoding: {
2261    type: 'pkcs8',
2262    format: 'pem',
2263    cipher: 'aes-256-cbc',
2264    passphrase: 'top secret'
2265  }
2266});
2267```
2268
2269The return value `{ publicKey, privateKey }` represents the generated key pair.
2270When PEM encoding was selected, the respective key will be a string, otherwise
2271it will be a buffer containing the data encoded as DER.
2272
2273### `crypto.getCiphers()`
2274<!-- YAML
2275added: v0.9.3
2276-->
2277
2278* Returns: {string[]} An array with the names of the supported cipher
2279  algorithms.
2280
2281```js
2282const ciphers = crypto.getCiphers();
2283console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]
2284```
2285
2286### `crypto.getCurves()`
2287<!-- YAML
2288added: v2.3.0
2289-->
2290
2291* Returns: {string[]} An array with the names of the supported elliptic curves.
2292
2293```js
2294const curves = crypto.getCurves();
2295console.log(curves); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
2296```
2297
2298### `crypto.getDiffieHellman(groupName)`
2299<!-- YAML
2300added: v0.7.5
2301-->
2302
2303* `groupName` {string}
2304* Returns: {DiffieHellmanGroup}
2305
2306Creates a predefined `DiffieHellmanGroup` key exchange object. The
2307supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in
2308[RFC 2412][], but see [Caveats][]) and `'modp14'`, `'modp15'`,
2309`'modp16'`, `'modp17'`, `'modp18'` (defined in [RFC 3526][]). The
2310returned object mimics the interface of objects created by
2311[`crypto.createDiffieHellman()`][], but will not allow changing
2312the keys (with [`diffieHellman.setPublicKey()`][], for example). The
2313advantage of using this method is that the parties do not have to
2314generate nor exchange a group modulus beforehand, saving both processor
2315and communication time.
2316
2317Example (obtaining a shared secret):
2318
2319```js
2320const crypto = require('crypto');
2321const alice = crypto.getDiffieHellman('modp14');
2322const bob = crypto.getDiffieHellman('modp14');
2323
2324alice.generateKeys();
2325bob.generateKeys();
2326
2327const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
2328const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
2329
2330/* aliceSecret and bobSecret should be the same */
2331console.log(aliceSecret === bobSecret);
2332```
2333
2334### `crypto.getFips()`
2335<!-- YAML
2336added: v10.0.0
2337-->
2338
2339* Returns: {number} `1` if and only if a FIPS compliant crypto provider is
2340  currently in use, `0` otherwise. A future semver-major release may change
2341  the return type of this API to a {boolean}.
2342
2343### `crypto.getHashes()`
2344<!-- YAML
2345added: v0.9.3
2346-->
2347
2348* Returns: {string[]} An array of the names of the supported hash algorithms,
2349  such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms.
2350
2351```js
2352const hashes = crypto.getHashes();
2353console.log(hashes); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
2354```
2355
2356### `crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)`
2357<!-- YAML
2358added: v0.5.5
2359changes:
2360  - version: v14.0.0
2361    pr-url: https://github.com/nodejs/node/pull/30578
2362    description: The `iterations` parameter is now restricted to positive
2363                 values. Earlier releases treated other values as one.
2364  - version: v8.0.0
2365    pr-url: https://github.com/nodejs/node/pull/11305
2366    description: The `digest` parameter is always required now.
2367  - version: v6.0.0
2368    pr-url: https://github.com/nodejs/node/pull/4047
2369    description: Calling this function without passing the `digest` parameter
2370                 is deprecated now and will emit a warning.
2371  - version: v6.0.0
2372    pr-url: https://github.com/nodejs/node/pull/5522
2373    description: The default encoding for `password` if it is a string changed
2374                 from `binary` to `utf8`.
2375-->
2376
2377* `password` {string|Buffer|TypedArray|DataView}
2378* `salt` {string|Buffer|TypedArray|DataView}
2379* `iterations` {number}
2380* `keylen` {number}
2381* `digest` {string}
2382* `callback` {Function}
2383  * `err` {Error}
2384  * `derivedKey` {Buffer}
2385
2386Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)
2387implementation. A selected HMAC digest algorithm specified by `digest` is
2388applied to derive a key of the requested byte length (`keylen`) from the
2389`password`, `salt` and `iterations`.
2390
2391The supplied `callback` function is called with two arguments: `err` and
2392`derivedKey`. If an error occurs while deriving the key, `err` will be set;
2393otherwise `err` will be `null`. By default, the successfully generated
2394`derivedKey` will be passed to the callback as a [`Buffer`][]. An error will be
2395thrown if any of the input arguments specify invalid values or types.
2396
2397If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated,
2398please specify a `digest` explicitly.
2399
2400The `iterations` argument must be a number set as high as possible. The
2401higher the number of iterations, the more secure the derived key will be,
2402but will take a longer amount of time to complete.
2403
2404The `salt` should be as unique as possible. It is recommended that a salt is
2405random and at least 16 bytes long. See [NIST SP 800-132][] for details.
2406
2407```js
2408const crypto = require('crypto');
2409crypto.pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
2410  if (err) throw err;
2411  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
2412});
2413```
2414
2415The `crypto.DEFAULT_ENCODING` property can be used to change the way the
2416`derivedKey` is passed to the callback. This property, however, has been
2417deprecated and use should be avoided.
2418
2419```js
2420const crypto = require('crypto');
2421crypto.DEFAULT_ENCODING = 'hex';
2422crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {
2423  if (err) throw err;
2424  console.log(derivedKey);  // '3745e48...aa39b34'
2425});
2426```
2427
2428An array of supported digest functions can be retrieved using
2429[`crypto.getHashes()`][].
2430
2431This API uses libuv's threadpool, which can have surprising and
2432negative performance implications for some applications; see the
2433[`UV_THREADPOOL_SIZE`][] documentation for more information.
2434
2435### `crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)`
2436<!-- YAML
2437added: v0.9.3
2438changes:
2439  - version: v14.0.0
2440    pr-url: https://github.com/nodejs/node/pull/30578
2441    description: The `iterations` parameter is now restricted to positive
2442                 values. Earlier releases treated other values as one.
2443  - version: v6.0.0
2444    pr-url: https://github.com/nodejs/node/pull/4047
2445    description: Calling this function without passing the `digest` parameter
2446                 is deprecated now and will emit a warning.
2447  - version: v6.0.0
2448    pr-url: https://github.com/nodejs/node/pull/5522
2449    description: The default encoding for `password` if it is a string changed
2450                 from `binary` to `utf8`.
2451-->
2452
2453* `password` {string|Buffer|TypedArray|DataView}
2454* `salt` {string|Buffer|TypedArray|DataView}
2455* `iterations` {number}
2456* `keylen` {number}
2457* `digest` {string}
2458* Returns: {Buffer}
2459
2460Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)
2461implementation. A selected HMAC digest algorithm specified by `digest` is
2462applied to derive a key of the requested byte length (`keylen`) from the
2463`password`, `salt` and `iterations`.
2464
2465If an error occurs an `Error` will be thrown, otherwise the derived key will be
2466returned as a [`Buffer`][].
2467
2468If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated,
2469please specify a `digest` explicitly.
2470
2471The `iterations` argument must be a number set as high as possible. The
2472higher the number of iterations, the more secure the derived key will be,
2473but will take a longer amount of time to complete.
2474
2475The `salt` should be as unique as possible. It is recommended that a salt is
2476random and at least 16 bytes long. See [NIST SP 800-132][] for details.
2477
2478```js
2479const crypto = require('crypto');
2480const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
2481console.log(key.toString('hex'));  // '3745e48...08d59ae'
2482```
2483
2484The `crypto.DEFAULT_ENCODING` property may be used to change the way the
2485`derivedKey` is returned. This property, however, is deprecated and use
2486should be avoided.
2487
2488```js
2489const crypto = require('crypto');
2490crypto.DEFAULT_ENCODING = 'hex';
2491const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
2492console.log(key);  // '3745e48...aa39b34'
2493```
2494
2495An array of supported digest functions can be retrieved using
2496[`crypto.getHashes()`][].
2497
2498### `crypto.privateDecrypt(privateKey, buffer)`
2499<!-- YAML
2500added: v0.11.14
2501changes:
2502  - version: v12.11.0
2503    pr-url: https://github.com/nodejs/node/pull/29489
2504    description: The `oaepLabel` option was added.
2505  - version: v12.9.0
2506    pr-url: https://github.com/nodejs/node/pull/28335
2507    description: The `oaepHash` option was added.
2508  - version: v11.6.0
2509    pr-url: https://github.com/nodejs/node/pull/24234
2510    description: This function now supports key objects.
2511-->
2512
2513* `privateKey` {Object | string | Buffer | KeyObject}
2514  * `oaepHash` {string} The hash function to use for OAEP padding and MGF1.
2515    **Default:** `'sha1'`
2516  * `oaepLabel` {Buffer | TypedArray | DataView} The label to use for OAEP
2517     padding. If not specified, no label is used.
2518  * `padding` {crypto.constants} An optional padding value defined in
2519    `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`,
2520    `crypto.constants.RSA_PKCS1_PADDING`, or
2521    `crypto.constants.RSA_PKCS1_OAEP_PADDING`.
2522* `buffer` {Buffer | TypedArray | DataView}
2523* Returns: {Buffer} A new `Buffer` with the decrypted content.
2524
2525Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using
2526the corresponding public key, for example using [`crypto.publicEncrypt()`][].
2527
2528If `privateKey` is not a [`KeyObject`][], this function behaves as if
2529`privateKey` had been passed to [`crypto.createPrivateKey()`][]. If it is an
2530object, the `padding` property can be passed. Otherwise, this function uses
2531`RSA_PKCS1_OAEP_PADDING`.
2532
2533### `crypto.privateEncrypt(privateKey, buffer)`
2534<!-- YAML
2535added: v1.1.0
2536changes:
2537  - version: v11.6.0
2538    pr-url: https://github.com/nodejs/node/pull/24234
2539    description: This function now supports key objects.
2540-->
2541
2542* `privateKey` {Object | string | Buffer | KeyObject}
2543  * `key` {string | Buffer | KeyObject} A PEM encoded private key.
2544  * `passphrase` {string | Buffer} An optional passphrase for the private key.
2545  * `padding` {crypto.constants} An optional padding value defined in
2546    `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or
2547    `crypto.constants.RSA_PKCS1_PADDING`.
2548* `buffer` {Buffer | TypedArray | DataView}
2549* Returns: {Buffer} A new `Buffer` with the encrypted content.
2550
2551Encrypts `buffer` with `privateKey`. The returned data can be decrypted using
2552the corresponding public key, for example using [`crypto.publicDecrypt()`][].
2553
2554If `privateKey` is not a [`KeyObject`][], this function behaves as if
2555`privateKey` had been passed to [`crypto.createPrivateKey()`][]. If it is an
2556object, the `padding` property can be passed. Otherwise, this function uses
2557`RSA_PKCS1_PADDING`.
2558
2559### `crypto.publicDecrypt(key, buffer)`
2560<!-- YAML
2561added: v1.1.0
2562changes:
2563  - version: v11.6.0
2564    pr-url: https://github.com/nodejs/node/pull/24234
2565    description: This function now supports key objects.
2566-->
2567
2568* `key` {Object | string | Buffer | KeyObject}
2569  * `passphrase` {string | Buffer} An optional passphrase for the private key.
2570  * `padding` {crypto.constants} An optional padding value defined in
2571    `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or
2572    `crypto.constants.RSA_PKCS1_PADDING`.
2573* `buffer` {Buffer | TypedArray | DataView}
2574* Returns: {Buffer} A new `Buffer` with the decrypted content.
2575
2576Decrypts `buffer` with `key`.`buffer` was previously encrypted using
2577the corresponding private key, for example using [`crypto.privateEncrypt()`][].
2578
2579If `key` is not a [`KeyObject`][], this function behaves as if
2580`key` had been passed to [`crypto.createPublicKey()`][]. If it is an
2581object, the `padding` property can be passed. Otherwise, this function uses
2582`RSA_PKCS1_PADDING`.
2583
2584Because RSA public keys can be derived from private keys, a private key may
2585be passed instead of a public key.
2586
2587### `crypto.publicEncrypt(key, buffer)`
2588<!-- YAML
2589added: v0.11.14
2590changes:
2591  - version: v12.11.0
2592    pr-url: https://github.com/nodejs/node/pull/29489
2593    description: The `oaepLabel` option was added.
2594  - version: v12.9.0
2595    pr-url: https://github.com/nodejs/node/pull/28335
2596    description: The `oaepHash` option was added.
2597  - version: v11.6.0
2598    pr-url: https://github.com/nodejs/node/pull/24234
2599    description: This function now supports key objects.
2600-->
2601
2602* `key` {Object | string | Buffer | KeyObject}
2603  * `key` {string | Buffer | KeyObject} A PEM encoded public or private key.
2604  * `oaepHash` {string} The hash function to use for OAEP padding and MGF1.
2605    **Default:** `'sha1'`
2606  * `oaepLabel` {Buffer | TypedArray | DataView} The label to use for OAEP
2607     padding. If not specified, no label is used.
2608  * `passphrase` {string | Buffer} An optional passphrase for the private key.
2609  * `padding` {crypto.constants} An optional padding value defined in
2610    `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`,
2611    `crypto.constants.RSA_PKCS1_PADDING`, or
2612    `crypto.constants.RSA_PKCS1_OAEP_PADDING`.
2613* `buffer` {Buffer | TypedArray | DataView}
2614* Returns: {Buffer} A new `Buffer` with the encrypted content.
2615
2616Encrypts the content of `buffer` with `key` and returns a new
2617[`Buffer`][] with encrypted content. The returned data can be decrypted using
2618the corresponding private key, for example using [`crypto.privateDecrypt()`][].
2619
2620If `key` is not a [`KeyObject`][], this function behaves as if
2621`key` had been passed to [`crypto.createPublicKey()`][]. If it is an
2622object, the `padding` property can be passed. Otherwise, this function uses
2623`RSA_PKCS1_OAEP_PADDING`.
2624
2625Because RSA public keys can be derived from private keys, a private key may
2626be passed instead of a public key.
2627
2628### `crypto.randomBytes(size[, callback])`
2629<!-- YAML
2630added: v0.5.8
2631changes:
2632  - version: v9.0.0
2633    pr-url: https://github.com/nodejs/node/pull/16454
2634    description: Passing `null` as the `callback` argument now throws
2635                 `ERR_INVALID_CALLBACK`.
2636-->
2637
2638* `size` {number}
2639* `callback` {Function}
2640  * `err` {Error}
2641  * `buf` {Buffer}
2642* Returns: {Buffer} if the `callback` function is not provided.
2643
2644Generates cryptographically strong pseudo-random data. The `size` argument
2645is a number indicating the number of bytes to generate.
2646
2647If a `callback` function is provided, the bytes are generated asynchronously
2648and the `callback` function is invoked with two arguments: `err` and `buf`.
2649If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The
2650`buf` argument is a [`Buffer`][] containing the generated bytes.
2651
2652```js
2653// Asynchronous
2654const crypto = require('crypto');
2655crypto.randomBytes(256, (err, buf) => {
2656  if (err) throw err;
2657  console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
2658});
2659```
2660
2661If the `callback` function is not provided, the random bytes are generated
2662synchronously and returned as a [`Buffer`][]. An error will be thrown if
2663there is a problem generating the bytes.
2664
2665```js
2666// Synchronous
2667const buf = crypto.randomBytes(256);
2668console.log(
2669  `${buf.length} bytes of random data: ${buf.toString('hex')}`);
2670```
2671
2672The `crypto.randomBytes()` method will not complete until there is
2673sufficient entropy available.
2674This should normally never take longer than a few milliseconds. The only time
2675when generating the random bytes may conceivably block for a longer period of
2676time is right after boot, when the whole system is still low on entropy.
2677
2678This API uses libuv's threadpool, which can have surprising and
2679negative performance implications for some applications; see the
2680[`UV_THREADPOOL_SIZE`][] documentation for more information.
2681
2682The asynchronous version of `crypto.randomBytes()` is carried out in a single
2683threadpool request. To minimize threadpool task length variation, partition
2684large `randomBytes` requests when doing so as part of fulfilling a client
2685request.
2686
2687### `crypto.randomFillSync(buffer[, offset][, size])`
2688<!-- YAML
2689added:
2690  - v7.10.0
2691  - v6.13.0
2692changes:
2693  - version: v9.0.0
2694    pr-url: https://github.com/nodejs/node/pull/15231
2695    description: The `buffer` argument may be any `TypedArray` or `DataView`.
2696-->
2697
2698* `buffer` {Buffer|TypedArray|DataView} Must be supplied.
2699* `offset` {number} **Default:** `0`
2700* `size` {number} **Default:** `buffer.length - offset`
2701* Returns: {Buffer|TypedArray|DataView} The object passed as `buffer` argument.
2702
2703Synchronous version of [`crypto.randomFill()`][].
2704
2705```js
2706const buf = Buffer.alloc(10);
2707console.log(crypto.randomFillSync(buf).toString('hex'));
2708
2709crypto.randomFillSync(buf, 5);
2710console.log(buf.toString('hex'));
2711
2712// The above is equivalent to the following:
2713crypto.randomFillSync(buf, 5, 5);
2714console.log(buf.toString('hex'));
2715```
2716
2717Any `TypedArray` or `DataView` instance may be passed as `buffer`.
2718
2719```js
2720const a = new Uint32Array(10);
2721console.log(Buffer.from(crypto.randomFillSync(a).buffer,
2722                        a.byteOffset, a.byteLength).toString('hex'));
2723
2724const b = new Float64Array(10);
2725console.log(Buffer.from(crypto.randomFillSync(b).buffer,
2726                        b.byteOffset, b.byteLength).toString('hex'));
2727
2728const c = new DataView(new ArrayBuffer(10));
2729console.log(Buffer.from(crypto.randomFillSync(c).buffer,
2730                        c.byteOffset, c.byteLength).toString('hex'));
2731```
2732
2733### `crypto.randomFill(buffer[, offset][, size], callback)`
2734<!-- YAML
2735added:
2736  - v7.10.0
2737  - v6.13.0
2738changes:
2739  - version: v9.0.0
2740    pr-url: https://github.com/nodejs/node/pull/15231
2741    description: The `buffer` argument may be any `TypedArray` or `DataView`.
2742-->
2743
2744* `buffer` {Buffer|TypedArray|DataView} Must be supplied.
2745* `offset` {number} **Default:** `0`
2746* `size` {number} **Default:** `buffer.length - offset`
2747* `callback` {Function} `function(err, buf) {}`.
2748
2749This function is similar to [`crypto.randomBytes()`][] but requires the first
2750argument to be a [`Buffer`][] that will be filled. It also
2751requires that a callback is passed in.
2752
2753If the `callback` function is not provided, an error will be thrown.
2754
2755```js
2756const buf = Buffer.alloc(10);
2757crypto.randomFill(buf, (err, buf) => {
2758  if (err) throw err;
2759  console.log(buf.toString('hex'));
2760});
2761
2762crypto.randomFill(buf, 5, (err, buf) => {
2763  if (err) throw err;
2764  console.log(buf.toString('hex'));
2765});
2766
2767// The above is equivalent to the following:
2768crypto.randomFill(buf, 5, 5, (err, buf) => {
2769  if (err) throw err;
2770  console.log(buf.toString('hex'));
2771});
2772```
2773
2774Any `TypedArray` or `DataView` instance may be passed as `buffer`.
2775
2776```js
2777const a = new Uint32Array(10);
2778crypto.randomFill(a, (err, buf) => {
2779  if (err) throw err;
2780  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
2781    .toString('hex'));
2782});
2783
2784const b = new Float64Array(10);
2785crypto.randomFill(b, (err, buf) => {
2786  if (err) throw err;
2787  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
2788    .toString('hex'));
2789});
2790
2791const c = new DataView(new ArrayBuffer(10));
2792crypto.randomFill(c, (err, buf) => {
2793  if (err) throw err;
2794  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
2795    .toString('hex'));
2796});
2797```
2798
2799This API uses libuv's threadpool, which can have surprising and
2800negative performance implications for some applications; see the
2801[`UV_THREADPOOL_SIZE`][] documentation for more information.
2802
2803The asynchronous version of `crypto.randomFill()` is carried out in a single
2804threadpool request. To minimize threadpool task length variation, partition
2805large `randomFill` requests when doing so as part of fulfilling a client
2806request.
2807
2808### `crypto.randomInt([min, ]max[, callback])`
2809<!-- YAML
2810added: v14.10.0
2811-->
2812
2813* `min` {integer} Start of random range (inclusive). **Default**: `0`.
2814* `max` {integer} End of random range (exclusive).
2815* `callback` {Function} `function(err, n) {}`.
2816
2817Return a random integer `n` such that `min <= n < max`.  This
2818implementation avoids [modulo bias][].
2819
2820The range (`max - min`) must be less than 2<sup>48</sup>. `min` and `max` must
2821be [safe integers][].
2822
2823If the `callback` function is not provided, the random integer is
2824generated synchronously.
2825
2826```js
2827// Asynchronous
2828crypto.randomInt(3, (err, n) => {
2829  if (err) throw err;
2830  console.log(`Random number chosen from (0, 1, 2): ${n}`);
2831});
2832```
2833
2834```js
2835// Synchronous
2836const n = crypto.randomInt(3);
2837console.log(`Random number chosen from (0, 1, 2): ${n}`);
2838```
2839
2840```js
2841// With `min` argument
2842const n = crypto.randomInt(1, 7);
2843console.log(`The dice rolled: ${n}`);
2844```
2845
2846### `crypto.randomUUID([options])`
2847<!-- YAML
2848added: v14.17.0
2849-->
2850
2851* `options` {Object}
2852  * `disableEntropyCache` {boolean} By default, to improve performance,
2853    Node.js generates and caches enough random data to generate up to
2854    128 random UUIDs. To generate a UUID without using the cache, set
2855    `disableEntropyCache` to `true`. **Defaults**: `false`.
2856* Returns: {string}
2857
2858Generates a random [RFC 4122][] version 4 UUID. The UUID is generated using a
2859cryptographic pseudorandom number generator.
2860
2861### `crypto.scrypt(password, salt, keylen[, options], callback)`
2862<!-- YAML
2863added: v10.5.0
2864changes:
2865  - version:
2866     - v12.8.0
2867     - v10.17.0
2868    pr-url: https://github.com/nodejs/node/pull/28799
2869    description: The `maxmem` value can now be any safe integer.
2870  - version: v10.9.0
2871    pr-url: https://github.com/nodejs/node/pull/21525
2872    description: The `cost`, `blockSize` and `parallelization` option names
2873                 have been added.
2874-->
2875
2876* `password` {string|Buffer|TypedArray|DataView}
2877* `salt` {string|Buffer|TypedArray|DataView}
2878* `keylen` {number}
2879* `options` {Object}
2880  * `cost` {number} CPU/memory cost parameter. Must be a power of two greater
2881    than one. **Default:** `16384`.
2882  * `blockSize` {number} Block size parameter. **Default:** `8`.
2883  * `parallelization` {number} Parallelization parameter. **Default:** `1`.
2884  * `N` {number} Alias for `cost`. Only one of both may be specified.
2885  * `r` {number} Alias for `blockSize`. Only one of both may be specified.
2886  * `p` {number} Alias for `parallelization`. Only one of both may be specified.
2887  * `maxmem` {number} Memory upper bound. It is an error when (approximately)
2888    `128 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.
2889* `callback` {Function}
2890  * `err` {Error}
2891  * `derivedKey` {Buffer}
2892
2893Provides an asynchronous [scrypt][] implementation. Scrypt is a password-based
2894key derivation function that is designed to be expensive computationally and
2895memory-wise in order to make brute-force attacks unrewarding.
2896
2897The `salt` should be as unique as possible. It is recommended that a salt is
2898random and at least 16 bytes long. See [NIST SP 800-132][] for details.
2899
2900The `callback` function is called with two arguments: `err` and `derivedKey`.
2901`err` is an exception object when key derivation fails, otherwise `err` is
2902`null`. `derivedKey` is passed to the callback as a [`Buffer`][].
2903
2904An exception is thrown when any of the input arguments specify invalid values
2905or types.
2906
2907```js
2908const crypto = require('crypto');
2909// Using the factory defaults.
2910crypto.scrypt('password', 'salt', 64, (err, derivedKey) => {
2911  if (err) throw err;
2912  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
2913});
2914// Using a custom N parameter. Must be a power of two.
2915crypto.scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
2916  if (err) throw err;
2917  console.log(derivedKey.toString('hex'));  // '3745e48...aa39b34'
2918});
2919```
2920
2921### `crypto.scryptSync(password, salt, keylen[, options])`
2922<!-- YAML
2923added: v10.5.0
2924changes:
2925  - version:
2926     - v12.8.0
2927     - v10.17.0
2928    pr-url: https://github.com/nodejs/node/pull/28799
2929    description: The `maxmem` value can now be any safe integer.
2930  - version: v10.9.0
2931    pr-url: https://github.com/nodejs/node/pull/21525
2932    description: The `cost`, `blockSize` and `parallelization` option names
2933                 have been added.
2934-->
2935
2936* `password` {string|Buffer|TypedArray|DataView}
2937* `salt` {string|Buffer|TypedArray|DataView}
2938* `keylen` {number}
2939* `options` {Object}
2940  * `cost` {number} CPU/memory cost parameter. Must be a power of two greater
2941    than one. **Default:** `16384`.
2942  * `blockSize` {number} Block size parameter. **Default:** `8`.
2943  * `parallelization` {number} Parallelization parameter. **Default:** `1`.
2944  * `N` {number} Alias for `cost`. Only one of both may be specified.
2945  * `r` {number} Alias for `blockSize`. Only one of both may be specified.
2946  * `p` {number} Alias for `parallelization`. Only one of both may be specified.
2947  * `maxmem` {number} Memory upper bound. It is an error when (approximately)
2948    `128 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.
2949* Returns: {Buffer}
2950
2951Provides a synchronous [scrypt][] implementation. Scrypt is a password-based
2952key derivation function that is designed to be expensive computationally and
2953memory-wise in order to make brute-force attacks unrewarding.
2954
2955The `salt` should be as unique as possible. It is recommended that a salt is
2956random and at least 16 bytes long. See [NIST SP 800-132][] for details.
2957
2958An exception is thrown when key derivation fails, otherwise the derived key is
2959returned as a [`Buffer`][].
2960
2961An exception is thrown when any of the input arguments specify invalid values
2962or types.
2963
2964```js
2965const crypto = require('crypto');
2966// Using the factory defaults.
2967const key1 = crypto.scryptSync('password', 'salt', 64);
2968console.log(key1.toString('hex'));  // '3745e48...08d59ae'
2969// Using a custom N parameter. Must be a power of two.
2970const key2 = crypto.scryptSync('password', 'salt', 64, { N: 1024 });
2971console.log(key2.toString('hex'));  // '3745e48...aa39b34'
2972```
2973
2974### `crypto.setEngine(engine[, flags])`
2975<!-- YAML
2976added: v0.11.11
2977-->
2978
2979* `engine` {string}
2980* `flags` {crypto.constants} **Default:** `crypto.constants.ENGINE_METHOD_ALL`
2981
2982Load and set the `engine` for some or all OpenSSL functions (selected by flags).
2983
2984`engine` could be either an id or a path to the engine's shared library.
2985
2986The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags`
2987is a bit field taking one of or a mix of the following flags (defined in
2988`crypto.constants`):
2989
2990* `crypto.constants.ENGINE_METHOD_RSA`
2991* `crypto.constants.ENGINE_METHOD_DSA`
2992* `crypto.constants.ENGINE_METHOD_DH`
2993* `crypto.constants.ENGINE_METHOD_RAND`
2994* `crypto.constants.ENGINE_METHOD_EC`
2995* `crypto.constants.ENGINE_METHOD_CIPHERS`
2996* `crypto.constants.ENGINE_METHOD_DIGESTS`
2997* `crypto.constants.ENGINE_METHOD_PKEY_METHS`
2998* `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS`
2999* `crypto.constants.ENGINE_METHOD_ALL`
3000* `crypto.constants.ENGINE_METHOD_NONE`
3001
3002The flags below are deprecated in OpenSSL-1.1.0.
3003
3004* `crypto.constants.ENGINE_METHOD_ECDH`
3005* `crypto.constants.ENGINE_METHOD_ECDSA`
3006* `crypto.constants.ENGINE_METHOD_STORE`
3007
3008### `crypto.setFips(bool)`
3009<!-- YAML
3010added: v10.0.0
3011-->
3012
3013* `bool` {boolean} `true` to enable FIPS mode.
3014
3015Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.
3016Throws an error if FIPS mode is not available.
3017
3018### `crypto.sign(algorithm, data, key)`
3019<!-- YAML
3020added: v12.0.0
3021changes:
3022  - version:
3023     - v13.2.0
3024     - v12.16.0
3025    pr-url: https://github.com/nodejs/node/pull/29292
3026    description: This function now supports IEEE-P1363 DSA and ECDSA signatures.
3027-->
3028
3029* `algorithm` {string | null | undefined}
3030* `data` {Buffer | TypedArray | DataView}
3031* `key` {Object | string | Buffer | KeyObject}
3032* Returns: {Buffer}
3033
3034Calculates and returns the signature for `data` using the given private key and
3035algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is
3036dependent upon the key type (especially Ed25519 and Ed448).
3037
3038If `key` is not a [`KeyObject`][], this function behaves as if `key` had been
3039passed to [`crypto.createPrivateKey()`][]. If it is an object, the following
3040additional properties can be passed:
3041
3042* `dsaEncoding` {string} For DSA and ECDSA, this option specifies the
3043  format of the generated signature. It can be one of the following:
3044  * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`.
3045  * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363.
3046* `padding` {integer} Optional padding value for RSA, one of the following:
3047  * `crypto.constants.RSA_PKCS1_PADDING` (default)
3048  * `crypto.constants.RSA_PKCS1_PSS_PADDING`
3049
3050  `RSA_PKCS1_PSS_PADDING` will use MGF1 with the same hash function
3051  used to sign the message as specified in section 3.1 of [RFC 4055][].
3052* `saltLength` {integer} Salt length for when padding is
3053  `RSA_PKCS1_PSS_PADDING`. The special value
3054  `crypto.constants.RSA_PSS_SALTLEN_DIGEST` sets the salt length to the digest
3055  size, `crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN` (default) sets it to the
3056  maximum permissible value.
3057
3058### `crypto.timingSafeEqual(a, b)`
3059<!-- YAML
3060added: v6.6.0
3061-->
3062
3063* `a` {Buffer | TypedArray | DataView}
3064* `b` {Buffer | TypedArray | DataView}
3065* Returns: {boolean}
3066
3067This function is based on a constant-time algorithm.
3068Returns true if `a` is equal to `b`, without leaking timing information that
3069would allow an attacker to guess one of the values. This is suitable for
3070comparing HMAC digests or secret values like authentication cookies or
3071[capability urls](https://www.w3.org/TR/capability-urls/).
3072
3073`a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they
3074must have the same byte length.
3075
3076If at least one of `a` and `b` is a `TypedArray` with more than one byte per
3077entry, such as `Uint16Array`, the result will be computed using the platform
3078byte order.
3079
3080Use of `crypto.timingSafeEqual` does not guarantee that the *surrounding* code
3081is timing-safe. Care should be taken to ensure that the surrounding code does
3082not introduce timing vulnerabilities.
3083
3084### `crypto.verify(algorithm, data, key, signature)`
3085<!-- YAML
3086added: v12.0.0
3087changes:
3088  - version:
3089     - v13.2.0
3090     - v12.16.0
3091    pr-url: https://github.com/nodejs/node/pull/29292
3092    description: This function now supports IEEE-P1363 DSA and ECDSA signatures.
3093-->
3094
3095* `algorithm` {string | null | undefined}
3096* `data` {Buffer | TypedArray | DataView}
3097* `key` {Object | string | Buffer | KeyObject}
3098* `signature` {Buffer | TypedArray | DataView}
3099* Returns: {boolean}
3100
3101Verifies the given signature for `data` using the given key and algorithm. If
3102`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the
3103key type (especially Ed25519 and Ed448).
3104
3105If `key` is not a [`KeyObject`][], this function behaves as if `key` had been
3106passed to [`crypto.createPublicKey()`][]. If it is an object, the following
3107additional properties can be passed:
3108
3109* `dsaEncoding` {string} For DSA and ECDSA, this option specifies the
3110  format of the signature. It can be one of the following:
3111  * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`.
3112  * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363.
3113* `padding` {integer} Optional padding value for RSA, one of the following:
3114  * `crypto.constants.RSA_PKCS1_PADDING` (default)
3115  * `crypto.constants.RSA_PKCS1_PSS_PADDING`
3116
3117  `RSA_PKCS1_PSS_PADDING` will use MGF1 with the same hash function
3118  used to sign the message as specified in section 3.1 of [RFC 4055][].
3119* `saltLength` {integer} Salt length for when padding is
3120  `RSA_PKCS1_PSS_PADDING`. The special value
3121  `crypto.constants.RSA_PSS_SALTLEN_DIGEST` sets the salt length to the digest
3122  size, `crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN` (default) sets it to the
3123  maximum permissible value.
3124
3125The `signature` argument is the previously calculated signature for the `data`.
3126
3127Because public keys can be derived from private keys, a private key or a public
3128key may be passed for `key`.
3129
3130## Notes
3131
3132### Legacy streams API (prior to Node.js 0.10)
3133
3134The Crypto module was added to Node.js before there was the concept of a
3135unified Stream API, and before there were [`Buffer`][] objects for handling
3136binary data. As such, the many of the `crypto` defined classes have methods not
3137typically found on other Node.js classes that implement the [streams][stream]
3138API (e.g. `update()`, `final()`, or `digest()`). Also, many methods accepted
3139and returned `'latin1'` encoded strings by default rather than `Buffer`s. This
3140default was changed after Node.js v0.8 to use [`Buffer`][] objects by default
3141instead.
3142
3143### Recent ECDH changes
3144
3145Usage of `ECDH` with non-dynamically generated key pairs has been simplified.
3146Now, [`ecdh.setPrivateKey()`][] can be called with a preselected private key
3147and the associated public point (key) will be computed and stored in the object.
3148This allows code to only store and provide the private part of the EC key pair.
3149[`ecdh.setPrivateKey()`][] now also validates that the private key is valid for
3150the selected curve.
3151
3152The [`ecdh.setPublicKey()`][] method is now deprecated as its inclusion in the
3153API is not useful. Either a previously stored private key should be set, which
3154automatically generates the associated public key, or [`ecdh.generateKeys()`][]
3155should be called. The main drawback of using [`ecdh.setPublicKey()`][] is that
3156it can be used to put the ECDH key pair into an inconsistent state.
3157
3158### Support for weak or compromised algorithms
3159
3160The `crypto` module still supports some algorithms which are already
3161compromised and are not currently recommended for use. The API also allows
3162the use of ciphers and hashes with a small key size that are too weak for safe
3163use.
3164
3165Users should take full responsibility for selecting the crypto
3166algorithm and key size according to their security requirements.
3167
3168Based on the recommendations of [NIST SP 800-131A][]:
3169
3170* MD5 and SHA-1 are no longer acceptable where collision resistance is
3171  required such as digital signatures.
3172* The key used with RSA, DSA, and DH algorithms is recommended to have
3173  at least 2048 bits and that of the curve of ECDSA and ECDH at least
3174  224 bits, to be safe to use for several years.
3175* The DH groups of `modp1`, `modp2` and `modp5` have a key size
3176  smaller than 2048 bits and are not recommended.
3177
3178See the reference for other recommendations and details.
3179
3180### CCM mode
3181
3182CCM is one of the supported [AEAD algorithms][]. Applications which use this
3183mode must adhere to certain restrictions when using the cipher API:
3184
3185* The authentication tag length must be specified during cipher creation by
3186  setting the `authTagLength` option and must be one of 4, 6, 8, 10, 12, 14 or
3187  16 bytes.
3188* The length of the initialization vector (nonce) `N` must be between 7 and 13
3189  bytes (`7 ≤ N ≤ 13`).
3190* The length of the plaintext is limited to `2 ** (8 * (15 - N))` bytes.
3191* When decrypting, the authentication tag must be set via `setAuthTag()` before
3192  calling `update()`.
3193  Otherwise, decryption will fail and `final()` will throw an error in
3194  compliance with section 2.6 of [RFC 3610][].
3195* Using stream methods such as `write(data)`, `end(data)` or `pipe()` in CCM
3196  mode might fail as CCM cannot handle more than one chunk of data per instance.
3197* When passing additional authenticated data (AAD), the length of the actual
3198  message in bytes must be passed to `setAAD()` via the `plaintextLength`
3199  option.
3200  Many crypto libraries include the authentication tag in the ciphertext,
3201  which means that they produce ciphertexts of the length
3202  `plaintextLength + authTagLength`. Node.js does not include the authentication
3203  tag, so the ciphertext length is always `plaintextLength`.
3204  This is not necessary if no AAD is used.
3205* As CCM processes the whole message at once, `update()` can only be called
3206  once.
3207* Even though calling `update()` is sufficient to encrypt/decrypt the message,
3208  applications *must* call `final()` to compute or verify the
3209  authentication tag.
3210
3211```js
3212const crypto = require('crypto');
3213
3214const key = 'keykeykeykeykeykeykeykey';
3215const nonce = crypto.randomBytes(12);
3216
3217const aad = Buffer.from('0123456789', 'hex');
3218
3219const cipher = crypto.createCipheriv('aes-192-ccm', key, nonce, {
3220  authTagLength: 16
3221});
3222const plaintext = 'Hello world';
3223cipher.setAAD(aad, {
3224  plaintextLength: Buffer.byteLength(plaintext)
3225});
3226const ciphertext = cipher.update(plaintext, 'utf8');
3227cipher.final();
3228const tag = cipher.getAuthTag();
3229
3230// Now transmit { ciphertext, nonce, tag }.
3231
3232const decipher = crypto.createDecipheriv('aes-192-ccm', key, nonce, {
3233  authTagLength: 16
3234});
3235decipher.setAuthTag(tag);
3236decipher.setAAD(aad, {
3237  plaintextLength: ciphertext.length
3238});
3239const receivedPlaintext = decipher.update(ciphertext, null, 'utf8');
3240
3241try {
3242  decipher.final();
3243} catch (err) {
3244  console.error('Authentication failed!');
3245  return;
3246}
3247
3248console.log(receivedPlaintext);
3249```
3250
3251## Crypto constants
3252
3253The following constants exported by `crypto.constants` apply to various uses of
3254the `crypto`, `tls`, and `https` modules and are generally specific to OpenSSL.
3255
3256### OpenSSL options
3257
3258<table>
3259  <tr>
3260    <th>Constant</th>
3261    <th>Description</th>
3262  </tr>
3263  <tr>
3264    <td><code>SSL_OP_ALL</code></td>
3265    <td>Applies multiple bug workarounds within OpenSSL. See
3266    <a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html">https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html</a>
3267    for detail.</td>
3268  </tr>
3269  <tr>
3270    <td><code>SSL_OP_ALLOW_NO_DHE_KEX</code></td>
3271    <td>Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode
3272    for TLS v1.3</td>
3273  </tr>
3274  <tr>
3275    <td><code>SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION</code></td>
3276    <td>Allows legacy insecure renegotiation between OpenSSL and unpatched
3277    clients or servers. See
3278    <a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html">https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html</a>.</td>
3279  </tr>
3280  <tr>
3281    <td><code>SSL_OP_CIPHER_SERVER_PREFERENCE</code></td>
3282    <td>Attempts to use the server's preferences instead of the client's when
3283    selecting a cipher. Behavior depends on protocol version. See
3284    <a href="https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html">https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html</a>.</td>
3285  </tr>
3286  <tr>
3287    <td><code>SSL_OP_CISCO_ANYCONNECT</code></td>
3288    <td>Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER.</td>
3289  </tr>
3290  <tr>
3291    <td><code>SSL_OP_COOKIE_EXCHANGE</code></td>
3292    <td>Instructs OpenSSL to turn on cookie exchange.</td>
3293  </tr>
3294  <tr>
3295    <td><code>SSL_OP_CRYPTOPRO_TLSEXT_BUG</code></td>
3296    <td>Instructs OpenSSL to add server-hello extension from an early version
3297    of the cryptopro draft.</td>
3298  </tr>
3299  <tr>
3300    <td><code>SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS</code></td>
3301    <td>Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability
3302    workaround added in OpenSSL 0.9.6d.</td>
3303  </tr>
3304  <tr>
3305    <td><code>SSL_OP_EPHEMERAL_RSA</code></td>
3306    <td>Instructs OpenSSL to always use the tmp_rsa key when performing RSA
3307    operations.</td>
3308  </tr>
3309  <tr>
3310    <td><code>SSL_OP_LEGACY_SERVER_CONNECT</code></td>
3311    <td>Allows initial connection to servers that do not support RI.</td>
3312  </tr>
3313  <tr>
3314    <td><code>SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER</code></td>
3315    <td></td>
3316  </tr>
3317  <tr>
3318    <td><code>SSL_OP_MICROSOFT_SESS_ID_BUG</code></td>
3319    <td></td>
3320  </tr>
3321  <tr>
3322    <td><code>SSL_OP_MSIE_SSLV2_RSA_PADDING</code></td>
3323    <td>Instructs OpenSSL to disable the workaround for a man-in-the-middle
3324    protocol-version vulnerability in the SSL 2.0 server implementation.</td>
3325  </tr>
3326  <tr>
3327    <td><code>SSL_OP_NETSCAPE_CA_DN_BUG</code></td>
3328    <td></td>
3329  </tr>
3330  <tr>
3331    <td><code>SSL_OP_NETSCAPE_CHALLENGE_BUG</code></td>
3332    <td></td>
3333  </tr>
3334  <tr>
3335    <td><code>SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG</code></td>
3336    <td></td>
3337  </tr>
3338  <tr>
3339    <td><code>SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG</code></td>
3340    <td></td>
3341  </tr>
3342  <tr>
3343    <td><code>SSL_OP_NO_COMPRESSION</code></td>
3344    <td>Instructs OpenSSL to disable support for SSL/TLS compression.</td>
3345  </tr>
3346  <tr>
3347    <td><code>SSL_OP_NO_ENCRYPT_THEN_MAC</code></td>
3348    <td>Instructs OpenSSL to disable encrypt-then-MAC.</td>
3349  </tr>
3350  <tr>
3351    <td><code>SSL_OP_NO_QUERY_MTU</code></td>
3352    <td></td>
3353  </tr>
3354  <tr>
3355    <td><code>SSL_OP_NO_RENEGOTIATION</code></td>
3356    <td>Instructs OpenSSL to disable renegotiation.</td>
3357  </tr>
3358  <tr>
3359    <td><code>SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION</code></td>
3360    <td>Instructs OpenSSL to always start a new session when performing
3361    renegotiation.</td>
3362  </tr>
3363  <tr>
3364    <td><code>SSL_OP_NO_SSLv2</code></td>
3365    <td>Instructs OpenSSL to turn off SSL v2</td>
3366  </tr>
3367  <tr>
3368    <td><code>SSL_OP_NO_SSLv3</code></td>
3369    <td>Instructs OpenSSL to turn off SSL v3</td>
3370  </tr>
3371  <tr>
3372    <td><code>SSL_OP_NO_TICKET</code></td>
3373    <td>Instructs OpenSSL to disable use of RFC4507bis tickets.</td>
3374  </tr>
3375  <tr>
3376    <td><code>SSL_OP_NO_TLSv1</code></td>
3377    <td>Instructs OpenSSL to turn off TLS v1</td>
3378  </tr>
3379  <tr>
3380    <td><code>SSL_OP_NO_TLSv1_1</code></td>
3381    <td>Instructs OpenSSL to turn off TLS v1.1</td>
3382  </tr>
3383  <tr>
3384    <td><code>SSL_OP_NO_TLSv1_2</code></td>
3385    <td>Instructs OpenSSL to turn off TLS v1.2</td>
3386  </tr>
3387  <tr>
3388    <td><code>SSL_OP_NO_TLSv1_3</code></td>
3389    <td>Instructs OpenSSL to turn off TLS v1.3</td>
3390  </tr>
3391    <td><code>SSL_OP_PKCS1_CHECK_1</code></td>
3392    <td></td>
3393  </tr>
3394  <tr>
3395    <td><code>SSL_OP_PKCS1_CHECK_2</code></td>
3396    <td></td>
3397  </tr>
3398  <tr>
3399    <td><code>SSL_OP_PRIORITIZE_CHACHA</code></td>
3400    <td>Instructs OpenSSL server to prioritize ChaCha20Poly1305
3401    when client does.
3402    This option has no effect if
3403    <code>SSL_OP_CIPHER_SERVER_PREFERENCE</code>
3404    is not enabled.</td>
3405  </tr>
3406  <tr>
3407    <td><code>SSL_OP_SINGLE_DH_USE</code></td>
3408    <td>Instructs OpenSSL to always create a new key when using
3409    temporary/ephemeral DH parameters.</td>
3410  </tr>
3411  <tr>
3412    <td><code>SSL_OP_SINGLE_ECDH_USE</code></td>
3413    <td>Instructs OpenSSL to always create a new key when using
3414    temporary/ephemeral ECDH parameters.</td>
3415  </tr>
3416    <td><code>SSL_OP_SSLEAY_080_CLIENT_DH_BUG</code></td>
3417    <td></td>
3418  </tr>
3419  <tr>
3420    <td><code>SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG</code></td>
3421    <td></td>
3422  </tr>
3423  <tr>
3424    <td><code>SSL_OP_TLS_BLOCK_PADDING_BUG</code></td>
3425    <td></td>
3426  </tr>
3427  <tr>
3428    <td><code>SSL_OP_TLS_D5_BUG</code></td>
3429    <td></td>
3430  </tr>
3431  <tr>
3432    <td><code>SSL_OP_TLS_ROLLBACK_BUG</code></td>
3433    <td>Instructs OpenSSL to disable version rollback attack detection.</td>
3434  </tr>
3435</table>
3436
3437### OpenSSL engine constants
3438
3439<table>
3440  <tr>
3441    <th>Constant</th>
3442    <th>Description</th>
3443  </tr>
3444  <tr>
3445    <td><code>ENGINE_METHOD_RSA</code></td>
3446    <td>Limit engine usage to RSA</td>
3447  </tr>
3448  <tr>
3449    <td><code>ENGINE_METHOD_DSA</code></td>
3450    <td>Limit engine usage to DSA</td>
3451  </tr>
3452  <tr>
3453    <td><code>ENGINE_METHOD_DH</code></td>
3454    <td>Limit engine usage to DH</td>
3455  </tr>
3456  <tr>
3457    <td><code>ENGINE_METHOD_RAND</code></td>
3458    <td>Limit engine usage to RAND</td>
3459  </tr>
3460  <tr>
3461    <td><code>ENGINE_METHOD_EC</code></td>
3462    <td>Limit engine usage to EC</td>
3463  </tr>
3464  <tr>
3465    <td><code>ENGINE_METHOD_CIPHERS</code></td>
3466    <td>Limit engine usage to CIPHERS</td>
3467  </tr>
3468  <tr>
3469    <td><code>ENGINE_METHOD_DIGESTS</code></td>
3470    <td>Limit engine usage to DIGESTS</td>
3471  </tr>
3472  <tr>
3473    <td><code>ENGINE_METHOD_PKEY_METHS</code></td>
3474    <td>Limit engine usage to PKEY_METHDS</td>
3475  </tr>
3476  <tr>
3477    <td><code>ENGINE_METHOD_PKEY_ASN1_METHS</code></td>
3478    <td>Limit engine usage to PKEY_ASN1_METHS</td>
3479  </tr>
3480  <tr>
3481    <td><code>ENGINE_METHOD_ALL</code></td>
3482    <td></td>
3483  </tr>
3484  <tr>
3485    <td><code>ENGINE_METHOD_NONE</code></td>
3486    <td></td>
3487  </tr>
3488</table>
3489
3490### Other OpenSSL constants
3491
3492See the [list of SSL OP Flags][] for details.
3493
3494<table>
3495  <tr>
3496    <th>Constant</th>
3497    <th>Description</th>
3498  </tr>
3499  <tr>
3500    <td><code>DH_CHECK_P_NOT_SAFE_PRIME</code></td>
3501    <td></td>
3502  </tr>
3503  <tr>
3504    <td><code>DH_CHECK_P_NOT_PRIME</code></td>
3505    <td></td>
3506  </tr>
3507  <tr>
3508    <td><code>DH_UNABLE_TO_CHECK_GENERATOR</code></td>
3509    <td></td>
3510  </tr>
3511  <tr>
3512    <td><code>DH_NOT_SUITABLE_GENERATOR</code></td>
3513    <td></td>
3514  </tr>
3515  <tr>
3516    <td><code>ALPN_ENABLED</code></td>
3517    <td></td>
3518  </tr>
3519  <tr>
3520    <td><code>RSA_PKCS1_PADDING</code></td>
3521    <td></td>
3522  </tr>
3523  <tr>
3524    <td><code>RSA_SSLV23_PADDING</code></td>
3525    <td></td>
3526  </tr>
3527  <tr>
3528    <td><code>RSA_NO_PADDING</code></td>
3529    <td></td>
3530  </tr>
3531  <tr>
3532    <td><code>RSA_PKCS1_OAEP_PADDING</code></td>
3533    <td></td>
3534  </tr>
3535  <tr>
3536    <td><code>RSA_X931_PADDING</code></td>
3537    <td></td>
3538  </tr>
3539  <tr>
3540    <td><code>RSA_PKCS1_PSS_PADDING</code></td>
3541    <td></td>
3542  </tr>
3543  <tr>
3544    <td><code>RSA_PSS_SALTLEN_DIGEST</code></td>
3545    <td>Sets the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to the
3546        digest size when signing or verifying.</td>
3547  </tr>
3548  <tr>
3549    <td><code>RSA_PSS_SALTLEN_MAX_SIGN</code></td>
3550    <td>Sets the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to the
3551        maximum permissible value when signing data.</td>
3552  </tr>
3553  <tr>
3554    <td><code>RSA_PSS_SALTLEN_AUTO</code></td>
3555    <td>Causes the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to be
3556        determined automatically when verifying a signature.</td>
3557  </tr>
3558  <tr>
3559    <td><code>POINT_CONVERSION_COMPRESSED</code></td>
3560    <td></td>
3561  </tr>
3562  <tr>
3563    <td><code>POINT_CONVERSION_UNCOMPRESSED</code></td>
3564    <td></td>
3565  </tr>
3566  <tr>
3567    <td><code>POINT_CONVERSION_HYBRID</code></td>
3568    <td></td>
3569  </tr>
3570</table>
3571
3572### Node.js crypto constants
3573
3574<table>
3575  <tr>
3576    <th>Constant</th>
3577    <th>Description</th>
3578  </tr>
3579  <tr>
3580    <td><code>defaultCoreCipherList</code></td>
3581    <td>Specifies the built-in default cipher list used by Node.js.</td>
3582  </tr>
3583  <tr>
3584    <td><code>defaultCipherList</code></td>
3585    <td>Specifies the active default cipher list used by the current Node.js
3586    process.</td>
3587  </tr>
3588</table>
3589
3590[AEAD algorithms]: https://en.wikipedia.org/wiki/Authenticated_encryption
3591[CCM mode]: #crypto_ccm_mode
3592[Caveats]: #crypto_support_for_weak_or_compromised_algorithms
3593[Crypto constants]: #crypto_crypto_constants_1
3594[HTML 5.2]: https://www.w3.org/TR/html52/changes.html#features-removed
3595[HTML5's `keygen` element]: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen
3596[NIST SP 800-131A]: https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf
3597[NIST SP 800-132]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf
3598[NIST SP 800-38D]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
3599[Nonce-Disrespecting Adversaries]: https://github.com/nonce-disrespect/nonce-disrespect
3600[OpenSSL's SPKAC implementation]: https://www.openssl.org/docs/man1.1.0/apps/openssl-spkac.html
3601[RFC 1421]: https://www.rfc-editor.org/rfc/rfc1421.txt
3602[RFC 2412]: https://www.rfc-editor.org/rfc/rfc2412.txt
3603[RFC 3526]: https://www.rfc-editor.org/rfc/rfc3526.txt
3604[RFC 3610]: https://www.rfc-editor.org/rfc/rfc3610.txt
3605[RFC 4055]: https://www.rfc-editor.org/rfc/rfc4055.txt
3606[RFC 4122]: https://www.rfc-editor.org/rfc/rfc4122.txt
3607[RFC 5208]: https://www.rfc-editor.org/rfc/rfc5208.txt
3608[`Buffer`]: buffer.md
3609[`EVP_BytesToKey`]: https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html
3610[`KeyObject`]: #crypto_class_keyobject
3611[`Sign`]: #crypto_class_sign
3612[`UV_THREADPOOL_SIZE`]: cli.md#cli_uv_threadpool_size_size
3613[`Verify`]: #crypto_class_verify
3614[`cipher.final()`]: #crypto_cipher_final_outputencoding
3615[`cipher.update()`]: #crypto_cipher_update_data_inputencoding_outputencoding
3616[`crypto.createCipher()`]: #crypto_crypto_createcipher_algorithm_password_options
3617[`crypto.createCipheriv()`]: #crypto_crypto_createcipheriv_algorithm_key_iv_options
3618[`crypto.createDecipher()`]: #crypto_crypto_createdecipher_algorithm_password_options
3619[`crypto.createDecipheriv()`]: #crypto_crypto_createdecipheriv_algorithm_key_iv_options
3620[`crypto.createDiffieHellman()`]: #crypto_crypto_creatediffiehellman_prime_primeencoding_generator_generatorencoding
3621[`crypto.createECDH()`]: #crypto_crypto_createecdh_curvename
3622[`crypto.createHash()`]: #crypto_crypto_createhash_algorithm_options
3623[`crypto.createHmac()`]: #crypto_crypto_createhmac_algorithm_key_options
3624[`crypto.createPrivateKey()`]: #crypto_crypto_createprivatekey_key
3625[`crypto.createPublicKey()`]: #crypto_crypto_createpublickey_key
3626[`crypto.createSecretKey()`]: #crypto_crypto_createsecretkey_key
3627[`crypto.createSign()`]: #crypto_crypto_createsign_algorithm_options
3628[`crypto.createVerify()`]: #crypto_crypto_createverify_algorithm_options
3629[`crypto.getCurves()`]: #crypto_crypto_getcurves
3630[`crypto.getDiffieHellman()`]: #crypto_crypto_getdiffiehellman_groupname
3631[`crypto.getHashes()`]: #crypto_crypto_gethashes
3632[`crypto.privateDecrypt()`]: #crypto_crypto_privatedecrypt_privatekey_buffer
3633[`crypto.privateEncrypt()`]: #crypto_crypto_privateencrypt_privatekey_buffer
3634[`crypto.publicDecrypt()`]: #crypto_crypto_publicdecrypt_key_buffer
3635[`crypto.publicEncrypt()`]: #crypto_crypto_publicencrypt_key_buffer
3636[`crypto.randomBytes()`]: #crypto_crypto_randombytes_size_callback
3637[`crypto.randomFill()`]: #crypto_crypto_randomfill_buffer_offset_size_callback
3638[`crypto.scrypt()`]: #crypto_crypto_scrypt_password_salt_keylen_options_callback
3639[`decipher.final()`]: #crypto_decipher_final_outputencoding
3640[`decipher.update()`]: #crypto_decipher_update_data_inputencoding_outputencoding
3641[`diffieHellman.setPublicKey()`]: #crypto_diffiehellman_setpublickey_publickey_encoding
3642[`ecdh.generateKeys()`]: #crypto_ecdh_generatekeys_encoding_format
3643[`ecdh.setPrivateKey()`]: #crypto_ecdh_setprivatekey_privatekey_encoding
3644[`ecdh.setPublicKey()`]: #crypto_ecdh_setpublickey_publickey_encoding
3645[`hash.digest()`]: #crypto_hash_digest_encoding
3646[`hash.update()`]: #crypto_hash_update_data_inputencoding
3647[`hmac.digest()`]: #crypto_hmac_digest_encoding
3648[`hmac.update()`]: #crypto_hmac_update_data_inputencoding
3649[`keyObject.export()`]: #crypto_keyobject_export_options
3650[`postMessage()`]: worker_threads.md#worker_threads_port_postmessage_value_transferlist
3651[`sign.sign()`]: #crypto_sign_sign_privatekey_outputencoding
3652[`sign.update()`]: #crypto_sign_update_data_inputencoding
3653[`stream.Writable` options]: stream.md#stream_new_stream_writable_options
3654[`stream.transform` options]: stream.md#stream_new_stream_transform_options
3655[`util.promisify()`]: util.md#util_util_promisify_original
3656[`verify.update()`]: #crypto_verify_update_data_inputencoding
3657[`verify.verify()`]: #crypto_verify_verify_object_signature_signatureencoding
3658[encoding]: buffer.md#buffer_buffers_and_character_encodings
3659[initialization vector]: https://en.wikipedia.org/wiki/Initialization_vector
3660[list of SSL OP Flags]: https://wiki.openssl.org/index.php/List_of_SSL_OP_Flags#Table_of_Options
3661[modulo bias]: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias
3662[safe integers]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger
3663[scrypt]: https://en.wikipedia.org/wiki/Scrypt
3664[stream]: stream.md
3665[stream-writable-write]: stream.md#stream_writable_write_chunk_encoding_callback
3666