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