• 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 `node:crypto` module provides cryptographic functionality that includes a
10set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify
11functions.
12
13```mjs
14const { createHmac } = await import('node:crypto');
15
16const secret = 'abcdefg';
17const hash = createHmac('sha256', secret)
18               .update('I love cupcakes')
19               .digest('hex');
20console.log(hash);
21// Prints:
22//   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
23```
24
25```cjs
26const { createHmac } = require('node:crypto');
27
28const secret = 'abcdefg';
29const hash = createHmac('sha256', secret)
30               .update('I love cupcakes')
31               .digest('hex');
32console.log(hash);
33// Prints:
34//   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
35```
36
37## Determining if crypto support is unavailable
38
39It is possible for Node.js to be built without including support for the
40`node:crypto` module. In such cases, attempting to `import` from `crypto` or
41calling `require('node:crypto')` will result in an error being thrown.
42
43When using CommonJS, the error thrown can be caught using try/catch:
44
45<!-- eslint-skip -->
46
47```cjs
48let crypto;
49try {
50  crypto = require('node:crypto');
51} catch (err) {
52  console.error('crypto support is disabled!');
53}
54```
55
56When using the lexical ESM `import` keyword, the error can only be
57caught if a handler for `process.on('uncaughtException')` is registered
58_before_ any attempt to load the module is made (using, for instance,
59a preload module).
60
61When using ESM, if there is a chance that the code may be run on a build
62of Node.js where crypto support is not enabled, consider using the
63[`import()`][] function instead of the lexical `import` keyword:
64
65```mjs
66let crypto;
67try {
68  crypto = await import('node:crypto');
69} catch (err) {
70  console.error('crypto support is disabled!');
71}
72```
73
74## Class: `Certificate`
75
76<!-- YAML
77added: v0.11.8
78-->
79
80SPKAC is a Certificate Signing Request mechanism originally implemented by
81Netscape and was specified formally as part of HTML5's `keygen` element.
82
83`<keygen>` is deprecated since [HTML 5.2][] and new projects
84should not use this element anymore.
85
86The `node:crypto` module provides the `Certificate` class for working with SPKAC
87data. The most common usage is handling output generated by the HTML5
88`<keygen>` element. Node.js uses [OpenSSL's SPKAC implementation][] internally.
89
90### Static method: `Certificate.exportChallenge(spkac[, encoding])`
91
92<!-- YAML
93added: v9.0.0
94changes:
95  - version: v15.0.0
96    pr-url: https://github.com/nodejs/node/pull/35093
97    description: The spkac argument can be an ArrayBuffer. Limited the size of
98                 the spkac argument to a maximum of 2**31 - 1 bytes.
99-->
100
101* `spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}
102* `encoding` {string} The [encoding][] of the `spkac` string.
103* Returns: {Buffer} The challenge component of the `spkac` data structure, which
104  includes a public key and a challenge.
105
106```mjs
107const { Certificate } = await import('node:crypto');
108const spkac = getSpkacSomehow();
109const challenge = Certificate.exportChallenge(spkac);
110console.log(challenge.toString('utf8'));
111// Prints: the challenge as a UTF8 string
112```
113
114```cjs
115const { Certificate } = require('node:crypto');
116const spkac = getSpkacSomehow();
117const challenge = Certificate.exportChallenge(spkac);
118console.log(challenge.toString('utf8'));
119// Prints: the challenge as a UTF8 string
120```
121
122### Static method: `Certificate.exportPublicKey(spkac[, encoding])`
123
124<!-- YAML
125added: v9.0.0
126changes:
127  - version: v15.0.0
128    pr-url: https://github.com/nodejs/node/pull/35093
129    description: The spkac argument can be an ArrayBuffer. Limited the size of
130                 the spkac argument to a maximum of 2**31 - 1 bytes.
131-->
132
133* `spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}
134* `encoding` {string} The [encoding][] of the `spkac` string.
135* Returns: {Buffer} The public key component of the `spkac` data structure,
136  which includes a public key and a challenge.
137
138```mjs
139const { Certificate } = await import('node:crypto');
140const spkac = getSpkacSomehow();
141const publicKey = Certificate.exportPublicKey(spkac);
142console.log(publicKey);
143// Prints: the public key as <Buffer ...>
144```
145
146```cjs
147const { Certificate } = require('node:crypto');
148const spkac = getSpkacSomehow();
149const publicKey = Certificate.exportPublicKey(spkac);
150console.log(publicKey);
151// Prints: the public key as <Buffer ...>
152```
153
154### Static method: `Certificate.verifySpkac(spkac[, encoding])`
155
156<!-- YAML
157added: v9.0.0
158changes:
159  - version: v15.0.0
160    pr-url: https://github.com/nodejs/node/pull/35093
161    description: The spkac argument can be an ArrayBuffer. Added encoding.
162                 Limited the size of the spkac argument to a maximum of
163                 2**31 - 1 bytes.
164-->
165
166* `spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}
167* `encoding` {string} The [encoding][] of the `spkac` string.
168* Returns: {boolean} `true` if the given `spkac` data structure is valid,
169  `false` otherwise.
170
171```mjs
172import { Buffer } from 'node:buffer';
173const { Certificate } = await import('node:crypto');
174
175const spkac = getSpkacSomehow();
176console.log(Certificate.verifySpkac(Buffer.from(spkac)));
177// Prints: true or false
178```
179
180```cjs
181const { Buffer } = require('node:buffer');
182const { Certificate } = require('node:crypto');
183
184const spkac = getSpkacSomehow();
185console.log(Certificate.verifySpkac(Buffer.from(spkac)));
186// Prints: true or false
187```
188
189### Legacy API
190
191> Stability: 0 - Deprecated
192
193As a legacy interface, it is possible to create new instances of
194the `crypto.Certificate` class as illustrated in the examples below.
195
196#### `new crypto.Certificate()`
197
198Instances of the `Certificate` class can be created using the `new` keyword
199or by calling `crypto.Certificate()` as a function:
200
201```mjs
202const { Certificate } = await import('node:crypto');
203
204const cert1 = new Certificate();
205const cert2 = Certificate();
206```
207
208```cjs
209const { Certificate } = require('node:crypto');
210
211const cert1 = new Certificate();
212const cert2 = Certificate();
213```
214
215#### `certificate.exportChallenge(spkac[, encoding])`
216
217<!-- YAML
218added: v0.11.8
219-->
220
221* `spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}
222* `encoding` {string} The [encoding][] of the `spkac` string.
223* Returns: {Buffer} The challenge component of the `spkac` data structure, which
224  includes a public key and a challenge.
225
226```mjs
227const { Certificate } = await import('node:crypto');
228const cert = Certificate();
229const spkac = getSpkacSomehow();
230const challenge = cert.exportChallenge(spkac);
231console.log(challenge.toString('utf8'));
232// Prints: the challenge as a UTF8 string
233```
234
235```cjs
236const { Certificate } = require('node:crypto');
237const cert = Certificate();
238const spkac = getSpkacSomehow();
239const challenge = cert.exportChallenge(spkac);
240console.log(challenge.toString('utf8'));
241// Prints: the challenge as a UTF8 string
242```
243
244#### `certificate.exportPublicKey(spkac[, encoding])`
245
246<!-- YAML
247added: v0.11.8
248-->
249
250* `spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}
251* `encoding` {string} The [encoding][] of the `spkac` string.
252* Returns: {Buffer} The public key component of the `spkac` data structure,
253  which includes a public key and a challenge.
254
255```mjs
256const { Certificate } = await import('node:crypto');
257const cert = Certificate();
258const spkac = getSpkacSomehow();
259const publicKey = cert.exportPublicKey(spkac);
260console.log(publicKey);
261// Prints: the public key as <Buffer ...>
262```
263
264```cjs
265const { Certificate } = require('node:crypto');
266const cert = Certificate();
267const spkac = getSpkacSomehow();
268const publicKey = cert.exportPublicKey(spkac);
269console.log(publicKey);
270// Prints: the public key as <Buffer ...>
271```
272
273#### `certificate.verifySpkac(spkac[, encoding])`
274
275<!-- YAML
276added: v0.11.8
277-->
278
279* `spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}
280* `encoding` {string} The [encoding][] of the `spkac` string.
281* Returns: {boolean} `true` if the given `spkac` data structure is valid,
282  `false` otherwise.
283
284```mjs
285import { Buffer } from 'node:buffer';
286const { Certificate } = await import('node:crypto');
287
288const cert = Certificate();
289const spkac = getSpkacSomehow();
290console.log(cert.verifySpkac(Buffer.from(spkac)));
291// Prints: true or false
292```
293
294```cjs
295const { Buffer } = require('node:buffer');
296const { Certificate } = require('node:crypto');
297
298const cert = Certificate();
299const spkac = getSpkacSomehow();
300console.log(cert.verifySpkac(Buffer.from(spkac)));
301// Prints: true or false
302```
303
304## Class: `Cipher`
305
306<!-- YAML
307added: v0.1.94
308-->
309
310* Extends: {stream.Transform}
311
312Instances of the `Cipher` class are used to encrypt data. The class can be
313used in one of two ways:
314
315* As a [stream][] that is both readable and writable, where plain unencrypted
316  data is written to produce encrypted data on the readable side, or
317* Using the [`cipher.update()`][] and [`cipher.final()`][] methods to produce
318  the encrypted data.
319
320The [`crypto.createCipher()`][] or [`crypto.createCipheriv()`][] methods are
321used to create `Cipher` instances. `Cipher` objects are not to be created
322directly using the `new` keyword.
323
324Example: Using `Cipher` objects as streams:
325
326```mjs
327const {
328  scrypt,
329  randomFill,
330  createCipheriv,
331} = await import('node:crypto');
332
333const algorithm = 'aes-192-cbc';
334const password = 'Password used to generate key';
335
336// First, we'll generate the key. The key length is dependent on the algorithm.
337// In this case for aes192, it is 24 bytes (192 bits).
338scrypt(password, 'salt', 24, (err, key) => {
339  if (err) throw err;
340  // Then, we'll generate a random initialization vector
341  randomFill(new Uint8Array(16), (err, iv) => {
342    if (err) throw err;
343
344    // Once we have the key and iv, we can create and use the cipher...
345    const cipher = createCipheriv(algorithm, key, iv);
346
347    let encrypted = '';
348    cipher.setEncoding('hex');
349
350    cipher.on('data', (chunk) => encrypted += chunk);
351    cipher.on('end', () => console.log(encrypted));
352
353    cipher.write('some clear text data');
354    cipher.end();
355  });
356});
357```
358
359```cjs
360const {
361  scrypt,
362  randomFill,
363  createCipheriv,
364} = require('node:crypto');
365
366const algorithm = 'aes-192-cbc';
367const password = 'Password used to generate key';
368
369// First, we'll generate the key. The key length is dependent on the algorithm.
370// In this case for aes192, it is 24 bytes (192 bits).
371scrypt(password, 'salt', 24, (err, key) => {
372  if (err) throw err;
373  // Then, we'll generate a random initialization vector
374  randomFill(new Uint8Array(16), (err, iv) => {
375    if (err) throw err;
376
377    // Once we have the key and iv, we can create and use the cipher...
378    const cipher = createCipheriv(algorithm, key, iv);
379
380    let encrypted = '';
381    cipher.setEncoding('hex');
382
383    cipher.on('data', (chunk) => encrypted += chunk);
384    cipher.on('end', () => console.log(encrypted));
385
386    cipher.write('some clear text data');
387    cipher.end();
388  });
389});
390```
391
392Example: Using `Cipher` and piped streams:
393
394```mjs
395import {
396  createReadStream,
397  createWriteStream,
398} from 'node:fs';
399
400import {
401  pipeline,
402} from 'node:stream';
403
404const {
405  scrypt,
406  randomFill,
407  createCipheriv,
408} = await import('node:crypto');
409
410const algorithm = 'aes-192-cbc';
411const password = 'Password used to generate key';
412
413// First, we'll generate the key. The key length is dependent on the algorithm.
414// In this case for aes192, it is 24 bytes (192 bits).
415scrypt(password, 'salt', 24, (err, key) => {
416  if (err) throw err;
417  // Then, we'll generate a random initialization vector
418  randomFill(new Uint8Array(16), (err, iv) => {
419    if (err) throw err;
420
421    const cipher = createCipheriv(algorithm, key, iv);
422
423    const input = createReadStream('test.js');
424    const output = createWriteStream('test.enc');
425
426    pipeline(input, cipher, output, (err) => {
427      if (err) throw err;
428    });
429  });
430});
431```
432
433```cjs
434const {
435  createReadStream,
436  createWriteStream,
437} = require('node:fs');
438
439const {
440  pipeline,
441} = require('node:stream');
442
443const {
444  scrypt,
445  randomFill,
446  createCipheriv,
447} = require('node:crypto');
448
449const algorithm = 'aes-192-cbc';
450const password = 'Password used to generate key';
451
452// First, we'll generate the key. The key length is dependent on the algorithm.
453// In this case for aes192, it is 24 bytes (192 bits).
454scrypt(password, 'salt', 24, (err, key) => {
455  if (err) throw err;
456  // Then, we'll generate a random initialization vector
457  randomFill(new Uint8Array(16), (err, iv) => {
458    if (err) throw err;
459
460    const cipher = createCipheriv(algorithm, key, iv);
461
462    const input = createReadStream('test.js');
463    const output = createWriteStream('test.enc');
464
465    pipeline(input, cipher, output, (err) => {
466      if (err) throw err;
467    });
468  });
469});
470```
471
472Example: Using the [`cipher.update()`][] and [`cipher.final()`][] methods:
473
474```mjs
475const {
476  scrypt,
477  randomFill,
478  createCipheriv,
479} = await import('node:crypto');
480
481const algorithm = 'aes-192-cbc';
482const password = 'Password used to generate key';
483
484// First, we'll generate the key. The key length is dependent on the algorithm.
485// In this case for aes192, it is 24 bytes (192 bits).
486scrypt(password, 'salt', 24, (err, key) => {
487  if (err) throw err;
488  // Then, we'll generate a random initialization vector
489  randomFill(new Uint8Array(16), (err, iv) => {
490    if (err) throw err;
491
492    const cipher = createCipheriv(algorithm, key, iv);
493
494    let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
495    encrypted += cipher.final('hex');
496    console.log(encrypted);
497  });
498});
499```
500
501```cjs
502const {
503  scrypt,
504  randomFill,
505  createCipheriv,
506} = require('node:crypto');
507
508const algorithm = 'aes-192-cbc';
509const password = 'Password used to generate key';
510
511// First, we'll generate the key. The key length is dependent on the algorithm.
512// In this case for aes192, it is 24 bytes (192 bits).
513scrypt(password, 'salt', 24, (err, key) => {
514  if (err) throw err;
515  // Then, we'll generate a random initialization vector
516  randomFill(new Uint8Array(16), (err, iv) => {
517    if (err) throw err;
518
519    const cipher = createCipheriv(algorithm, key, iv);
520
521    let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
522    encrypted += cipher.final('hex');
523    console.log(encrypted);
524  });
525});
526```
527
528### `cipher.final([outputEncoding])`
529
530<!-- YAML
531added: v0.1.94
532-->
533
534* `outputEncoding` {string} The [encoding][] of the return value.
535* Returns: {Buffer | string} Any remaining enciphered contents.
536  If `outputEncoding` is specified, a string is
537  returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned.
538
539Once the `cipher.final()` method has been called, the `Cipher` object can no
540longer be used to encrypt data. Attempts to call `cipher.final()` more than
541once will result in an error being thrown.
542
543### `cipher.getAuthTag()`
544
545<!-- YAML
546added: v1.0.0
547-->
548
549* Returns: {Buffer} When using an authenticated encryption mode (`GCM`, `CCM`,
550  `OCB`, and `chacha20-poly1305` are currently supported), the
551  `cipher.getAuthTag()` method returns a
552  [`Buffer`][] containing the _authentication tag_ that has been computed from
553  the given data.
554
555The `cipher.getAuthTag()` method should only be called after encryption has
556been completed using the [`cipher.final()`][] method.
557
558If the `authTagLength` option was set during the `cipher` instance's creation,
559this function will return exactly `authTagLength` bytes.
560
561### `cipher.setAAD(buffer[, options])`
562
563<!-- YAML
564added: v1.0.0
565-->
566
567* `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}
568* `options` {Object} [`stream.transform` options][]
569  * `plaintextLength` {number}
570  * `encoding` {string} The string encoding to use when `buffer` is a string.
571* Returns: {Cipher} for method chaining.
572
573When using an authenticated encryption mode (`GCM`, `CCM`, `OCB`, and
574`chacha20-poly1305` are
575currently supported), the `cipher.setAAD()` method sets the value used for the
576_additional authenticated data_ (AAD) input parameter.
577
578The `plaintextLength` option is optional for `GCM` and `OCB`. When using `CCM`,
579the `plaintextLength` option must be specified and its value must match the
580length of the plaintext in bytes. See [CCM mode][].
581
582The `cipher.setAAD()` method must be called before [`cipher.update()`][].
583
584### `cipher.setAutoPadding([autoPadding])`
585
586<!-- YAML
587added: v0.7.1
588-->
589
590* `autoPadding` {boolean} **Default:** `true`
591* Returns: {Cipher} for method chaining.
592
593When using block encryption algorithms, the `Cipher` class will automatically
594add padding to the input data to the appropriate block size. To disable the
595default padding call `cipher.setAutoPadding(false)`.
596
597When `autoPadding` is `false`, the length of the entire input data must be a
598multiple of the cipher's block size or [`cipher.final()`][] will throw an error.
599Disabling automatic padding is useful for non-standard padding, for instance
600using `0x0` instead of PKCS padding.
601
602The `cipher.setAutoPadding()` method must be called before
603[`cipher.final()`][].
604
605### `cipher.update(data[, inputEncoding][, outputEncoding])`
606
607<!-- YAML
608added: v0.1.94
609changes:
610  - version: v6.0.0
611    pr-url: https://github.com/nodejs/node/pull/5522
612    description: The default `inputEncoding` changed from `binary` to `utf8`.
613-->
614
615* `data` {string|Buffer|TypedArray|DataView}
616* `inputEncoding` {string} The [encoding][] of the data.
617* `outputEncoding` {string} The [encoding][] of the return value.
618* Returns: {Buffer | string}
619
620Updates the cipher with `data`. If the `inputEncoding` argument is given,
621the `data`
622argument is a string using the specified encoding. If the `inputEncoding`
623argument is not given, `data` must be a [`Buffer`][], `TypedArray`, or
624`DataView`. If `data` is a [`Buffer`][], `TypedArray`, or `DataView`, then
625`inputEncoding` is ignored.
626
627The `outputEncoding` specifies the output format of the enciphered
628data. If the `outputEncoding`
629is specified, a string using the specified encoding is returned. If no
630`outputEncoding` is provided, a [`Buffer`][] is returned.
631
632The `cipher.update()` method can be called multiple times with new data until
633[`cipher.final()`][] is called. Calling `cipher.update()` after
634[`cipher.final()`][] will result in an error being thrown.
635
636## Class: `Decipher`
637
638<!-- YAML
639added: v0.1.94
640-->
641
642* Extends: {stream.Transform}
643
644Instances of the `Decipher` class are used to decrypt data. The class can be
645used in one of two ways:
646
647* As a [stream][] that is both readable and writable, where plain encrypted
648  data is written to produce unencrypted data on the readable side, or
649* Using the [`decipher.update()`][] and [`decipher.final()`][] methods to
650  produce the unencrypted data.
651
652The [`crypto.createDecipher()`][] or [`crypto.createDecipheriv()`][] methods are
653used to create `Decipher` instances. `Decipher` objects are not to be created
654directly using the `new` keyword.
655
656Example: Using `Decipher` objects as streams:
657
658```mjs
659import { Buffer } from 'node:buffer';
660const {
661  scryptSync,
662  createDecipheriv,
663} = await import('node:crypto');
664
665const algorithm = 'aes-192-cbc';
666const password = 'Password used to generate key';
667// Key length is dependent on the algorithm. In this case for aes192, it is
668// 24 bytes (192 bits).
669// Use the async `crypto.scrypt()` instead.
670const key = scryptSync(password, 'salt', 24);
671// The IV is usually passed along with the ciphertext.
672const iv = Buffer.alloc(16, 0); // Initialization vector.
673
674const decipher = createDecipheriv(algorithm, key, iv);
675
676let decrypted = '';
677decipher.on('readable', () => {
678  let chunk;
679  while (null !== (chunk = decipher.read())) {
680    decrypted += chunk.toString('utf8');
681  }
682});
683decipher.on('end', () => {
684  console.log(decrypted);
685  // Prints: some clear text data
686});
687
688// Encrypted with same algorithm, key and iv.
689const encrypted =
690  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
691decipher.write(encrypted, 'hex');
692decipher.end();
693```
694
695```cjs
696const {
697  scryptSync,
698  createDecipheriv,
699} = require('node:crypto');
700const { Buffer } = require('node:buffer');
701
702const algorithm = 'aes-192-cbc';
703const password = 'Password used to generate key';
704// Key length is dependent on the algorithm. In this case for aes192, it is
705// 24 bytes (192 bits).
706// Use the async `crypto.scrypt()` instead.
707const key = scryptSync(password, 'salt', 24);
708// The IV is usually passed along with the ciphertext.
709const iv = Buffer.alloc(16, 0); // Initialization vector.
710
711const decipher = createDecipheriv(algorithm, key, iv);
712
713let decrypted = '';
714decipher.on('readable', () => {
715  let chunk;
716  while (null !== (chunk = decipher.read())) {
717    decrypted += chunk.toString('utf8');
718  }
719});
720decipher.on('end', () => {
721  console.log(decrypted);
722  // Prints: some clear text data
723});
724
725// Encrypted with same algorithm, key and iv.
726const encrypted =
727  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
728decipher.write(encrypted, 'hex');
729decipher.end();
730```
731
732Example: Using `Decipher` and piped streams:
733
734```mjs
735import {
736  createReadStream,
737  createWriteStream,
738} from 'node:fs';
739import { Buffer } from 'node:buffer';
740const {
741  scryptSync,
742  createDecipheriv,
743} = await import('node:crypto');
744
745const algorithm = 'aes-192-cbc';
746const password = 'Password used to generate key';
747// Use the async `crypto.scrypt()` instead.
748const key = scryptSync(password, 'salt', 24);
749// The IV is usually passed along with the ciphertext.
750const iv = Buffer.alloc(16, 0); // Initialization vector.
751
752const decipher = createDecipheriv(algorithm, key, iv);
753
754const input = createReadStream('test.enc');
755const output = createWriteStream('test.js');
756
757input.pipe(decipher).pipe(output);
758```
759
760```cjs
761const {
762  createReadStream,
763  createWriteStream,
764} = require('node:fs');
765const {
766  scryptSync,
767  createDecipheriv,
768} = require('node:crypto');
769const { Buffer } = require('node:buffer');
770
771const algorithm = 'aes-192-cbc';
772const password = 'Password used to generate key';
773// Use the async `crypto.scrypt()` instead.
774const key = scryptSync(password, 'salt', 24);
775// The IV is usually passed along with the ciphertext.
776const iv = Buffer.alloc(16, 0); // Initialization vector.
777
778const decipher = createDecipheriv(algorithm, key, iv);
779
780const input = createReadStream('test.enc');
781const output = createWriteStream('test.js');
782
783input.pipe(decipher).pipe(output);
784```
785
786Example: Using the [`decipher.update()`][] and [`decipher.final()`][] methods:
787
788```mjs
789import { Buffer } from 'node:buffer';
790const {
791  scryptSync,
792  createDecipheriv,
793} = await import('node:crypto');
794
795const algorithm = 'aes-192-cbc';
796const password = 'Password used to generate key';
797// Use the async `crypto.scrypt()` instead.
798const key = scryptSync(password, 'salt', 24);
799// The IV is usually passed along with the ciphertext.
800const iv = Buffer.alloc(16, 0); // Initialization vector.
801
802const decipher = createDecipheriv(algorithm, key, iv);
803
804// Encrypted using same algorithm, key and iv.
805const encrypted =
806  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
807let decrypted = decipher.update(encrypted, 'hex', 'utf8');
808decrypted += decipher.final('utf8');
809console.log(decrypted);
810// Prints: some clear text data
811```
812
813```cjs
814const {
815  scryptSync,
816  createDecipheriv,
817} = require('node:crypto');
818const { Buffer } = require('node:buffer');
819
820const algorithm = 'aes-192-cbc';
821const password = 'Password used to generate key';
822// Use the async `crypto.scrypt()` instead.
823const key = scryptSync(password, 'salt', 24);
824// The IV is usually passed along with the ciphertext.
825const iv = Buffer.alloc(16, 0); // Initialization vector.
826
827const decipher = createDecipheriv(algorithm, key, iv);
828
829// Encrypted using same algorithm, key and iv.
830const encrypted =
831  'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
832let decrypted = decipher.update(encrypted, 'hex', 'utf8');
833decrypted += decipher.final('utf8');
834console.log(decrypted);
835// Prints: some clear text data
836```
837
838### `decipher.final([outputEncoding])`
839
840<!-- YAML
841added: v0.1.94
842-->
843
844* `outputEncoding` {string} The [encoding][] of the return value.
845* Returns: {Buffer | string} Any remaining deciphered contents.
846  If `outputEncoding` is specified, a string is
847  returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned.
848
849Once the `decipher.final()` method has been called, the `Decipher` object can
850no longer be used to decrypt data. Attempts to call `decipher.final()` more
851than once will result in an error being thrown.
852
853### `decipher.setAAD(buffer[, options])`
854
855<!-- YAML
856added: v1.0.0
857changes:
858  - version: v15.0.0
859    pr-url: https://github.com/nodejs/node/pull/35093
860    description: The buffer argument can be a string or ArrayBuffer and is
861                limited to no more than 2 ** 31 - 1 bytes.
862  - version: v7.2.0
863    pr-url: https://github.com/nodejs/node/pull/9398
864    description: This method now returns a reference to `decipher`.
865-->
866
867* `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}
868* `options` {Object} [`stream.transform` options][]
869  * `plaintextLength` {number}
870  * `encoding` {string} String encoding to use when `buffer` is a string.
871* Returns: {Decipher} for method chaining.
872
873When using an authenticated encryption mode (`GCM`, `CCM`, `OCB`, and
874`chacha20-poly1305` are
875currently supported), the `decipher.setAAD()` method sets the value used for the
876_additional authenticated data_ (AAD) input parameter.
877
878The `options` argument is optional for `GCM`. When using `CCM`, the
879`plaintextLength` option must be specified and its value must match the length
880of the ciphertext in bytes. See [CCM mode][].
881
882The `decipher.setAAD()` method must be called before [`decipher.update()`][].
883
884When passing a string as the `buffer`, please consider
885[caveats when using strings as inputs to cryptographic APIs][].
886
887### `decipher.setAuthTag(buffer[, encoding])`
888
889<!-- YAML
890added: v1.0.0
891changes:
892  - version: v15.0.0
893    pr-url: https://github.com/nodejs/node/pull/35093
894    description: The buffer argument can be a string or ArrayBuffer and is
895                limited to no more than 2 ** 31 - 1 bytes.
896  - version: v11.0.0
897    pr-url: https://github.com/nodejs/node/pull/17825
898    description: This method now throws if the GCM tag length is invalid.
899  - version: v7.2.0
900    pr-url: https://github.com/nodejs/node/pull/9398
901    description: This method now returns a reference to `decipher`.
902-->
903
904* `buffer` {string|Buffer|ArrayBuffer|TypedArray|DataView}
905* `encoding` {string} String encoding to use when `buffer` is a string.
906* Returns: {Decipher} for method chaining.
907
908When using an authenticated encryption mode (`GCM`, `CCM`, `OCB`, and
909`chacha20-poly1305` are
910currently supported), the `decipher.setAuthTag()` method is used to pass in the
911received _authentication tag_. If no tag is provided, or if the cipher text
912has been tampered with, [`decipher.final()`][] will throw, indicating that the
913cipher text should be discarded due to failed authentication. If the tag length
914is invalid according to [NIST SP 800-38D][] or does not match the value of the
915`authTagLength` option, `decipher.setAuthTag()` will throw an error.
916
917The `decipher.setAuthTag()` method must be called before [`decipher.update()`][]
918for `CCM` mode or before [`decipher.final()`][] for `GCM` and `OCB` modes and
919`chacha20-poly1305`.
920`decipher.setAuthTag()` can only be called once.
921
922When passing a string as the authentication tag, please consider
923[caveats when using strings as inputs to cryptographic APIs][].
924
925### `decipher.setAutoPadding([autoPadding])`
926
927<!-- YAML
928added: v0.7.1
929-->
930
931* `autoPadding` {boolean} **Default:** `true`
932* Returns: {Decipher} for method chaining.
933
934When data has been encrypted without standard block padding, calling
935`decipher.setAutoPadding(false)` will disable automatic padding to prevent
936[`decipher.final()`][] from checking for and removing padding.
937
938Turning auto padding off will only work if the input data's length is a
939multiple of the ciphers block size.
940
941The `decipher.setAutoPadding()` method must be called before
942[`decipher.final()`][].
943
944### `decipher.update(data[, inputEncoding][, outputEncoding])`
945
946<!-- YAML
947added: v0.1.94
948changes:
949  - version: v6.0.0
950    pr-url: https://github.com/nodejs/node/pull/5522
951    description: The default `inputEncoding` changed from `binary` to `utf8`.
952-->
953
954* `data` {string|Buffer|TypedArray|DataView}
955* `inputEncoding` {string} The [encoding][] of the `data` string.
956* `outputEncoding` {string} The [encoding][] of the return value.
957* Returns: {Buffer | string}
958
959Updates the decipher with `data`. If the `inputEncoding` argument is given,
960the `data`
961argument is a string using the specified encoding. If the `inputEncoding`
962argument is not given, `data` must be a [`Buffer`][]. If `data` is a
963[`Buffer`][] then `inputEncoding` is ignored.
964
965The `outputEncoding` specifies the output format of the enciphered
966data. If the `outputEncoding`
967is specified, a string using the specified encoding is returned. If no
968`outputEncoding` is provided, a [`Buffer`][] is returned.
969
970The `decipher.update()` method can be called multiple times with new data until
971[`decipher.final()`][] is called. Calling `decipher.update()` after
972[`decipher.final()`][] will result in an error being thrown.
973
974## Class: `DiffieHellman`
975
976<!-- YAML
977added: v0.5.0
978-->
979
980The `DiffieHellman` class is a utility for creating Diffie-Hellman key
981exchanges.
982
983Instances of the `DiffieHellman` class can be created using the
984[`crypto.createDiffieHellman()`][] function.
985
986```mjs
987import assert from 'node:assert';
988
989const {
990  createDiffieHellman,
991} = await import('node:crypto');
992
993// Generate Alice's keys...
994const alice = createDiffieHellman(2048);
995const aliceKey = alice.generateKeys();
996
997// Generate Bob's keys...
998const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());
999const bobKey = bob.generateKeys();
1000
1001// Exchange and generate the secret...
1002const aliceSecret = alice.computeSecret(bobKey);
1003const bobSecret = bob.computeSecret(aliceKey);
1004
1005// OK
1006assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
1007```
1008
1009```cjs
1010const assert = require('node:assert');
1011
1012const {
1013  createDiffieHellman,
1014} = require('node:crypto');
1015
1016// Generate Alice's keys...
1017const alice = createDiffieHellman(2048);
1018const aliceKey = alice.generateKeys();
1019
1020// Generate Bob's keys...
1021const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());
1022const bobKey = bob.generateKeys();
1023
1024// Exchange and generate the secret...
1025const aliceSecret = alice.computeSecret(bobKey);
1026const bobSecret = bob.computeSecret(aliceKey);
1027
1028// OK
1029assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
1030```
1031
1032### `diffieHellman.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])`
1033
1034<!-- YAML
1035added: v0.5.0
1036-->
1037
1038* `otherPublicKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}
1039* `inputEncoding` {string} The [encoding][] of an `otherPublicKey` string.
1040* `outputEncoding` {string} The [encoding][] of the return value.
1041* Returns: {Buffer | string}
1042
1043Computes the shared secret using `otherPublicKey` as the other
1044party's public key and returns the computed shared secret. The supplied
1045key is interpreted using the specified `inputEncoding`, and secret is
1046encoded using specified `outputEncoding`.
1047If the `inputEncoding` is not
1048provided, `otherPublicKey` is expected to be a [`Buffer`][],
1049`TypedArray`, or `DataView`.
1050
1051If `outputEncoding` is given a string is returned; otherwise, a
1052[`Buffer`][] is returned.
1053
1054### `diffieHellman.generateKeys([encoding])`
1055
1056<!-- YAML
1057added: v0.5.0
1058-->
1059
1060* `encoding` {string} The [encoding][] of the return value.
1061* Returns: {Buffer | string}
1062
1063Generates private and public Diffie-Hellman key values unless they have been
1064generated or computed already, and returns
1065the public key in the specified `encoding`. This key should be
1066transferred to the other party.
1067If `encoding` is provided a string is returned; otherwise a
1068[`Buffer`][] is returned.
1069
1070This function is a thin wrapper around [`DH_generate_key()`][]. In particular,
1071once a private key has been generated or set, calling this function only updates
1072the public key but does not generate a new private key.
1073
1074### `diffieHellman.getGenerator([encoding])`
1075
1076<!-- YAML
1077added: v0.5.0
1078-->
1079
1080* `encoding` {string} The [encoding][] of the return value.
1081* Returns: {Buffer | string}
1082
1083Returns the Diffie-Hellman generator in the specified `encoding`.
1084If `encoding` is provided a string is
1085returned; otherwise a [`Buffer`][] is returned.
1086
1087### `diffieHellman.getPrime([encoding])`
1088
1089<!-- YAML
1090added: v0.5.0
1091-->
1092
1093* `encoding` {string} The [encoding][] of the return value.
1094* Returns: {Buffer | string}
1095
1096Returns the Diffie-Hellman prime in the specified `encoding`.
1097If `encoding` is provided a string is
1098returned; otherwise a [`Buffer`][] is returned.
1099
1100### `diffieHellman.getPrivateKey([encoding])`
1101
1102<!-- YAML
1103added: v0.5.0
1104-->
1105
1106* `encoding` {string} The [encoding][] of the return value.
1107* Returns: {Buffer | string}
1108
1109Returns the Diffie-Hellman private key in the specified `encoding`.
1110If `encoding` is provided a
1111string is returned; otherwise a [`Buffer`][] is returned.
1112
1113### `diffieHellman.getPublicKey([encoding])`
1114
1115<!-- YAML
1116added: v0.5.0
1117-->
1118
1119* `encoding` {string} The [encoding][] of the return value.
1120* Returns: {Buffer | string}
1121
1122Returns the Diffie-Hellman public key in the specified `encoding`.
1123If `encoding` is provided a
1124string is returned; otherwise a [`Buffer`][] is returned.
1125
1126### `diffieHellman.setPrivateKey(privateKey[, encoding])`
1127
1128<!-- YAML
1129added: v0.5.0
1130-->
1131
1132* `privateKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}
1133* `encoding` {string} The [encoding][] of the `privateKey` string.
1134
1135Sets the Diffie-Hellman private key. If the `encoding` argument is provided,
1136`privateKey` is expected
1137to be a string. If no `encoding` is provided, `privateKey` is expected
1138to be a [`Buffer`][], `TypedArray`, or `DataView`.
1139
1140This function does not automatically compute the associated public key. Either
1141[`diffieHellman.setPublicKey()`][] or [`diffieHellman.generateKeys()`][] can be
1142used to manually provide the public key or to automatically derive it.
1143
1144### `diffieHellman.setPublicKey(publicKey[, encoding])`
1145
1146<!-- YAML
1147added: v0.5.0
1148-->
1149
1150* `publicKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}
1151* `encoding` {string} The [encoding][] of the `publicKey` string.
1152
1153Sets the Diffie-Hellman public key. If the `encoding` argument is provided,
1154`publicKey` is expected
1155to be a string. If no `encoding` is provided, `publicKey` is expected
1156to be a [`Buffer`][], `TypedArray`, or `DataView`.
1157
1158### `diffieHellman.verifyError`
1159
1160<!-- YAML
1161added: v0.11.12
1162-->
1163
1164A bit field containing any warnings and/or errors resulting from a check
1165performed during initialization of the `DiffieHellman` object.
1166
1167The following values are valid for this property (as defined in `node:constants` module):
1168
1169* `DH_CHECK_P_NOT_SAFE_PRIME`
1170* `DH_CHECK_P_NOT_PRIME`
1171* `DH_UNABLE_TO_CHECK_GENERATOR`
1172* `DH_NOT_SUITABLE_GENERATOR`
1173
1174## Class: `DiffieHellmanGroup`
1175
1176<!-- YAML
1177added: v0.7.5
1178-->
1179
1180The `DiffieHellmanGroup` class takes a well-known modp group as its argument.
1181It works the same as `DiffieHellman`, except that it does not allow changing
1182its keys after creation. In other words, it does not implement `setPublicKey()`
1183or `setPrivateKey()` methods.
1184
1185```mjs
1186const { createDiffieHellmanGroup } = await import('node:crypto');
1187const dh = createDiffieHellmanGroup('modp16');
1188```
1189
1190```cjs
1191const { createDiffieHellmanGroup } = require('node:crypto');
1192const dh = createDiffieHellmanGroup('modp16');
1193```
1194
1195The following groups are supported:
1196
1197* `'modp14'` (2048 bits, [RFC 3526][] Section 3)
1198* `'modp15'` (3072 bits, [RFC 3526][] Section 4)
1199* `'modp16'` (4096 bits, [RFC 3526][] Section 5)
1200* `'modp17'` (6144 bits, [RFC 3526][] Section 6)
1201* `'modp18'` (8192 bits, [RFC 3526][] Section 7)
1202
1203The following groups are still supported but deprecated (see [Caveats][]):
1204
1205* `'modp1'` (768 bits, [RFC 2409][] Section 6.1) <span class="deprecated-inline"></span>
1206* `'modp2'` (1024 bits, [RFC 2409][] Section 6.2) <span class="deprecated-inline"></span>
1207* `'modp5'` (1536 bits, [RFC 3526][] Section 2) <span class="deprecated-inline"></span>
1208
1209These deprecated groups might be removed in future versions of Node.js.
1210
1211## Class: `ECDH`
1212
1213<!-- YAML
1214added: v0.11.14
1215-->
1216
1217The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)
1218key exchanges.
1219
1220Instances of the `ECDH` class can be created using the
1221[`crypto.createECDH()`][] function.
1222
1223```mjs
1224import assert from 'node:assert';
1225
1226const {
1227  createECDH,
1228} = await import('node:crypto');
1229
1230// Generate Alice's keys...
1231const alice = createECDH('secp521r1');
1232const aliceKey = alice.generateKeys();
1233
1234// Generate Bob's keys...
1235const bob = createECDH('secp521r1');
1236const bobKey = bob.generateKeys();
1237
1238// Exchange and generate the secret...
1239const aliceSecret = alice.computeSecret(bobKey);
1240const bobSecret = bob.computeSecret(aliceKey);
1241
1242assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
1243// OK
1244```
1245
1246```cjs
1247const assert = require('node:assert');
1248
1249const {
1250  createECDH,
1251} = require('node:crypto');
1252
1253// Generate Alice's keys...
1254const alice = createECDH('secp521r1');
1255const aliceKey = alice.generateKeys();
1256
1257// Generate Bob's keys...
1258const bob = createECDH('secp521r1');
1259const bobKey = bob.generateKeys();
1260
1261// Exchange and generate the secret...
1262const aliceSecret = alice.computeSecret(bobKey);
1263const bobSecret = bob.computeSecret(aliceKey);
1264
1265assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
1266// OK
1267```
1268
1269### Static method: `ECDH.convertKey(key, curve[, inputEncoding[, outputEncoding[, format]]])`
1270
1271<!-- YAML
1272added: v10.0.0
1273-->
1274
1275* `key` {string|ArrayBuffer|Buffer|TypedArray|DataView}
1276* `curve` {string}
1277* `inputEncoding` {string} The [encoding][] of the `key` string.
1278* `outputEncoding` {string} The [encoding][] of the return value.
1279* `format` {string} **Default:** `'uncompressed'`
1280* Returns: {Buffer | string}
1281
1282Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the
1283format specified by `format`. The `format` argument specifies point encoding
1284and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is
1285interpreted using the specified `inputEncoding`, and the returned key is encoded
1286using the specified `outputEncoding`.
1287
1288Use [`crypto.getCurves()`][] to obtain a list of available curve names.
1289On recent OpenSSL releases, `openssl ecparam -list_curves` will also display
1290the name and description of each available elliptic curve.
1291
1292If `format` is not specified the point will be returned in `'uncompressed'`
1293format.
1294
1295If the `inputEncoding` is not provided, `key` is expected to be a [`Buffer`][],
1296`TypedArray`, or `DataView`.
1297
1298Example (uncompressing a key):
1299
1300```mjs
1301const {
1302  createECDH,
1303  ECDH,
1304} = await import('node:crypto');
1305
1306const ecdh = createECDH('secp256k1');
1307ecdh.generateKeys();
1308
1309const compressedKey = ecdh.getPublicKey('hex', 'compressed');
1310
1311const uncompressedKey = ECDH.convertKey(compressedKey,
1312                                        'secp256k1',
1313                                        'hex',
1314                                        'hex',
1315                                        'uncompressed');
1316
1317// The converted key and the uncompressed public key should be the same
1318console.log(uncompressedKey === ecdh.getPublicKey('hex'));
1319```
1320
1321```cjs
1322const {
1323  createECDH,
1324  ECDH,
1325} = require('node:crypto');
1326
1327const ecdh = createECDH('secp256k1');
1328ecdh.generateKeys();
1329
1330const compressedKey = ecdh.getPublicKey('hex', 'compressed');
1331
1332const uncompressedKey = ECDH.convertKey(compressedKey,
1333                                        'secp256k1',
1334                                        'hex',
1335                                        'hex',
1336                                        'uncompressed');
1337
1338// The converted key and the uncompressed public key should be the same
1339console.log(uncompressedKey === ecdh.getPublicKey('hex'));
1340```
1341
1342### `ecdh.computeSecret(otherPublicKey[, inputEncoding][, outputEncoding])`
1343
1344<!-- YAML
1345added: v0.11.14
1346changes:
1347  - version: v10.0.0
1348    pr-url: https://github.com/nodejs/node/pull/16849
1349    description: Changed error format to better support invalid public key
1350                 error.
1351  - version: v6.0.0
1352    pr-url: https://github.com/nodejs/node/pull/5522
1353    description: The default `inputEncoding` changed from `binary` to `utf8`.
1354-->
1355
1356* `otherPublicKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}
1357* `inputEncoding` {string} The [encoding][] of the `otherPublicKey` string.
1358* `outputEncoding` {string} The [encoding][] of the return value.
1359* Returns: {Buffer | string}
1360
1361Computes the shared secret using `otherPublicKey` as the other
1362party's public key and returns the computed shared secret. The supplied
1363key is interpreted using specified `inputEncoding`, and the returned secret
1364is encoded using the specified `outputEncoding`.
1365If the `inputEncoding` is not
1366provided, `otherPublicKey` is expected to be a [`Buffer`][], `TypedArray`, or
1367`DataView`.
1368
1369If `outputEncoding` is given a string will be returned; otherwise a
1370[`Buffer`][] is returned.
1371
1372`ecdh.computeSecret` will throw an
1373`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`
1374lies outside of the elliptic curve. Since `otherPublicKey` is
1375usually supplied from a remote user over an insecure network,
1376be sure to handle this exception accordingly.
1377
1378### `ecdh.generateKeys([encoding[, format]])`
1379
1380<!-- YAML
1381added: v0.11.14
1382-->
1383
1384* `encoding` {string} The [encoding][] of the return value.
1385* `format` {string} **Default:** `'uncompressed'`
1386* Returns: {Buffer | string}
1387
1388Generates private and public EC Diffie-Hellman key values, and returns
1389the public key in the specified `format` and `encoding`. This key should be
1390transferred to the other party.
1391
1392The `format` argument specifies point encoding and can be `'compressed'` or
1393`'uncompressed'`. If `format` is not specified, the point will be returned in
1394`'uncompressed'` format.
1395
1396If `encoding` is provided a string is returned; otherwise a [`Buffer`][]
1397is returned.
1398
1399### `ecdh.getPrivateKey([encoding])`
1400
1401<!-- YAML
1402added: v0.11.14
1403-->
1404
1405* `encoding` {string} The [encoding][] of the return value.
1406* Returns: {Buffer | string} The EC Diffie-Hellman in the specified `encoding`.
1407
1408If `encoding` is specified, a string is returned; otherwise a [`Buffer`][] is
1409returned.
1410
1411### `ecdh.getPublicKey([encoding][, format])`
1412
1413<!-- YAML
1414added: v0.11.14
1415-->
1416
1417* `encoding` {string} The [encoding][] of the return value.
1418* `format` {string} **Default:** `'uncompressed'`
1419* Returns: {Buffer | string} The EC Diffie-Hellman public key in the specified
1420  `encoding` and `format`.
1421
1422The `format` argument specifies point encoding and can be `'compressed'` or
1423`'uncompressed'`. If `format` is not specified the point will be returned in
1424`'uncompressed'` format.
1425
1426If `encoding` is specified, a string is returned; otherwise a [`Buffer`][] is
1427returned.
1428
1429### `ecdh.setPrivateKey(privateKey[, encoding])`
1430
1431<!-- YAML
1432added: v0.11.14
1433-->
1434
1435* `privateKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}
1436* `encoding` {string} The [encoding][] of the `privateKey` string.
1437
1438Sets the EC Diffie-Hellman private key.
1439If `encoding` is provided, `privateKey` is expected
1440to be a string; otherwise `privateKey` is expected to be a [`Buffer`][],
1441`TypedArray`, or `DataView`.
1442
1443If `privateKey` is not valid for the curve specified when the `ECDH` object was
1444created, an error is thrown. Upon setting the private key, the associated
1445public point (key) is also generated and set in the `ECDH` object.
1446
1447### `ecdh.setPublicKey(publicKey[, encoding])`
1448
1449<!-- YAML
1450added: v0.11.14
1451deprecated: v5.2.0
1452-->
1453
1454> Stability: 0 - Deprecated
1455
1456* `publicKey` {string|ArrayBuffer|Buffer|TypedArray|DataView}
1457* `encoding` {string} The [encoding][] of the `publicKey` string.
1458
1459Sets the EC Diffie-Hellman public key.
1460If `encoding` is provided `publicKey` is expected to
1461be a string; otherwise a [`Buffer`][], `TypedArray`, or `DataView` is expected.
1462
1463There is not normally a reason to call this method because `ECDH`
1464only requires a private key and the other party's public key to compute the
1465shared secret. Typically either [`ecdh.generateKeys()`][] or
1466[`ecdh.setPrivateKey()`][] will be called. The [`ecdh.setPrivateKey()`][] method
1467attempts to generate the public point/key associated with the private key being
1468set.
1469
1470Example (obtaining a shared secret):
1471
1472```mjs
1473const {
1474  createECDH,
1475  createHash,
1476} = await import('node:crypto');
1477
1478const alice = createECDH('secp256k1');
1479const bob = createECDH('secp256k1');
1480
1481// This is a shortcut way of specifying one of Alice's previous private
1482// keys. It would be unwise to use such a predictable private key in a real
1483// application.
1484alice.setPrivateKey(
1485  createHash('sha256').update('alice', 'utf8').digest(),
1486);
1487
1488// Bob uses a newly generated cryptographically strong
1489// pseudorandom key pair
1490bob.generateKeys();
1491
1492const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
1493const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
1494
1495// aliceSecret and bobSecret should be the same shared secret value
1496console.log(aliceSecret === bobSecret);
1497```
1498
1499```cjs
1500const {
1501  createECDH,
1502  createHash,
1503} = require('node:crypto');
1504
1505const alice = createECDH('secp256k1');
1506const bob = createECDH('secp256k1');
1507
1508// This is a shortcut way of specifying one of Alice's previous private
1509// keys. It would be unwise to use such a predictable private key in a real
1510// application.
1511alice.setPrivateKey(
1512  createHash('sha256').update('alice', 'utf8').digest(),
1513);
1514
1515// Bob uses a newly generated cryptographically strong
1516// pseudorandom key pair
1517bob.generateKeys();
1518
1519const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
1520const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
1521
1522// aliceSecret and bobSecret should be the same shared secret value
1523console.log(aliceSecret === bobSecret);
1524```
1525
1526## Class: `Hash`
1527
1528<!-- YAML
1529added: v0.1.92
1530-->
1531
1532* Extends: {stream.Transform}
1533
1534The `Hash` class is a utility for creating hash digests of data. It can be
1535used in one of two ways:
1536
1537* As a [stream][] that is both readable and writable, where data is written
1538  to produce a computed hash digest on the readable side, or
1539* Using the [`hash.update()`][] and [`hash.digest()`][] methods to produce the
1540  computed hash.
1541
1542The [`crypto.createHash()`][] method is used to create `Hash` instances. `Hash`
1543objects are not to be created directly using the `new` keyword.
1544
1545Example: Using `Hash` objects as streams:
1546
1547```mjs
1548const {
1549  createHash,
1550} = await import('node:crypto');
1551
1552const hash = createHash('sha256');
1553
1554hash.on('readable', () => {
1555  // Only one element is going to be produced by the
1556  // hash stream.
1557  const data = hash.read();
1558  if (data) {
1559    console.log(data.toString('hex'));
1560    // Prints:
1561    //   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
1562  }
1563});
1564
1565hash.write('some data to hash');
1566hash.end();
1567```
1568
1569```cjs
1570const {
1571  createHash,
1572} = require('node:crypto');
1573
1574const hash = createHash('sha256');
1575
1576hash.on('readable', () => {
1577  // Only one element is going to be produced by the
1578  // hash stream.
1579  const data = hash.read();
1580  if (data) {
1581    console.log(data.toString('hex'));
1582    // Prints:
1583    //   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
1584  }
1585});
1586
1587hash.write('some data to hash');
1588hash.end();
1589```
1590
1591Example: Using `Hash` and piped streams:
1592
1593```mjs
1594import { createReadStream } from 'node:fs';
1595import { stdout } from 'node:process';
1596const { createHash } = await import('node:crypto');
1597
1598const hash = createHash('sha256');
1599
1600const input = createReadStream('test.js');
1601input.pipe(hash).setEncoding('hex').pipe(stdout);
1602```
1603
1604```cjs
1605const { createReadStream } = require('node:fs');
1606const { createHash } = require('node:crypto');
1607const { stdout } = require('node:process');
1608
1609const hash = createHash('sha256');
1610
1611const input = createReadStream('test.js');
1612input.pipe(hash).setEncoding('hex').pipe(stdout);
1613```
1614
1615Example: Using the [`hash.update()`][] and [`hash.digest()`][] methods:
1616
1617```mjs
1618const {
1619  createHash,
1620} = await import('node:crypto');
1621
1622const hash = createHash('sha256');
1623
1624hash.update('some data to hash');
1625console.log(hash.digest('hex'));
1626// Prints:
1627//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
1628```
1629
1630```cjs
1631const {
1632  createHash,
1633} = require('node:crypto');
1634
1635const hash = createHash('sha256');
1636
1637hash.update('some data to hash');
1638console.log(hash.digest('hex'));
1639// Prints:
1640//   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
1641```
1642
1643### `hash.copy([options])`
1644
1645<!-- YAML
1646added: v13.1.0
1647-->
1648
1649* `options` {Object} [`stream.transform` options][]
1650* Returns: {Hash}
1651
1652Creates a new `Hash` object that contains a deep copy of the internal state
1653of the current `Hash` object.
1654
1655The optional `options` argument controls stream behavior. For XOF hash
1656functions such as `'shake256'`, the `outputLength` option can be used to
1657specify the desired output length in bytes.
1658
1659An error is thrown when an attempt is made to copy the `Hash` object after
1660its [`hash.digest()`][] method has been called.
1661
1662```mjs
1663// Calculate a rolling hash.
1664const {
1665  createHash,
1666} = await import('node:crypto');
1667
1668const hash = createHash('sha256');
1669
1670hash.update('one');
1671console.log(hash.copy().digest('hex'));
1672
1673hash.update('two');
1674console.log(hash.copy().digest('hex'));
1675
1676hash.update('three');
1677console.log(hash.copy().digest('hex'));
1678
1679// Etc.
1680```
1681
1682```cjs
1683// Calculate a rolling hash.
1684const {
1685  createHash,
1686} = require('node:crypto');
1687
1688const hash = createHash('sha256');
1689
1690hash.update('one');
1691console.log(hash.copy().digest('hex'));
1692
1693hash.update('two');
1694console.log(hash.copy().digest('hex'));
1695
1696hash.update('three');
1697console.log(hash.copy().digest('hex'));
1698
1699// Etc.
1700```
1701
1702### `hash.digest([encoding])`
1703
1704<!-- YAML
1705added: v0.1.92
1706-->
1707
1708* `encoding` {string} The [encoding][] of the return value.
1709* Returns: {Buffer | string}
1710
1711Calculates the digest of all of the data passed to be hashed (using the
1712[`hash.update()`][] method).
1713If `encoding` is provided a string will be returned; otherwise
1714a [`Buffer`][] is returned.
1715
1716The `Hash` object can not be used again after `hash.digest()` method has been
1717called. Multiple calls will cause an error to be thrown.
1718
1719### `hash.update(data[, inputEncoding])`
1720
1721<!-- YAML
1722added: v0.1.92
1723changes:
1724  - version: v6.0.0
1725    pr-url: https://github.com/nodejs/node/pull/5522
1726    description: The default `inputEncoding` changed from `binary` to `utf8`.
1727-->
1728
1729* `data` {string|Buffer|TypedArray|DataView}
1730* `inputEncoding` {string} The [encoding][] of the `data` string.
1731
1732Updates the hash content with the given `data`, the encoding of which
1733is given in `inputEncoding`.
1734If `encoding` is not provided, and the `data` is a string, an
1735encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or
1736`DataView`, then `inputEncoding` is ignored.
1737
1738This can be called many times with new data as it is streamed.
1739
1740## Class: `Hmac`
1741
1742<!-- YAML
1743added: v0.1.94
1744-->
1745
1746* Extends: {stream.Transform}
1747
1748The `Hmac` class is a utility for creating cryptographic HMAC digests. It can
1749be used in one of two ways:
1750
1751* As a [stream][] that is both readable and writable, where data is written
1752  to produce a computed HMAC digest on the readable side, or
1753* Using the [`hmac.update()`][] and [`hmac.digest()`][] methods to produce the
1754  computed HMAC digest.
1755
1756The [`crypto.createHmac()`][] method is used to create `Hmac` instances. `Hmac`
1757objects are not to be created directly using the `new` keyword.
1758
1759Example: Using `Hmac` objects as streams:
1760
1761```mjs
1762const {
1763  createHmac,
1764} = await import('node:crypto');
1765
1766const hmac = createHmac('sha256', 'a secret');
1767
1768hmac.on('readable', () => {
1769  // Only one element is going to be produced by the
1770  // hash stream.
1771  const data = hmac.read();
1772  if (data) {
1773    console.log(data.toString('hex'));
1774    // Prints:
1775    //   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
1776  }
1777});
1778
1779hmac.write('some data to hash');
1780hmac.end();
1781```
1782
1783```cjs
1784const {
1785  createHmac,
1786} = require('node:crypto');
1787
1788const hmac = createHmac('sha256', 'a secret');
1789
1790hmac.on('readable', () => {
1791  // Only one element is going to be produced by the
1792  // hash stream.
1793  const data = hmac.read();
1794  if (data) {
1795    console.log(data.toString('hex'));
1796    // Prints:
1797    //   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
1798  }
1799});
1800
1801hmac.write('some data to hash');
1802hmac.end();
1803```
1804
1805Example: Using `Hmac` and piped streams:
1806
1807```mjs
1808import { createReadStream } from 'node:fs';
1809import { stdout } from 'node:process';
1810const {
1811  createHmac,
1812} = await import('node:crypto');
1813
1814const hmac = createHmac('sha256', 'a secret');
1815
1816const input = createReadStream('test.js');
1817input.pipe(hmac).pipe(stdout);
1818```
1819
1820```cjs
1821const {
1822  createReadStream,
1823} = require('node:fs');
1824const {
1825  createHmac,
1826} = require('node:crypto');
1827const { stdout } = require('node:process');
1828
1829const hmac = createHmac('sha256', 'a secret');
1830
1831const input = createReadStream('test.js');
1832input.pipe(hmac).pipe(stdout);
1833```
1834
1835Example: Using the [`hmac.update()`][] and [`hmac.digest()`][] methods:
1836
1837```mjs
1838const {
1839  createHmac,
1840} = await import('node:crypto');
1841
1842const hmac = createHmac('sha256', 'a secret');
1843
1844hmac.update('some data to hash');
1845console.log(hmac.digest('hex'));
1846// Prints:
1847//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
1848```
1849
1850```cjs
1851const {
1852  createHmac,
1853} = require('node:crypto');
1854
1855const hmac = createHmac('sha256', 'a secret');
1856
1857hmac.update('some data to hash');
1858console.log(hmac.digest('hex'));
1859// Prints:
1860//   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
1861```
1862
1863### `hmac.digest([encoding])`
1864
1865<!-- YAML
1866added: v0.1.94
1867-->
1868
1869* `encoding` {string} The [encoding][] of the return value.
1870* Returns: {Buffer | string}
1871
1872Calculates the HMAC digest of all of the data passed using [`hmac.update()`][].
1873If `encoding` is
1874provided a string is returned; otherwise a [`Buffer`][] is returned;
1875
1876The `Hmac` object can not be used again after `hmac.digest()` has been
1877called. Multiple calls to `hmac.digest()` will result in an error being thrown.
1878
1879### `hmac.update(data[, inputEncoding])`
1880
1881<!-- YAML
1882added: v0.1.94
1883changes:
1884  - version: v6.0.0
1885    pr-url: https://github.com/nodejs/node/pull/5522
1886    description: The default `inputEncoding` changed from `binary` to `utf8`.
1887-->
1888
1889* `data` {string|Buffer|TypedArray|DataView}
1890* `inputEncoding` {string} The [encoding][] of the `data` string.
1891
1892Updates the `Hmac` content with the given `data`, the encoding of which
1893is given in `inputEncoding`.
1894If `encoding` is not provided, and the `data` is a string, an
1895encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or
1896`DataView`, then `inputEncoding` is ignored.
1897
1898This can be called many times with new data as it is streamed.
1899
1900## Class: `KeyObject`
1901
1902<!-- YAML
1903added: v11.6.0
1904changes:
1905  - version:
1906    - v14.5.0
1907    - v12.19.0
1908    pr-url: https://github.com/nodejs/node/pull/33360
1909    description: Instances of this class can now be passed to worker threads
1910                 using `postMessage`.
1911  - version: v11.13.0
1912    pr-url: https://github.com/nodejs/node/pull/26438
1913    description: This class is now exported.
1914-->
1915
1916Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key,
1917and each kind of key exposes different functions. The
1918[`crypto.createSecretKey()`][], [`crypto.createPublicKey()`][] and
1919[`crypto.createPrivateKey()`][] methods are used to create `KeyObject`
1920instances. `KeyObject` objects are not to be created directly using the `new`
1921keyword.
1922
1923Most applications should consider using the new `KeyObject` API instead of
1924passing keys as strings or `Buffer`s due to improved security features.
1925
1926`KeyObject` instances can be passed to other threads via [`postMessage()`][].
1927The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to
1928be listed in the `transferList` argument.
1929
1930### Static method: `KeyObject.from(key)`
1931
1932<!-- YAML
1933added: v15.0.0
1934-->
1935
1936* `key` {CryptoKey}
1937* Returns: {KeyObject}
1938
1939Example: Converting a `CryptoKey` instance to a `KeyObject`:
1940
1941```mjs
1942const { webcrypto, KeyObject } = await import('node:crypto');
1943const { subtle } = webcrypto;
1944
1945const key = await subtle.generateKey({
1946  name: 'HMAC',
1947  hash: 'SHA-256',
1948  length: 256,
1949}, true, ['sign', 'verify']);
1950
1951const keyObject = KeyObject.from(key);
1952console.log(keyObject.symmetricKeySize);
1953// Prints: 32 (symmetric key size in bytes)
1954```
1955
1956```cjs
1957const {
1958  webcrypto: {
1959    subtle,
1960  },
1961  KeyObject,
1962} = require('node:crypto');
1963
1964(async function() {
1965  const key = await subtle.generateKey({
1966    name: 'HMAC',
1967    hash: 'SHA-256',
1968    length: 256,
1969  }, true, ['sign', 'verify']);
1970
1971  const keyObject = KeyObject.from(key);
1972  console.log(keyObject.symmetricKeySize);
1973  // Prints: 32 (symmetric key size in bytes)
1974})();
1975```
1976
1977### `keyObject.asymmetricKeyDetails`
1978
1979<!-- YAML
1980added: v15.7.0
1981changes:
1982  - version: v16.9.0
1983    pr-url: https://github.com/nodejs/node/pull/39851
1984    description: Expose `RSASSA-PSS-params` sequence parameters
1985                 for RSA-PSS keys.
1986-->
1987
1988* {Object}
1989  * `modulusLength`: {number} Key size in bits (RSA, DSA).
1990  * `publicExponent`: {bigint} Public exponent (RSA).
1991  * `hashAlgorithm`: {string} Name of the message digest (RSA-PSS).
1992  * `mgf1HashAlgorithm`: {string} Name of the message digest used by
1993    MGF1 (RSA-PSS).
1994  * `saltLength`: {number} Minimal salt length in bytes (RSA-PSS).
1995  * `divisorLength`: {number} Size of `q` in bits (DSA).
1996  * `namedCurve`: {string} Name of the curve (EC).
1997
1998This property exists only on asymmetric keys. Depending on the type of the key,
1999this object contains information about the key. None of the information obtained
2000through this property can be used to uniquely identify a key or to compromise
2001the security of the key.
2002
2003For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence,
2004the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be
2005set.
2006
2007Other key details might be exposed via this API using additional attributes.
2008
2009### `keyObject.asymmetricKeyType`
2010
2011<!-- YAML
2012added: v11.6.0
2013changes:
2014  - version:
2015     - v13.9.0
2016     - v12.17.0
2017    pr-url: https://github.com/nodejs/node/pull/31178
2018    description: Added support for `'dh'`.
2019  - version: v12.0.0
2020    pr-url: https://github.com/nodejs/node/pull/26960
2021    description: Added support for `'rsa-pss'`.
2022  - version: v12.0.0
2023    pr-url: https://github.com/nodejs/node/pull/26786
2024    description: This property now returns `undefined` for KeyObject
2025                 instances of unrecognized type instead of aborting.
2026  - version: v12.0.0
2027    pr-url: https://github.com/nodejs/node/pull/26774
2028    description: Added support for `'x25519'` and `'x448'`.
2029  - version: v12.0.0
2030    pr-url: https://github.com/nodejs/node/pull/26319
2031    description: Added support for `'ed25519'` and `'ed448'`.
2032-->
2033
2034* {string}
2035
2036For asymmetric keys, this property represents the type of the key. Supported key
2037types are:
2038
2039* `'rsa'` (OID 1.2.840.113549.1.1.1)
2040* `'rsa-pss'` (OID 1.2.840.113549.1.1.10)
2041* `'dsa'` (OID 1.2.840.10040.4.1)
2042* `'ec'` (OID 1.2.840.10045.2.1)
2043* `'x25519'` (OID 1.3.101.110)
2044* `'x448'` (OID 1.3.101.111)
2045* `'ed25519'` (OID 1.3.101.112)
2046* `'ed448'` (OID 1.3.101.113)
2047* `'dh'` (OID 1.2.840.113549.1.3.1)
2048
2049This property is `undefined` for unrecognized `KeyObject` types and symmetric
2050keys.
2051
2052### `keyObject.export([options])`
2053
2054<!-- YAML
2055added: v11.6.0
2056changes:
2057  - version: v15.9.0
2058    pr-url: https://github.com/nodejs/node/pull/37081
2059    description: Added support for `'jwk'` format.
2060-->
2061
2062* `options`: {Object}
2063* Returns: {string | Buffer | Object}
2064
2065For symmetric keys, the following encoding options can be used:
2066
2067* `format`: {string} Must be `'buffer'` (default) or `'jwk'`.
2068
2069For public keys, the following encoding options can be used:
2070
2071* `type`: {string} Must be one of `'pkcs1'` (RSA only) or `'spki'`.
2072* `format`: {string} Must be `'pem'`, `'der'`, or `'jwk'`.
2073
2074For private keys, the following encoding options can be used:
2075
2076* `type`: {string} Must be one of `'pkcs1'` (RSA only), `'pkcs8'` or
2077  `'sec1'` (EC only).
2078* `format`: {string} Must be `'pem'`, `'der'`, or `'jwk'`.
2079* `cipher`: {string} If specified, the private key will be encrypted with
2080  the given `cipher` and `passphrase` using PKCS#5 v2.0 password based
2081  encryption.
2082* `passphrase`: {string | Buffer} The passphrase to use for encryption, see
2083  `cipher`.
2084
2085The result type depends on the selected encoding format, when PEM the
2086result is a string, when DER it will be a buffer containing the data
2087encoded as DER, when [JWK][] it will be an object.
2088
2089When [JWK][] encoding format was selected, all other encoding options are
2090ignored.
2091
2092PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of
2093the `cipher` and `format` options. The PKCS#8 `type` can be used with any
2094`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a
2095`cipher`. PKCS#1 and SEC1 can only be encrypted by specifying a `cipher`
2096when the PEM `format` is used. For maximum compatibility, use PKCS#8 for
2097encrypted private keys. Since PKCS#8 defines its own
2098encryption mechanism, PEM-level encryption is not supported when encrypting
2099a PKCS#8 key. See [RFC 5208][] for PKCS#8 encryption and [RFC 1421][] for
2100PKCS#1 and SEC1 encryption.
2101
2102### `keyObject.equals(otherKeyObject)`
2103
2104<!-- YAML
2105added: v17.7.0
2106-->
2107
2108* `otherKeyObject`: {KeyObject} A `KeyObject` with which to
2109  compare `keyObject`.
2110* Returns: {boolean}
2111
2112Returns `true` or `false` depending on whether the keys have exactly the same
2113type, value, and parameters. This method is not
2114[constant time](https://en.wikipedia.org/wiki/Timing_attack).
2115
2116### `keyObject.symmetricKeySize`
2117
2118<!-- YAML
2119added: v11.6.0
2120-->
2121
2122* {number}
2123
2124For secret keys, this property represents the size of the key in bytes. This
2125property is `undefined` for asymmetric keys.
2126
2127### `keyObject.type`
2128
2129<!-- YAML
2130added: v11.6.0
2131-->
2132
2133* {string}
2134
2135Depending on the type of this `KeyObject`, this property is either
2136`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys
2137or `'private'` for private (asymmetric) keys.
2138
2139## Class: `Sign`
2140
2141<!-- YAML
2142added: v0.1.92
2143-->
2144
2145* Extends: {stream.Writable}
2146
2147The `Sign` class is a utility for generating signatures. It can be used in one
2148of two ways:
2149
2150* As a writable [stream][], where data to be signed is written and the
2151  [`sign.sign()`][] method is used to generate and return the signature, or
2152* Using the [`sign.update()`][] and [`sign.sign()`][] methods to produce the
2153  signature.
2154
2155The [`crypto.createSign()`][] method is used to create `Sign` instances. The
2156argument is the string name of the hash function to use. `Sign` objects are not
2157to be created directly using the `new` keyword.
2158
2159Example: Using `Sign` and [`Verify`][] objects as streams:
2160
2161```mjs
2162const {
2163  generateKeyPairSync,
2164  createSign,
2165  createVerify,
2166} = await import('node:crypto');
2167
2168const { privateKey, publicKey } = generateKeyPairSync('ec', {
2169  namedCurve: 'sect239k1',
2170});
2171
2172const sign = createSign('SHA256');
2173sign.write('some data to sign');
2174sign.end();
2175const signature = sign.sign(privateKey, 'hex');
2176
2177const verify = createVerify('SHA256');
2178verify.write('some data to sign');
2179verify.end();
2180console.log(verify.verify(publicKey, signature, 'hex'));
2181// Prints: true
2182```
2183
2184```cjs
2185const {
2186  generateKeyPairSync,
2187  createSign,
2188  createVerify,
2189} = require('node:crypto');
2190
2191const { privateKey, publicKey } = generateKeyPairSync('ec', {
2192  namedCurve: 'sect239k1',
2193});
2194
2195const sign = createSign('SHA256');
2196sign.write('some data to sign');
2197sign.end();
2198const signature = sign.sign(privateKey, 'hex');
2199
2200const verify = createVerify('SHA256');
2201verify.write('some data to sign');
2202verify.end();
2203console.log(verify.verify(publicKey, signature, 'hex'));
2204// Prints: true
2205```
2206
2207Example: Using the [`sign.update()`][] and [`verify.update()`][] methods:
2208
2209```mjs
2210const {
2211  generateKeyPairSync,
2212  createSign,
2213  createVerify,
2214} = await import('node:crypto');
2215
2216const { privateKey, publicKey } = generateKeyPairSync('rsa', {
2217  modulusLength: 2048,
2218});
2219
2220const sign = createSign('SHA256');
2221sign.update('some data to sign');
2222sign.end();
2223const signature = sign.sign(privateKey);
2224
2225const verify = createVerify('SHA256');
2226verify.update('some data to sign');
2227verify.end();
2228console.log(verify.verify(publicKey, signature));
2229// Prints: true
2230```
2231
2232```cjs
2233const {
2234  generateKeyPairSync,
2235  createSign,
2236  createVerify,
2237} = require('node:crypto');
2238
2239const { privateKey, publicKey } = generateKeyPairSync('rsa', {
2240  modulusLength: 2048,
2241});
2242
2243const sign = createSign('SHA256');
2244sign.update('some data to sign');
2245sign.end();
2246const signature = sign.sign(privateKey);
2247
2248const verify = createVerify('SHA256');
2249verify.update('some data to sign');
2250verify.end();
2251console.log(verify.verify(publicKey, signature));
2252// Prints: true
2253```
2254
2255### `sign.sign(privateKey[, outputEncoding])`
2256
2257<!-- YAML
2258added: v0.1.92
2259changes:
2260  - version: v15.0.0
2261    pr-url: https://github.com/nodejs/node/pull/35093
2262    description: The privateKey can also be an ArrayBuffer and CryptoKey.
2263  - version:
2264     - v13.2.0
2265     - v12.16.0
2266    pr-url: https://github.com/nodejs/node/pull/29292
2267    description: This function now supports IEEE-P1363 DSA and ECDSA signatures.
2268  - version: v12.0.0
2269    pr-url: https://github.com/nodejs/node/pull/26960
2270    description: This function now supports RSA-PSS keys.
2271  - version: v11.6.0
2272    pr-url: https://github.com/nodejs/node/pull/24234
2273    description: This function now supports key objects.
2274  - version: v8.0.0
2275    pr-url: https://github.com/nodejs/node/pull/11705
2276    description: Support for RSASSA-PSS and additional options was added.
2277-->
2278
2279<!--lint disable maximum-line-length remark-lint-->
2280
2281* `privateKey` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
2282  * `dsaEncoding` {string}
2283  * `padding` {integer}
2284  * `saltLength` {integer}
2285* `outputEncoding` {string} The [encoding][] of the return value.
2286* Returns: {Buffer | string}
2287
2288<!--lint enable maximum-line-length remark-lint-->
2289
2290Calculates the signature on all the data passed through using either
2291[`sign.update()`][] or [`sign.write()`][stream-writable-write].
2292
2293If `privateKey` is not a [`KeyObject`][], this function behaves as if
2294`privateKey` had been passed to [`crypto.createPrivateKey()`][]. If it is an
2295object, the following additional properties can be passed:
2296
2297* `dsaEncoding` {string} For DSA and ECDSA, this option specifies the
2298  format of the generated signature. It can be one of the following:
2299  * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`.
2300  * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363.
2301* `padding` {integer} Optional padding value for RSA, one of the following:
2302
2303  * `crypto.constants.RSA_PKCS1_PADDING` (default)
2304  * `crypto.constants.RSA_PKCS1_PSS_PADDING`
2305
2306  `RSA_PKCS1_PSS_PADDING` will use MGF1 with the same hash function
2307  used to sign the message as specified in section 3.1 of [RFC 4055][], unless
2308  an MGF1 hash function has been specified as part of the key in compliance with
2309  section 3.3 of [RFC 4055][].
2310* `saltLength` {integer} Salt length for when padding is
2311  `RSA_PKCS1_PSS_PADDING`. The special value
2312  `crypto.constants.RSA_PSS_SALTLEN_DIGEST` sets the salt length to the digest
2313  size, `crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN` (default) sets it to the
2314  maximum permissible value.
2315
2316If `outputEncoding` is provided a string is returned; otherwise a [`Buffer`][]
2317is returned.
2318
2319The `Sign` object can not be again used after `sign.sign()` method has been
2320called. Multiple calls to `sign.sign()` will result in an error being thrown.
2321
2322### `sign.update(data[, inputEncoding])`
2323
2324<!-- YAML
2325added: v0.1.92
2326changes:
2327  - version: v6.0.0
2328    pr-url: https://github.com/nodejs/node/pull/5522
2329    description: The default `inputEncoding` changed from `binary` to `utf8`.
2330-->
2331
2332* `data` {string|Buffer|TypedArray|DataView}
2333* `inputEncoding` {string} The [encoding][] of the `data` string.
2334
2335Updates the `Sign` content with the given `data`, the encoding of which
2336is given in `inputEncoding`.
2337If `encoding` is not provided, and the `data` is a string, an
2338encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or
2339`DataView`, then `inputEncoding` is ignored.
2340
2341This can be called many times with new data as it is streamed.
2342
2343## Class: `Verify`
2344
2345<!-- YAML
2346added: v0.1.92
2347-->
2348
2349* Extends: {stream.Writable}
2350
2351The `Verify` class is a utility for verifying signatures. It can be used in one
2352of two ways:
2353
2354* As a writable [stream][] where written data is used to validate against the
2355  supplied signature, or
2356* Using the [`verify.update()`][] and [`verify.verify()`][] methods to verify
2357  the signature.
2358
2359The [`crypto.createVerify()`][] method is used to create `Verify` instances.
2360`Verify` objects are not to be created directly using the `new` keyword.
2361
2362See [`Sign`][] for examples.
2363
2364### `verify.update(data[, inputEncoding])`
2365
2366<!-- YAML
2367added: v0.1.92
2368changes:
2369  - version: v6.0.0
2370    pr-url: https://github.com/nodejs/node/pull/5522
2371    description: The default `inputEncoding` changed from `binary` to `utf8`.
2372-->
2373
2374* `data` {string|Buffer|TypedArray|DataView}
2375* `inputEncoding` {string} The [encoding][] of the `data` string.
2376
2377Updates the `Verify` content with the given `data`, the encoding of which
2378is given in `inputEncoding`.
2379If `inputEncoding` is not provided, and the `data` is a string, an
2380encoding of `'utf8'` is enforced. If `data` is a [`Buffer`][], `TypedArray`, or
2381`DataView`, then `inputEncoding` is ignored.
2382
2383This can be called many times with new data as it is streamed.
2384
2385### `verify.verify(object, signature[, signatureEncoding])`
2386
2387<!-- YAML
2388added: v0.1.92
2389changes:
2390  - version: v15.0.0
2391    pr-url: https://github.com/nodejs/node/pull/35093
2392    description: The object can also be an ArrayBuffer and CryptoKey.
2393  - version:
2394     - v13.2.0
2395     - v12.16.0
2396    pr-url: https://github.com/nodejs/node/pull/29292
2397    description: This function now supports IEEE-P1363 DSA and ECDSA signatures.
2398  - version: v12.0.0
2399    pr-url: https://github.com/nodejs/node/pull/26960
2400    description: This function now supports RSA-PSS keys.
2401  - version: v11.7.0
2402    pr-url: https://github.com/nodejs/node/pull/25217
2403    description: The key can now be a private key.
2404  - version: v8.0.0
2405    pr-url: https://github.com/nodejs/node/pull/11705
2406    description: Support for RSASSA-PSS and additional options was added.
2407-->
2408
2409<!--lint disable maximum-line-length remark-lint-->
2410
2411* `object` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
2412  * `dsaEncoding` {string}
2413  * `padding` {integer}
2414  * `saltLength` {integer}
2415* `signature` {string|ArrayBuffer|Buffer|TypedArray|DataView}
2416* `signatureEncoding` {string} The [encoding][] of the `signature` string.
2417* Returns: {boolean} `true` or `false` depending on the validity of the
2418  signature for the data and public key.
2419
2420<!--lint enable maximum-line-length remark-lint-->
2421
2422Verifies the provided data using the given `object` and `signature`.
2423
2424If `object` is not a [`KeyObject`][], this function behaves as if
2425`object` had been passed to [`crypto.createPublicKey()`][]. If it is an
2426object, the following additional properties can be passed:
2427
2428* `dsaEncoding` {string} For DSA and ECDSA, this option specifies the
2429  format of the signature. It can be one of the following:
2430  * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`.
2431  * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363.
2432* `padding` {integer} Optional padding value for RSA, one of the following:
2433
2434  * `crypto.constants.RSA_PKCS1_PADDING` (default)
2435  * `crypto.constants.RSA_PKCS1_PSS_PADDING`
2436
2437  `RSA_PKCS1_PSS_PADDING` will use MGF1 with the same hash function
2438  used to verify the message as specified in section 3.1 of [RFC 4055][], unless
2439  an MGF1 hash function has been specified as part of the key in compliance with
2440  section 3.3 of [RFC 4055][].
2441* `saltLength` {integer} Salt length for when padding is
2442  `RSA_PKCS1_PSS_PADDING`. The special value
2443  `crypto.constants.RSA_PSS_SALTLEN_DIGEST` sets the salt length to the digest
2444  size, `crypto.constants.RSA_PSS_SALTLEN_AUTO` (default) causes it to be
2445  determined automatically.
2446
2447The `signature` argument is the previously calculated signature for the data, in
2448the `signatureEncoding`.
2449If a `signatureEncoding` is specified, the `signature` is expected to be a
2450string; otherwise `signature` is expected to be a [`Buffer`][],
2451`TypedArray`, or `DataView`.
2452
2453The `verify` object can not be used again after `verify.verify()` has been
2454called. Multiple calls to `verify.verify()` will result in an error being
2455thrown.
2456
2457Because public keys can be derived from private keys, a private key may
2458be passed instead of a public key.
2459
2460## Class: `X509Certificate`
2461
2462<!-- YAML
2463added: v15.6.0
2464-->
2465
2466Encapsulates an X509 certificate and provides read-only access to
2467its information.
2468
2469```mjs
2470const { X509Certificate } = await import('node:crypto');
2471
2472const x509 = new X509Certificate('{... pem encoded cert ...}');
2473
2474console.log(x509.subject);
2475```
2476
2477```cjs
2478const { X509Certificate } = require('node:crypto');
2479
2480const x509 = new X509Certificate('{... pem encoded cert ...}');
2481
2482console.log(x509.subject);
2483```
2484
2485### `new X509Certificate(buffer)`
2486
2487<!-- YAML
2488added: v15.6.0
2489-->
2490
2491* `buffer` {string|TypedArray|Buffer|DataView} A PEM or DER encoded
2492  X509 Certificate.
2493
2494### `x509.ca`
2495
2496<!-- YAML
2497added: v15.6.0
2498-->
2499
2500* Type: {boolean} Will be `true` if this is a Certificate Authority (CA)
2501  certificate.
2502
2503### `x509.checkEmail(email[, options])`
2504
2505<!-- YAML
2506added: v15.6.0
2507changes:
2508  - version: v18.0.0
2509    pr-url: https://github.com/nodejs/node/pull/41600
2510    description: The subject option now defaults to `'default'`.
2511  - version:
2512      - v17.5.0
2513      - v16.14.1
2514    pr-url: https://github.com/nodejs/node/pull/41599
2515    description: The `wildcards`, `partialWildcards`, `multiLabelWildcards`, and
2516                 `singleLabelSubdomains` options have been removed since they
2517                 had no effect.
2518  - version: v17.5.0
2519    pr-url: https://github.com/nodejs/node/pull/41569
2520    description: The subject option can now be set to `'default'`.
2521-->
2522
2523* `email` {string}
2524* `options` {Object}
2525  * `subject` {string} `'default'`, `'always'`, or `'never'`.
2526    **Default:** `'default'`.
2527* Returns: {string|undefined} Returns `email` if the certificate matches,
2528  `undefined` if it does not.
2529
2530Checks whether the certificate matches the given email address.
2531
2532If the `'subject'` option is undefined or set to `'default'`, the certificate
2533subject is only considered if the subject alternative name extension either does
2534not exist or does not contain any email addresses.
2535
2536If the `'subject'` option is set to `'always'` and if the subject alternative
2537name extension either does not exist or does not contain a matching email
2538address, the certificate subject is considered.
2539
2540If the `'subject'` option is set to `'never'`, the certificate subject is never
2541considered, even if the certificate contains no subject alternative names.
2542
2543### `x509.checkHost(name[, options])`
2544
2545<!-- YAML
2546added: v15.6.0
2547changes:
2548  - version: v18.0.0
2549    pr-url: https://github.com/nodejs/node/pull/41600
2550    description: The subject option now defaults to `'default'`.
2551  - version: v17.5.0
2552    pr-url: https://github.com/nodejs/node/pull/41569
2553    description: The subject option can now be set to `'default'`.
2554-->
2555
2556* `name` {string}
2557* `options` {Object}
2558  * `subject` {string} `'default'`, `'always'`, or `'never'`.
2559    **Default:** `'default'`.
2560  * `wildcards` {boolean} **Default:** `true`.
2561  * `partialWildcards` {boolean} **Default:** `true`.
2562  * `multiLabelWildcards` {boolean} **Default:** `false`.
2563  * `singleLabelSubdomains` {boolean} **Default:** `false`.
2564* Returns: {string|undefined} Returns a subject name that matches `name`,
2565  or `undefined` if no subject name matches `name`.
2566
2567Checks whether the certificate matches the given host name.
2568
2569If the certificate matches the given host name, the matching subject name is
2570returned. The returned name might be an exact match (e.g., `foo.example.com`)
2571or it might contain wildcards (e.g., `*.example.com`). Because host name
2572comparisons are case-insensitive, the returned subject name might also differ
2573from the given `name` in capitalization.
2574
2575If the `'subject'` option is undefined or set to `'default'`, the certificate
2576subject is only considered if the subject alternative name extension either does
2577not exist or does not contain any DNS names. This behavior is consistent with
2578[RFC 2818][] ("HTTP Over TLS").
2579
2580If the `'subject'` option is set to `'always'` and if the subject alternative
2581name extension either does not exist or does not contain a matching DNS name,
2582the certificate subject is considered.
2583
2584If the `'subject'` option is set to `'never'`, the certificate subject is never
2585considered, even if the certificate contains no subject alternative names.
2586
2587### `x509.checkIP(ip)`
2588
2589<!-- YAML
2590added: v15.6.0
2591changes:
2592  - version:
2593      - v17.5.0
2594      - v16.14.1
2595    pr-url: https://github.com/nodejs/node/pull/41571
2596    description: The `options` argument has been removed since it had no effect.
2597-->
2598
2599* `ip` {string}
2600* Returns: {string|undefined} Returns `ip` if the certificate matches,
2601  `undefined` if it does not.
2602
2603Checks whether the certificate matches the given IP address (IPv4 or IPv6).
2604
2605Only [RFC 5280][] `iPAddress` subject alternative names are considered, and they
2606must match the given `ip` address exactly. Other subject alternative names as
2607well as the subject field of the certificate are ignored.
2608
2609### `x509.checkIssued(otherCert)`
2610
2611<!-- YAML
2612added: v15.6.0
2613-->
2614
2615* `otherCert` {X509Certificate}
2616* Returns: {boolean}
2617
2618Checks whether this certificate was issued by the given `otherCert`.
2619
2620### `x509.checkPrivateKey(privateKey)`
2621
2622<!-- YAML
2623added: v15.6.0
2624-->
2625
2626* `privateKey` {KeyObject} A private key.
2627* Returns: {boolean}
2628
2629Checks whether the public key for this certificate is consistent with
2630the given private key.
2631
2632### `x509.fingerprint`
2633
2634<!-- YAML
2635added: v15.6.0
2636-->
2637
2638* Type: {string}
2639
2640The SHA-1 fingerprint of this certificate.
2641
2642Because SHA-1 is cryptographically broken and because the security of SHA-1 is
2643significantly worse than that of algorithms that are commonly used to sign
2644certificates, consider using [`x509.fingerprint256`][] instead.
2645
2646### `x509.fingerprint256`
2647
2648<!-- YAML
2649added: v15.6.0
2650-->
2651
2652* Type: {string}
2653
2654The SHA-256 fingerprint of this certificate.
2655
2656### `x509.fingerprint512`
2657
2658<!-- YAML
2659added:
2660  - v17.2.0
2661  - v16.14.0
2662-->
2663
2664* Type: {string}
2665
2666The SHA-512 fingerprint of this certificate.
2667
2668Because computing the SHA-256 fingerprint is usually faster and because it is
2669only half the size of the SHA-512 fingerprint, [`x509.fingerprint256`][] may be
2670a better choice. While SHA-512 presumably provides a higher level of security in
2671general, the security of SHA-256 matches that of most algorithms that are
2672commonly used to sign certificates.
2673
2674### `x509.infoAccess`
2675
2676<!-- YAML
2677added: v15.6.0
2678changes:
2679  - version:
2680      - v17.3.1
2681      - v16.13.2
2682    pr-url: https://github.com/nodejs-private/node-private/pull/300
2683    description: Parts of this string may be encoded as JSON string literals
2684                 in response to CVE-2021-44532.
2685-->
2686
2687* Type: {string}
2688
2689A textual representation of the certificate's authority information access
2690extension.
2691
2692This is a line feed separated list of access descriptions. Each line begins with
2693the access method and the kind of the access location, followed by a colon and
2694the value associated with the access location.
2695
2696After the prefix denoting the access method and the kind of the access location,
2697the remainder of each line might be enclosed in quotes to indicate that the
2698value is a JSON string literal. For backward compatibility, Node.js only uses
2699JSON string literals within this property when necessary to avoid ambiguity.
2700Third-party code should be prepared to handle both possible entry formats.
2701
2702### `x509.issuer`
2703
2704<!-- YAML
2705added: v15.6.0
2706-->
2707
2708* Type: {string}
2709
2710The issuer identification included in this certificate.
2711
2712### `x509.issuerCertificate`
2713
2714<!-- YAML
2715added: v15.9.0
2716-->
2717
2718* Type: {X509Certificate}
2719
2720The issuer certificate or `undefined` if the issuer certificate is not
2721available.
2722
2723### `x509.keyUsage`
2724
2725<!-- YAML
2726added: v15.6.0
2727-->
2728
2729* Type: {string\[]}
2730
2731An array detailing the key usages for this certificate.
2732
2733### `x509.publicKey`
2734
2735<!-- YAML
2736added: v15.6.0
2737-->
2738
2739* Type: {KeyObject}
2740
2741The public key {KeyObject} for this certificate.
2742
2743### `x509.raw`
2744
2745<!-- YAML
2746added: v15.6.0
2747-->
2748
2749* Type: {Buffer}
2750
2751A `Buffer` containing the DER encoding of this certificate.
2752
2753### `x509.serialNumber`
2754
2755<!-- YAML
2756added: v15.6.0
2757-->
2758
2759* Type: {string}
2760
2761The serial number of this certificate.
2762
2763Serial numbers are assigned by certificate authorities and do not uniquely
2764identify certificates. Consider using [`x509.fingerprint256`][] as a unique
2765identifier instead.
2766
2767### `x509.subject`
2768
2769<!-- YAML
2770added: v15.6.0
2771-->
2772
2773* Type: {string}
2774
2775The complete subject of this certificate.
2776
2777### `x509.subjectAltName`
2778
2779<!-- YAML
2780added: v15.6.0
2781changes:
2782  - version:
2783      - v17.3.1
2784      - v16.13.2
2785    pr-url: https://github.com/nodejs-private/node-private/pull/300
2786    description: Parts of this string may be encoded as JSON string literals
2787                 in response to CVE-2021-44532.
2788-->
2789
2790* Type: {string}
2791
2792The subject alternative name specified for this certificate.
2793
2794This is a comma-separated list of subject alternative names. Each entry begins
2795with a string identifying the kind of the subject alternative name followed by
2796a colon and the value associated with the entry.
2797
2798Earlier versions of Node.js incorrectly assumed that it is safe to split this
2799property at the two-character sequence `', '` (see [CVE-2021-44532][]). However,
2800both malicious and legitimate certificates can contain subject alternative names
2801that include this sequence when represented as a string.
2802
2803After the prefix denoting the type of the entry, the remainder of each entry
2804might be enclosed in quotes to indicate that the value is a JSON string literal.
2805For backward compatibility, Node.js only uses JSON string literals within this
2806property when necessary to avoid ambiguity. Third-party code should be prepared
2807to handle both possible entry formats.
2808
2809### `x509.toJSON()`
2810
2811<!-- YAML
2812added: v15.6.0
2813-->
2814
2815* Type: {string}
2816
2817There is no standard JSON encoding for X509 certificates. The
2818`toJSON()` method returns a string containing the PEM encoded
2819certificate.
2820
2821### `x509.toLegacyObject()`
2822
2823<!-- YAML
2824added: v15.6.0
2825-->
2826
2827* Type: {Object}
2828
2829Returns information about this certificate using the legacy
2830[certificate object][] encoding.
2831
2832### `x509.toString()`
2833
2834<!-- YAML
2835added: v15.6.0
2836-->
2837
2838* Type: {string}
2839
2840Returns the PEM-encoded certificate.
2841
2842### `x509.validFrom`
2843
2844<!-- YAML
2845added: v15.6.0
2846-->
2847
2848* Type: {string}
2849
2850The date/time from which this certificate is considered valid.
2851
2852### `x509.validTo`
2853
2854<!-- YAML
2855added: v15.6.0
2856-->
2857
2858* Type: {string}
2859
2860The date/time until which this certificate is considered valid.
2861
2862### `x509.verify(publicKey)`
2863
2864<!-- YAML
2865added: v15.6.0
2866-->
2867
2868* `publicKey` {KeyObject} A public key.
2869* Returns: {boolean}
2870
2871Verifies that this certificate was signed by the given public key.
2872Does not perform any other validation checks on the certificate.
2873
2874## `node:crypto` module methods and properties
2875
2876### `crypto.constants`
2877
2878<!-- YAML
2879added: v6.3.0
2880-->
2881
2882* {Object}
2883
2884An object containing commonly used constants for crypto and security related
2885operations. The specific constants currently defined are described in
2886[Crypto constants][].
2887
2888### `crypto.DEFAULT_ENCODING`
2889
2890<!-- YAML
2891added: v0.9.3
2892deprecated: v10.0.0
2893-->
2894
2895> Stability: 0 - Deprecated
2896
2897The default encoding to use for functions that can take either strings
2898or [buffers][`Buffer`]. The default value is `'buffer'`, which makes methods
2899default to [`Buffer`][] objects.
2900
2901The `crypto.DEFAULT_ENCODING` mechanism is provided for backward compatibility
2902with legacy programs that expect `'latin1'` to be the default encoding.
2903
2904New applications should expect the default to be `'buffer'`.
2905
2906This property is deprecated.
2907
2908### `crypto.fips`
2909
2910<!-- YAML
2911added: v6.0.0
2912deprecated: v10.0.0
2913-->
2914
2915> Stability: 0 - Deprecated
2916
2917Property for checking and controlling whether a FIPS compliant crypto provider
2918is currently in use. Setting to true requires a FIPS build of Node.js.
2919
2920This property is deprecated. Please use `crypto.setFips()` and
2921`crypto.getFips()` instead.
2922
2923### `crypto.checkPrime(candidate[, options], callback)`
2924
2925<!-- YAML
2926added: v15.8.0
2927changes:
2928  - version: v18.0.0
2929    pr-url: https://github.com/nodejs/node/pull/41678
2930    description: Passing an invalid callback to the `callback` argument
2931                 now throws `ERR_INVALID_ARG_TYPE` instead of
2932                 `ERR_INVALID_CALLBACK`.
2933-->
2934
2935* `candidate` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint}
2936  A possible prime encoded as a sequence of big endian octets of arbitrary
2937  length.
2938* `options` {Object}
2939  * `checks` {number} The number of Miller-Rabin probabilistic primality
2940    iterations to perform. When the value is `0` (zero), a number of checks
2941    is used that yields a false positive rate of at most 2<sup>-64</sup> for
2942    random input. Care must be used when selecting a number of checks. Refer
2943    to the OpenSSL documentation for the [`BN_is_prime_ex`][] function `nchecks`
2944    options for more details. **Default:** `0`
2945* `callback` {Function}
2946  * `err` {Error} Set to an {Error} object if an error occurred during check.
2947  * `result` {boolean} `true` if the candidate is a prime with an error
2948    probability less than `0.25 ** options.checks`.
2949
2950Checks the primality of the `candidate`.
2951
2952### `crypto.checkPrimeSync(candidate[, options])`
2953
2954<!-- YAML
2955added: v15.8.0
2956-->
2957
2958* `candidate` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint}
2959  A possible prime encoded as a sequence of big endian octets of arbitrary
2960  length.
2961* `options` {Object}
2962  * `checks` {number} The number of Miller-Rabin probabilistic primality
2963    iterations to perform. When the value is `0` (zero), a number of checks
2964    is used that yields a false positive rate of at most 2<sup>-64</sup> for
2965    random input. Care must be used when selecting a number of checks. Refer
2966    to the OpenSSL documentation for the [`BN_is_prime_ex`][] function `nchecks`
2967    options for more details. **Default:** `0`
2968* Returns: {boolean} `true` if the candidate is a prime with an error
2969  probability less than `0.25 ** options.checks`.
2970
2971Checks the primality of the `candidate`.
2972
2973### `crypto.createCipher(algorithm, password[, options])`
2974
2975<!-- YAML
2976added: v0.1.94
2977deprecated: v10.0.0
2978changes:
2979  - version: v17.9.0
2980    pr-url: https://github.com/nodejs/node/pull/42427
2981    description: The `authTagLength` option is now optional when using the
2982                 `chacha20-poly1305` cipher and defaults to 16 bytes.
2983  - version: v15.0.0
2984    pr-url: https://github.com/nodejs/node/pull/35093
2985    description: The password argument can be an ArrayBuffer and is limited to
2986                 a maximum of 2 ** 31 - 1 bytes.
2987  - version: v10.10.0
2988    pr-url: https://github.com/nodejs/node/pull/21447
2989    description: Ciphers in OCB mode are now supported.
2990  - version: v10.2.0
2991    pr-url: https://github.com/nodejs/node/pull/20235
2992    description: The `authTagLength` option can now be used to produce shorter
2993                 authentication tags in GCM mode and defaults to 16 bytes.
2994-->
2995
2996> Stability: 0 - Deprecated: Use [`crypto.createCipheriv()`][] instead.
2997
2998* `algorithm` {string}
2999* `password` {string|ArrayBuffer|Buffer|TypedArray|DataView}
3000* `options` {Object} [`stream.transform` options][]
3001* Returns: {Cipher}
3002
3003Creates and returns a `Cipher` object that uses the given `algorithm` and
3004`password`.
3005
3006The `options` argument controls stream behavior and is optional except when a
3007cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the
3008`authTagLength` option is required and specifies the length of the
3009authentication tag in bytes, see [CCM mode][]. In GCM mode, the `authTagLength`
3010option is not required but can be used to set the length of the authentication
3011tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
3012For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
3013
3014The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
3015recent OpenSSL releases, `openssl list -cipher-algorithms` will
3016display the available cipher algorithms.
3017
3018The `password` is used to derive the cipher key and initialization vector (IV).
3019The value must be either a `'latin1'` encoded string, a [`Buffer`][], a
3020`TypedArray`, or a `DataView`.
3021
3022<strong class="critical">This function is semantically insecure for all
3023supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,
3024GCM, or CCM).</strong>
3025
3026The implementation of `crypto.createCipher()` derives keys using the OpenSSL
3027function [`EVP_BytesToKey`][] with the digest algorithm set to MD5, one
3028iteration, and no salt. The lack of salt allows dictionary attacks as the same
3029password always creates the same key. The low iteration count and
3030non-cryptographically secure hash algorithm allow passwords to be tested very
3031rapidly.
3032
3033In line with OpenSSL's recommendation to use a more modern algorithm instead of
3034[`EVP_BytesToKey`][] it is recommended that developers derive a key and IV on
3035their own using [`crypto.scrypt()`][] and to use [`crypto.createCipheriv()`][]
3036to create the `Cipher` object. Users should not use ciphers with counter mode
3037(e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when
3038they are used in order to avoid the risk of IV reuse that causes
3039vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting
3040Adversaries][] for details.
3041
3042### `crypto.createCipheriv(algorithm, key, iv[, options])`
3043
3044<!-- YAML
3045added: v0.1.94
3046changes:
3047  - version: v17.9.0
3048    pr-url: https://github.com/nodejs/node/pull/42427
3049    description: The `authTagLength` option is now optional when using the
3050                 `chacha20-poly1305` cipher and defaults to 16 bytes.
3051  - version: v15.0.0
3052    pr-url: https://github.com/nodejs/node/pull/35093
3053    description: The password and iv arguments can be an ArrayBuffer and are
3054                 each limited to a maximum of 2 ** 31 - 1 bytes.
3055  - version: v11.6.0
3056    pr-url: https://github.com/nodejs/node/pull/24234
3057    description: The `key` argument can now be a `KeyObject`.
3058  - version:
3059     - v11.2.0
3060     - v10.17.0
3061    pr-url: https://github.com/nodejs/node/pull/24081
3062    description: The cipher `chacha20-poly1305` (the IETF variant of
3063                 ChaCha20-Poly1305) is now supported.
3064  - version: v10.10.0
3065    pr-url: https://github.com/nodejs/node/pull/21447
3066    description: Ciphers in OCB mode are now supported.
3067  - version: v10.2.0
3068    pr-url: https://github.com/nodejs/node/pull/20235
3069    description: The `authTagLength` option can now be used to produce shorter
3070                 authentication tags in GCM mode and defaults to 16 bytes.
3071  - version: v9.9.0
3072    pr-url: https://github.com/nodejs/node/pull/18644
3073    description: The `iv` parameter may now be `null` for ciphers which do not
3074                 need an initialization vector.
3075-->
3076
3077* `algorithm` {string}
3078* `key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
3079* `iv` {string|ArrayBuffer|Buffer|TypedArray|DataView|null}
3080* `options` {Object} [`stream.transform` options][]
3081* Returns: {Cipher}
3082
3083Creates and returns a `Cipher` object, with the given `algorithm`, `key` and
3084initialization vector (`iv`).
3085
3086The `options` argument controls stream behavior and is optional except when a
3087cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the
3088`authTagLength` option is required and specifies the length of the
3089authentication tag in bytes, see [CCM mode][]. In GCM mode, the `authTagLength`
3090option is not required but can be used to set the length of the authentication
3091tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
3092For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
3093
3094The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
3095recent OpenSSL releases, `openssl list -cipher-algorithms` will
3096display the available cipher algorithms.
3097
3098The `key` is the raw key used by the `algorithm` and `iv` is an
3099[initialization vector][]. Both arguments must be `'utf8'` encoded strings,
3100[Buffers][`Buffer`], `TypedArray`, or `DataView`s. The `key` may optionally be
3101a [`KeyObject`][] of type `secret`. If the cipher does not need
3102an initialization vector, `iv` may be `null`.
3103
3104When passing strings for `key` or `iv`, please consider
3105[caveats when using strings as inputs to cryptographic APIs][].
3106
3107Initialization vectors should be unpredictable and unique; ideally, they will be
3108cryptographically random. They do not have to be secret: IVs are typically just
3109added to ciphertext messages unencrypted. It may sound contradictory that
3110something has to be unpredictable and unique, but does not have to be secret;
3111remember that an attacker must not be able to predict ahead of time what a
3112given IV will be.
3113
3114### `crypto.createDecipher(algorithm, password[, options])`
3115
3116<!-- YAML
3117added: v0.1.94
3118deprecated: v10.0.0
3119changes:
3120  - version: v17.9.0
3121    pr-url: https://github.com/nodejs/node/pull/42427
3122    description: The `authTagLength` option is now optional when using the
3123                 `chacha20-poly1305` cipher and defaults to 16 bytes.
3124  - version: v10.10.0
3125    pr-url: https://github.com/nodejs/node/pull/21447
3126    description: Ciphers in OCB mode are now supported.
3127-->
3128
3129> Stability: 0 - Deprecated: Use [`crypto.createDecipheriv()`][] instead.
3130
3131* `algorithm` {string}
3132* `password` {string|ArrayBuffer|Buffer|TypedArray|DataView}
3133* `options` {Object} [`stream.transform` options][]
3134* Returns: {Decipher}
3135
3136Creates and returns a `Decipher` object that uses the given `algorithm` and
3137`password` (key).
3138
3139The `options` argument controls stream behavior and is optional except when a
3140cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the
3141`authTagLength` option is required and specifies the length of the
3142authentication tag in bytes, see [CCM mode][].
3143For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
3144
3145<strong class="critical">This function is semantically insecure for all
3146supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,
3147GCM, or CCM).</strong>
3148
3149The implementation of `crypto.createDecipher()` derives keys using the OpenSSL
3150function [`EVP_BytesToKey`][] with the digest algorithm set to MD5, one
3151iteration, and no salt. The lack of salt allows dictionary attacks as the same
3152password always creates the same key. The low iteration count and
3153non-cryptographically secure hash algorithm allow passwords to be tested very
3154rapidly.
3155
3156In line with OpenSSL's recommendation to use a more modern algorithm instead of
3157[`EVP_BytesToKey`][] it is recommended that developers derive a key and IV on
3158their own using [`crypto.scrypt()`][] and to use [`crypto.createDecipheriv()`][]
3159to create the `Decipher` object.
3160
3161### `crypto.createDecipheriv(algorithm, key, iv[, options])`
3162
3163<!-- YAML
3164added: v0.1.94
3165changes:
3166  - version: v17.9.0
3167    pr-url: https://github.com/nodejs/node/pull/42427
3168    description: The `authTagLength` option is now optional when using the
3169                 `chacha20-poly1305` cipher and defaults to 16 bytes.
3170  - version: v11.6.0
3171    pr-url: https://github.com/nodejs/node/pull/24234
3172    description: The `key` argument can now be a `KeyObject`.
3173  - version:
3174     - v11.2.0
3175     - v10.17.0
3176    pr-url: https://github.com/nodejs/node/pull/24081
3177    description: The cipher `chacha20-poly1305` (the IETF variant of
3178                 ChaCha20-Poly1305) is now supported.
3179  - version: v10.10.0
3180    pr-url: https://github.com/nodejs/node/pull/21447
3181    description: Ciphers in OCB mode are now supported.
3182  - version: v10.2.0
3183    pr-url: https://github.com/nodejs/node/pull/20039
3184    description: The `authTagLength` option can now be used to restrict accepted
3185                 GCM authentication tag lengths.
3186  - version: v9.9.0
3187    pr-url: https://github.com/nodejs/node/pull/18644
3188    description: The `iv` parameter may now be `null` for ciphers which do not
3189                 need an initialization vector.
3190-->
3191
3192* `algorithm` {string}
3193* `key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
3194* `iv` {string|ArrayBuffer|Buffer|TypedArray|DataView|null}
3195* `options` {Object} [`stream.transform` options][]
3196* Returns: {Decipher}
3197
3198Creates and returns a `Decipher` object that uses the given `algorithm`, `key`
3199and initialization vector (`iv`).
3200
3201The `options` argument controls stream behavior and is optional except when a
3202cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the
3203`authTagLength` option is required and specifies the length of the
3204authentication tag in bytes, see [CCM mode][]. In GCM mode, the `authTagLength`
3205option is not required but can be used to restrict accepted authentication tags
3206to those with the specified length.
3207For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
3208
3209The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
3210recent OpenSSL releases, `openssl list -cipher-algorithms` will
3211display the available cipher algorithms.
3212
3213The `key` is the raw key used by the `algorithm` and `iv` is an
3214[initialization vector][]. Both arguments must be `'utf8'` encoded strings,
3215[Buffers][`Buffer`], `TypedArray`, or `DataView`s. The `key` may optionally be
3216a [`KeyObject`][] of type `secret`. If the cipher does not need
3217an initialization vector, `iv` may be `null`.
3218
3219When passing strings for `key` or `iv`, please consider
3220[caveats when using strings as inputs to cryptographic APIs][].
3221
3222Initialization vectors should be unpredictable and unique; ideally, they will be
3223cryptographically random. They do not have to be secret: IVs are typically just
3224added to ciphertext messages unencrypted. It may sound contradictory that
3225something has to be unpredictable and unique, but does not have to be secret;
3226remember that an attacker must not be able to predict ahead of time what a given
3227IV will be.
3228
3229### `crypto.createDiffieHellman(prime[, primeEncoding][, generator][, generatorEncoding])`
3230
3231<!-- YAML
3232added: v0.11.12
3233changes:
3234  - version: v8.0.0
3235    pr-url: https://github.com/nodejs/node/pull/12223
3236    description: The `prime` argument can be any `TypedArray` or `DataView` now.
3237  - version: v8.0.0
3238    pr-url: https://github.com/nodejs/node/pull/11983
3239    description: The `prime` argument can be a `Uint8Array` now.
3240  - version: v6.0.0
3241    pr-url: https://github.com/nodejs/node/pull/5522
3242    description: The default for the encoding parameters changed
3243                 from `binary` to `utf8`.
3244-->
3245
3246* `prime` {string|ArrayBuffer|Buffer|TypedArray|DataView}
3247* `primeEncoding` {string} The [encoding][] of the `prime` string.
3248* `generator` {number|string|ArrayBuffer|Buffer|TypedArray|DataView}
3249  **Default:** `2`
3250* `generatorEncoding` {string} The [encoding][] of the `generator` string.
3251* Returns: {DiffieHellman}
3252
3253Creates a `DiffieHellman` key exchange object using the supplied `prime` and an
3254optional specific `generator`.
3255
3256The `generator` argument can be a number, string, or [`Buffer`][]. If
3257`generator` is not specified, the value `2` is used.
3258
3259If `primeEncoding` is specified, `prime` is expected to be a string; otherwise
3260a [`Buffer`][], `TypedArray`, or `DataView` is expected.
3261
3262If `generatorEncoding` is specified, `generator` is expected to be a string;
3263otherwise a number, [`Buffer`][], `TypedArray`, or `DataView` is expected.
3264
3265### `crypto.createDiffieHellman(primeLength[, generator])`
3266
3267<!-- YAML
3268added: v0.5.0
3269-->
3270
3271* `primeLength` {number}
3272* `generator` {number} **Default:** `2`
3273* Returns: {DiffieHellman}
3274
3275Creates a `DiffieHellman` key exchange object and generates a prime of
3276`primeLength` bits using an optional specific numeric `generator`.
3277If `generator` is not specified, the value `2` is used.
3278
3279### `crypto.createDiffieHellmanGroup(name)`
3280
3281<!-- YAML
3282added: v0.9.3
3283-->
3284
3285* `name` {string}
3286* Returns: {DiffieHellmanGroup}
3287
3288An alias for [`crypto.getDiffieHellman()`][]
3289
3290### `crypto.createECDH(curveName)`
3291
3292<!-- YAML
3293added: v0.11.14
3294-->
3295
3296* `curveName` {string}
3297* Returns: {ECDH}
3298
3299Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a
3300predefined curve specified by the `curveName` string. Use
3301[`crypto.getCurves()`][] to obtain a list of available curve names. On recent
3302OpenSSL releases, `openssl ecparam -list_curves` will also display the name
3303and description of each available elliptic curve.
3304
3305### `crypto.createHash(algorithm[, options])`
3306
3307<!-- YAML
3308added: v0.1.92
3309changes:
3310  - version: v12.8.0
3311    pr-url: https://github.com/nodejs/node/pull/28805
3312    description: The `outputLength` option was added for XOF hash functions.
3313-->
3314
3315* `algorithm` {string}
3316* `options` {Object} [`stream.transform` options][]
3317* Returns: {Hash}
3318
3319Creates and returns a `Hash` object that can be used to generate hash digests
3320using the given `algorithm`. Optional `options` argument controls stream
3321behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option
3322can be used to specify the desired output length in bytes.
3323
3324The `algorithm` is dependent on the available algorithms supported by the
3325version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
3326On recent releases of OpenSSL, `openssl list -digest-algorithms` will
3327display the available digest algorithms.
3328
3329Example: generating the sha256 sum of a file
3330
3331```mjs
3332import {
3333  createReadStream,
3334} from 'node:fs';
3335import { argv } from 'node:process';
3336const {
3337  createHash,
3338} = await import('node:crypto');
3339
3340const filename = argv[2];
3341
3342const hash = createHash('sha256');
3343
3344const input = createReadStream(filename);
3345input.on('readable', () => {
3346  // Only one element is going to be produced by the
3347  // hash stream.
3348  const data = input.read();
3349  if (data)
3350    hash.update(data);
3351  else {
3352    console.log(`${hash.digest('hex')} ${filename}`);
3353  }
3354});
3355```
3356
3357```cjs
3358const {
3359  createReadStream,
3360} = require('node:fs');
3361const {
3362  createHash,
3363} = require('node:crypto');
3364const { argv } = require('node:process');
3365
3366const filename = argv[2];
3367
3368const hash = createHash('sha256');
3369
3370const input = createReadStream(filename);
3371input.on('readable', () => {
3372  // Only one element is going to be produced by the
3373  // hash stream.
3374  const data = input.read();
3375  if (data)
3376    hash.update(data);
3377  else {
3378    console.log(`${hash.digest('hex')} ${filename}`);
3379  }
3380});
3381```
3382
3383### `crypto.createHmac(algorithm, key[, options])`
3384
3385<!-- YAML
3386added: v0.1.94
3387changes:
3388  - version: v15.0.0
3389    pr-url: https://github.com/nodejs/node/pull/35093
3390    description: The key can also be an ArrayBuffer or CryptoKey. The
3391                 encoding option was added. The key cannot contain
3392                 more than 2 ** 32 - 1 bytes.
3393  - version: v11.6.0
3394    pr-url: https://github.com/nodejs/node/pull/24234
3395    description: The `key` argument can now be a `KeyObject`.
3396-->
3397
3398* `algorithm` {string}
3399* `key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
3400* `options` {Object} [`stream.transform` options][]
3401  * `encoding` {string} The string encoding to use when `key` is a string.
3402* Returns: {Hmac}
3403
3404Creates and returns an `Hmac` object that uses the given `algorithm` and `key`.
3405Optional `options` argument controls stream behavior.
3406
3407The `algorithm` is dependent on the available algorithms supported by the
3408version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
3409On recent releases of OpenSSL, `openssl list -digest-algorithms` will
3410display the available digest algorithms.
3411
3412The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is
3413a [`KeyObject`][], its type must be `secret`. If it is a string, please consider
3414[caveats when using strings as inputs to cryptographic APIs][]. If it was
3415obtained from a cryptographically secure source of entropy, such as
3416[`crypto.randomBytes()`][] or [`crypto.generateKey()`][], its length should not
3417exceed the block size of `algorithm` (e.g., 512 bits for SHA-256).
3418
3419Example: generating the sha256 HMAC of a file
3420
3421```mjs
3422import {
3423  createReadStream,
3424} from 'node:fs';
3425import { argv } from 'node:process';
3426const {
3427  createHmac,
3428} = await import('node:crypto');
3429
3430const filename = argv[2];
3431
3432const hmac = createHmac('sha256', 'a secret');
3433
3434const input = createReadStream(filename);
3435input.on('readable', () => {
3436  // Only one element is going to be produced by the
3437  // hash stream.
3438  const data = input.read();
3439  if (data)
3440    hmac.update(data);
3441  else {
3442    console.log(`${hmac.digest('hex')} ${filename}`);
3443  }
3444});
3445```
3446
3447```cjs
3448const {
3449  createReadStream,
3450} = require('node:fs');
3451const {
3452  createHmac,
3453} = require('node:crypto');
3454const { argv } = require('node:process');
3455
3456const filename = argv[2];
3457
3458const hmac = createHmac('sha256', 'a secret');
3459
3460const input = createReadStream(filename);
3461input.on('readable', () => {
3462  // Only one element is going to be produced by the
3463  // hash stream.
3464  const data = input.read();
3465  if (data)
3466    hmac.update(data);
3467  else {
3468    console.log(`${hmac.digest('hex')} ${filename}`);
3469  }
3470});
3471```
3472
3473### `crypto.createPrivateKey(key)`
3474
3475<!-- YAML
3476added: v11.6.0
3477changes:
3478  - version: v15.12.0
3479    pr-url: https://github.com/nodejs/node/pull/37254
3480    description: The key can also be a JWK object.
3481  - version: v15.0.0
3482    pr-url: https://github.com/nodejs/node/pull/35093
3483    description: The key can also be an ArrayBuffer. The encoding option was
3484                 added. The key cannot contain more than 2 ** 32 - 1 bytes.
3485-->
3486
3487<!--lint disable maximum-line-length remark-lint-->
3488
3489* `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView}
3490  * `key`: {string|ArrayBuffer|Buffer|TypedArray|DataView|Object} The key
3491    material, either in PEM, DER, or JWK format.
3492  * `format`: {string} Must be `'pem'`, `'der'`, or '`'jwk'`.
3493    **Default:** `'pem'`.
3494  * `type`: {string} Must be `'pkcs1'`, `'pkcs8'` or `'sec1'`. This option is
3495    required only if the `format` is `'der'` and ignored otherwise.
3496  * `passphrase`: {string | Buffer} The passphrase to use for decryption.
3497  * `encoding`: {string} The string encoding to use when `key` is a string.
3498* Returns: {KeyObject}
3499
3500<!--lint enable maximum-line-length remark-lint-->
3501
3502Creates and returns a new key object containing a private key. If `key` is a
3503string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`
3504must be an object with the properties described above.
3505
3506If the private key is encrypted, a `passphrase` must be specified. The length
3507of the passphrase is limited to 1024 bytes.
3508
3509### `crypto.createPublicKey(key)`
3510
3511<!-- YAML
3512added: v11.6.0
3513changes:
3514  - version: v15.12.0
3515    pr-url: https://github.com/nodejs/node/pull/37254
3516    description: The key can also be a JWK object.
3517  - version: v15.0.0
3518    pr-url: https://github.com/nodejs/node/pull/35093
3519    description: The key can also be an ArrayBuffer. The encoding option was
3520                 added. The key cannot contain more than 2 ** 32 - 1 bytes.
3521  - version: v11.13.0
3522    pr-url: https://github.com/nodejs/node/pull/26278
3523    description: The `key` argument can now be a `KeyObject` with type
3524                 `private`.
3525  - version: v11.7.0
3526    pr-url: https://github.com/nodejs/node/pull/25217
3527    description: The `key` argument can now be a private key.
3528-->
3529
3530<!--lint disable maximum-line-length remark-lint-->
3531
3532* `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView}
3533  * `key`: {string|ArrayBuffer|Buffer|TypedArray|DataView|Object} The key
3534    material, either in PEM, DER, or JWK format.
3535  * `format`: {string} Must be `'pem'`, `'der'`, or `'jwk'`.
3536    **Default:** `'pem'`.
3537  * `type`: {string} Must be `'pkcs1'` or `'spki'`. This option is
3538    required only if the `format` is `'der'` and ignored otherwise.
3539  * `encoding` {string} The string encoding to use when `key` is a string.
3540* Returns: {KeyObject}
3541
3542<!--lint enable maximum-line-length remark-lint-->
3543
3544Creates and returns a new key object containing a public key. If `key` is a
3545string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`
3546with type `'private'`, the public key is derived from the given private key;
3547otherwise, `key` must be an object with the properties described above.
3548
3549If the format is `'pem'`, the `'key'` may also be an X.509 certificate.
3550
3551Because public keys can be derived from private keys, a private key may be
3552passed instead of a public key. In that case, this function behaves as if
3553[`crypto.createPrivateKey()`][] had been called, except that the type of the
3554returned `KeyObject` will be `'public'` and that the private key cannot be
3555extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type
3556`'private'` is given, a new `KeyObject` with type `'public'` will be returned
3557and it will be impossible to extract the private key from the returned object.
3558
3559### `crypto.createSecretKey(key[, encoding])`
3560
3561<!-- YAML
3562added: v11.6.0
3563changes:
3564  - version: v18.8.0
3565    pr-url: https://github.com/nodejs/node/pull/44201
3566    description: The key can now be zero-length.
3567  - version: v15.0.0
3568    pr-url: https://github.com/nodejs/node/pull/35093
3569    description: The key can also be an ArrayBuffer or string. The encoding
3570                 argument was added. The key cannot contain more than
3571                 2 ** 32 - 1 bytes.
3572-->
3573
3574* `key` {string|ArrayBuffer|Buffer|TypedArray|DataView}
3575* `encoding` {string} The string encoding when `key` is a string.
3576* Returns: {KeyObject}
3577
3578Creates and returns a new key object containing a secret key for symmetric
3579encryption or `Hmac`.
3580
3581### `crypto.createSign(algorithm[, options])`
3582
3583<!-- YAML
3584added: v0.1.92
3585-->
3586
3587* `algorithm` {string}
3588* `options` {Object} [`stream.Writable` options][]
3589* Returns: {Sign}
3590
3591Creates and returns a `Sign` object that uses the given `algorithm`. Use
3592[`crypto.getHashes()`][] to obtain the names of the available digest algorithms.
3593Optional `options` argument controls the `stream.Writable` behavior.
3594
3595In some cases, a `Sign` instance can be created using the name of a signature
3596algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
3597the corresponding digest algorithm. This does not work for all signature
3598algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
3599algorithm names.
3600
3601### `crypto.createVerify(algorithm[, options])`
3602
3603<!-- YAML
3604added: v0.1.92
3605-->
3606
3607* `algorithm` {string}
3608* `options` {Object} [`stream.Writable` options][]
3609* Returns: {Verify}
3610
3611Creates and returns a `Verify` object that uses the given algorithm.
3612Use [`crypto.getHashes()`][] to obtain an array of names of the available
3613signing algorithms. Optional `options` argument controls the
3614`stream.Writable` behavior.
3615
3616In some cases, a `Verify` instance can be created using the name of a signature
3617algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
3618the corresponding digest algorithm. This does not work for all signature
3619algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
3620algorithm names.
3621
3622### `crypto.diffieHellman(options)`
3623
3624<!-- YAML
3625added:
3626 - v13.9.0
3627 - v12.17.0
3628-->
3629
3630* `options`: {Object}
3631  * `privateKey`: {KeyObject}
3632  * `publicKey`: {KeyObject}
3633* Returns: {Buffer}
3634
3635Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`.
3636Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`
3637(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES).
3638
3639### `crypto.generateKey(type, options, callback)`
3640
3641<!-- YAML
3642added: v15.0.0
3643changes:
3644  - version: v18.0.0
3645    pr-url: https://github.com/nodejs/node/pull/41678
3646    description: Passing an invalid callback to the `callback` argument
3647                 now throws `ERR_INVALID_ARG_TYPE` instead of
3648                 `ERR_INVALID_CALLBACK`.
3649-->
3650
3651* `type`: {string} The intended use of the generated secret key. Currently
3652  accepted values are `'hmac'` and `'aes'`.
3653* `options`: {Object}
3654  * `length`: {number} The bit length of the key to generate. This must be a
3655    value greater than 0.
3656    * If `type` is `'hmac'`, the minimum is 8, and the maximum length is
3657      2<sup>31</sup>-1. If the value is not a multiple of 8, the generated
3658      key will be truncated to `Math.floor(length / 8)`.
3659    * If `type` is `'aes'`, the length must be one of `128`, `192`, or `256`.
3660* `callback`: {Function}
3661  * `err`: {Error}
3662  * `key`: {KeyObject}
3663
3664Asynchronously generates a new random secret key of the given `length`. The
3665`type` will determine which validations will be performed on the `length`.
3666
3667```mjs
3668const {
3669  generateKey,
3670} = await import('node:crypto');
3671
3672generateKey('hmac', { length: 512 }, (err, key) => {
3673  if (err) throw err;
3674  console.log(key.export().toString('hex'));  // 46e..........620
3675});
3676```
3677
3678```cjs
3679const {
3680  generateKey,
3681} = require('node:crypto');
3682
3683generateKey('hmac', { length: 512 }, (err, key) => {
3684  if (err) throw err;
3685  console.log(key.export().toString('hex'));  // 46e..........620
3686});
3687```
3688
3689The size of a generated HMAC key should not exceed the block size of the
3690underlying hash function. See [`crypto.createHmac()`][] for more information.
3691
3692### `crypto.generateKeyPair(type, options, callback)`
3693
3694<!-- YAML
3695added: v10.12.0
3696changes:
3697  - version: v18.0.0
3698    pr-url: https://github.com/nodejs/node/pull/41678
3699    description: Passing an invalid callback to the `callback` argument
3700                 now throws `ERR_INVALID_ARG_TYPE` instead of
3701                 `ERR_INVALID_CALLBACK`.
3702  - version: v16.10.0
3703    pr-url: https://github.com/nodejs/node/pull/39927
3704    description: Add ability to define `RSASSA-PSS-params` sequence parameters
3705                 for RSA-PSS keys pairs.
3706  - version:
3707     - v13.9.0
3708     - v12.17.0
3709    pr-url: https://github.com/nodejs/node/pull/31178
3710    description: Add support for Diffie-Hellman.
3711  - version: v12.0.0
3712    pr-url: https://github.com/nodejs/node/pull/26960
3713    description: Add support for RSA-PSS key pairs.
3714  - version: v12.0.0
3715    pr-url: https://github.com/nodejs/node/pull/26774
3716    description: Add ability to generate X25519 and X448 key pairs.
3717  - version: v12.0.0
3718    pr-url: https://github.com/nodejs/node/pull/26554
3719    description: Add ability to generate Ed25519 and Ed448 key pairs.
3720  - version: v11.6.0
3721    pr-url: https://github.com/nodejs/node/pull/24234
3722    description: The `generateKeyPair` and `generateKeyPairSync` functions now
3723                 produce key objects if no encoding was specified.
3724-->
3725
3726* `type`: {string} Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`,
3727  `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.
3728* `options`: {Object}
3729  * `modulusLength`: {number} Key size in bits (RSA, DSA).
3730  * `publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.
3731  * `hashAlgorithm`: {string} Name of the message digest (RSA-PSS).
3732  * `mgf1HashAlgorithm`: {string} Name of the message digest used by
3733    MGF1 (RSA-PSS).
3734  * `saltLength`: {number} Minimal salt length in bytes (RSA-PSS).
3735  * `divisorLength`: {number} Size of `q` in bits (DSA).
3736  * `namedCurve`: {string} Name of the curve to use (EC).
3737  * `prime`: {Buffer} The prime parameter (DH).
3738  * `primeLength`: {number} Prime length in bits (DH).
3739  * `generator`: {number} Custom generator (DH). **Default:** `2`.
3740  * `groupName`: {string} Diffie-Hellman group name (DH). See
3741    [`crypto.getDiffieHellman()`][].
3742  * `paramEncoding`: {string} Must be `'named'` or `'explicit'` (EC).
3743    **Default:** `'named'`.
3744  * `publicKeyEncoding`: {Object} See [`keyObject.export()`][].
3745  * `privateKeyEncoding`: {Object} See [`keyObject.export()`][].
3746* `callback`: {Function}
3747  * `err`: {Error}
3748  * `publicKey`: {string | Buffer | KeyObject}
3749  * `privateKey`: {string | Buffer | KeyObject}
3750
3751Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC,
3752Ed25519, Ed448, X25519, X448, and DH are currently supported.
3753
3754If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
3755behaves as if [`keyObject.export()`][] had been called on its result. Otherwise,
3756the respective part of the key is returned as a [`KeyObject`][].
3757
3758It is recommended to encode public keys as `'spki'` and private keys as
3759`'pkcs8'` with encryption for long-term storage:
3760
3761```mjs
3762const {
3763  generateKeyPair,
3764} = await import('node:crypto');
3765
3766generateKeyPair('rsa', {
3767  modulusLength: 4096,
3768  publicKeyEncoding: {
3769    type: 'spki',
3770    format: 'pem',
3771  },
3772  privateKeyEncoding: {
3773    type: 'pkcs8',
3774    format: 'pem',
3775    cipher: 'aes-256-cbc',
3776    passphrase: 'top secret',
3777  },
3778}, (err, publicKey, privateKey) => {
3779  // Handle errors and use the generated key pair.
3780});
3781```
3782
3783```cjs
3784const {
3785  generateKeyPair,
3786} = require('node:crypto');
3787
3788generateKeyPair('rsa', {
3789  modulusLength: 4096,
3790  publicKeyEncoding: {
3791    type: 'spki',
3792    format: 'pem',
3793  },
3794  privateKeyEncoding: {
3795    type: 'pkcs8',
3796    format: 'pem',
3797    cipher: 'aes-256-cbc',
3798    passphrase: 'top secret',
3799  },
3800}, (err, publicKey, privateKey) => {
3801  // Handle errors and use the generated key pair.
3802});
3803```
3804
3805On completion, `callback` will be called with `err` set to `undefined` and
3806`publicKey` / `privateKey` representing the generated key pair.
3807
3808If this method is invoked as its [`util.promisify()`][]ed version, it returns
3809a `Promise` for an `Object` with `publicKey` and `privateKey` properties.
3810
3811### `crypto.generateKeyPairSync(type, options)`
3812
3813<!-- YAML
3814added: v10.12.0
3815changes:
3816  - version: v16.10.0
3817    pr-url: https://github.com/nodejs/node/pull/39927
3818    description: Add ability to define `RSASSA-PSS-params` sequence parameters
3819                 for RSA-PSS keys pairs.
3820  - version:
3821     - v13.9.0
3822     - v12.17.0
3823    pr-url: https://github.com/nodejs/node/pull/31178
3824    description: Add support for Diffie-Hellman.
3825  - version: v12.0.0
3826    pr-url: https://github.com/nodejs/node/pull/26960
3827    description: Add support for RSA-PSS key pairs.
3828  - version: v12.0.0
3829    pr-url: https://github.com/nodejs/node/pull/26774
3830    description: Add ability to generate X25519 and X448 key pairs.
3831  - version: v12.0.0
3832    pr-url: https://github.com/nodejs/node/pull/26554
3833    description: Add ability to generate Ed25519 and Ed448 key pairs.
3834  - version: v11.6.0
3835    pr-url: https://github.com/nodejs/node/pull/24234
3836    description: The `generateKeyPair` and `generateKeyPairSync` functions now
3837                 produce key objects if no encoding was specified.
3838-->
3839
3840* `type`: {string} Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`,
3841  `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.
3842* `options`: {Object}
3843  * `modulusLength`: {number} Key size in bits (RSA, DSA).
3844  * `publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.
3845  * `hashAlgorithm`: {string} Name of the message digest (RSA-PSS).
3846  * `mgf1HashAlgorithm`: {string} Name of the message digest used by
3847    MGF1 (RSA-PSS).
3848  * `saltLength`: {number} Minimal salt length in bytes (RSA-PSS).
3849  * `divisorLength`: {number} Size of `q` in bits (DSA).
3850  * `namedCurve`: {string} Name of the curve to use (EC).
3851  * `prime`: {Buffer} The prime parameter (DH).
3852  * `primeLength`: {number} Prime length in bits (DH).
3853  * `generator`: {number} Custom generator (DH). **Default:** `2`.
3854  * `groupName`: {string} Diffie-Hellman group name (DH). See
3855    [`crypto.getDiffieHellman()`][].
3856  * `paramEncoding`: {string} Must be `'named'` or `'explicit'` (EC).
3857    **Default:** `'named'`.
3858  * `publicKeyEncoding`: {Object} See [`keyObject.export()`][].
3859  * `privateKeyEncoding`: {Object} See [`keyObject.export()`][].
3860* Returns: {Object}
3861  * `publicKey`: {string | Buffer | KeyObject}
3862  * `privateKey`: {string | Buffer | KeyObject}
3863
3864Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC,
3865Ed25519, Ed448, X25519, X448, and DH are currently supported.
3866
3867If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
3868behaves as if [`keyObject.export()`][] had been called on its result. Otherwise,
3869the respective part of the key is returned as a [`KeyObject`][].
3870
3871When encoding public keys, it is recommended to use `'spki'`. When encoding
3872private keys, it is recommended to use `'pkcs8'` with a strong passphrase,
3873and to keep the passphrase confidential.
3874
3875```mjs
3876const {
3877  generateKeyPairSync,
3878} = await import('node:crypto');
3879
3880const {
3881  publicKey,
3882  privateKey,
3883} = generateKeyPairSync('rsa', {
3884  modulusLength: 4096,
3885  publicKeyEncoding: {
3886    type: 'spki',
3887    format: 'pem',
3888  },
3889  privateKeyEncoding: {
3890    type: 'pkcs8',
3891    format: 'pem',
3892    cipher: 'aes-256-cbc',
3893    passphrase: 'top secret',
3894  },
3895});
3896```
3897
3898```cjs
3899const {
3900  generateKeyPairSync,
3901} = require('node:crypto');
3902
3903const {
3904  publicKey,
3905  privateKey,
3906} = generateKeyPairSync('rsa', {
3907  modulusLength: 4096,
3908  publicKeyEncoding: {
3909    type: 'spki',
3910    format: 'pem',
3911  },
3912  privateKeyEncoding: {
3913    type: 'pkcs8',
3914    format: 'pem',
3915    cipher: 'aes-256-cbc',
3916    passphrase: 'top secret',
3917  },
3918});
3919```
3920
3921The return value `{ publicKey, privateKey }` represents the generated key pair.
3922When PEM encoding was selected, the respective key will be a string, otherwise
3923it will be a buffer containing the data encoded as DER.
3924
3925### `crypto.generateKeySync(type, options)`
3926
3927<!-- YAML
3928added: v15.0.0
3929-->
3930
3931* `type`: {string} The intended use of the generated secret key. Currently
3932  accepted values are `'hmac'` and `'aes'`.
3933* `options`: {Object}
3934  * `length`: {number} The bit length of the key to generate.
3935    * If `type` is `'hmac'`, the minimum is 8, and the maximum length is
3936      2<sup>31</sup>-1. If the value is not a multiple of 8, the generated
3937      key will be truncated to `Math.floor(length / 8)`.
3938    * If `type` is `'aes'`, the length must be one of `128`, `192`, or `256`.
3939* Returns: {KeyObject}
3940
3941Synchronously generates a new random secret key of the given `length`. The
3942`type` will determine which validations will be performed on the `length`.
3943
3944```mjs
3945const {
3946  generateKeySync,
3947} = await import('node:crypto');
3948
3949const key = generateKeySync('hmac', { length: 512 });
3950console.log(key.export().toString('hex'));  // e89..........41e
3951```
3952
3953```cjs
3954const {
3955  generateKeySync,
3956} = require('node:crypto');
3957
3958const key = generateKeySync('hmac', { length: 512 });
3959console.log(key.export().toString('hex'));  // e89..........41e
3960```
3961
3962The size of a generated HMAC key should not exceed the block size of the
3963underlying hash function. See [`crypto.createHmac()`][] for more information.
3964
3965### `crypto.generatePrime(size[, options[, callback]])`
3966
3967<!-- YAML
3968added: v15.8.0
3969changes:
3970  - version: v18.0.0
3971    pr-url: https://github.com/nodejs/node/pull/41678
3972    description: Passing an invalid callback to the `callback` argument
3973                 now throws `ERR_INVALID_ARG_TYPE` instead of
3974                 `ERR_INVALID_CALLBACK`.
3975-->
3976
3977* `size` {number} The size (in bits) of the prime to generate.
3978* `options` {Object}
3979  * `add` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint}
3980  * `rem` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint}
3981  * `safe` {boolean} **Default:** `false`.
3982  * `bigint` {boolean} When `true`, the generated prime is returned
3983    as a `bigint`.
3984* `callback` {Function}
3985  * `err` {Error}
3986  * `prime` {ArrayBuffer|bigint}
3987
3988Generates a pseudorandom prime of `size` bits.
3989
3990If `options.safe` is `true`, the prime will be a safe prime -- that is,
3991`(prime - 1) / 2` will also be a prime.
3992
3993The `options.add` and `options.rem` parameters can be used to enforce additional
3994requirements, e.g., for Diffie-Hellman:
3995
3996* If `options.add` and `options.rem` are both set, the prime will satisfy the
3997  condition that `prime % add = rem`.
3998* If only `options.add` is set and `options.safe` is not `true`, the prime will
3999  satisfy the condition that `prime % add = 1`.
4000* If only `options.add` is set and `options.safe` is set to `true`, the prime
4001  will instead satisfy the condition that `prime % add = 3`. This is necessary
4002  because `prime % add = 1` for `options.add > 2` would contradict the condition
4003  enforced by `options.safe`.
4004* `options.rem` is ignored if `options.add` is not given.
4005
4006Both `options.add` and `options.rem` must be encoded as big-endian sequences
4007if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or
4008`DataView`.
4009
4010By default, the prime is encoded as a big-endian sequence of octets
4011in an {ArrayBuffer}. If the `bigint` option is `true`, then a {bigint}
4012is provided.
4013
4014### `crypto.generatePrimeSync(size[, options])`
4015
4016<!-- YAML
4017added: v15.8.0
4018-->
4019
4020* `size` {number} The size (in bits) of the prime to generate.
4021* `options` {Object}
4022  * `add` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint}
4023  * `rem` {ArrayBuffer|SharedArrayBuffer|TypedArray|Buffer|DataView|bigint}
4024  * `safe` {boolean} **Default:** `false`.
4025  * `bigint` {boolean} When `true`, the generated prime is returned
4026    as a `bigint`.
4027* Returns: {ArrayBuffer|bigint}
4028
4029Generates a pseudorandom prime of `size` bits.
4030
4031If `options.safe` is `true`, the prime will be a safe prime -- that is,
4032`(prime - 1) / 2` will also be a prime.
4033
4034The `options.add` and `options.rem` parameters can be used to enforce additional
4035requirements, e.g., for Diffie-Hellman:
4036
4037* If `options.add` and `options.rem` are both set, the prime will satisfy the
4038  condition that `prime % add = rem`.
4039* If only `options.add` is set and `options.safe` is not `true`, the prime will
4040  satisfy the condition that `prime % add = 1`.
4041* If only `options.add` is set and `options.safe` is set to `true`, the prime
4042  will instead satisfy the condition that `prime % add = 3`. This is necessary
4043  because `prime % add = 1` for `options.add > 2` would contradict the condition
4044  enforced by `options.safe`.
4045* `options.rem` is ignored if `options.add` is not given.
4046
4047Both `options.add` and `options.rem` must be encoded as big-endian sequences
4048if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or
4049`DataView`.
4050
4051By default, the prime is encoded as a big-endian sequence of octets
4052in an {ArrayBuffer}. If the `bigint` option is `true`, then a {bigint}
4053is provided.
4054
4055### `crypto.getCipherInfo(nameOrNid[, options])`
4056
4057<!-- YAML
4058added: v15.0.0
4059-->
4060
4061* `nameOrNid`: {string|number} The name or nid of the cipher to query.
4062* `options`: {Object}
4063  * `keyLength`: {number} A test key length.
4064  * `ivLength`: {number} A test IV length.
4065* Returns: {Object}
4066  * `name` {string} The name of the cipher
4067  * `nid` {number} The nid of the cipher
4068  * `blockSize` {number} The block size of the cipher in bytes. This property
4069    is omitted when `mode` is `'stream'`.
4070  * `ivLength` {number} The expected or default initialization vector length in
4071    bytes. This property is omitted if the cipher does not use an initialization
4072    vector.
4073  * `keyLength` {number} The expected or default key length in bytes.
4074  * `mode` {string} The cipher mode. One of `'cbc'`, `'ccm'`, `'cfb'`, `'ctr'`,
4075    `'ecb'`, `'gcm'`, `'ocb'`, `'ofb'`, `'stream'`, `'wrap'`, `'xts'`.
4076
4077Returns information about a given cipher.
4078
4079Some ciphers accept variable length keys and initialization vectors. By default,
4080the `crypto.getCipherInfo()` method will return the default values for these
4081ciphers. To test if a given key length or iv length is acceptable for given
4082cipher, use the `keyLength` and `ivLength` options. If the given values are
4083unacceptable, `undefined` will be returned.
4084
4085### `crypto.getCiphers()`
4086
4087<!-- YAML
4088added: v0.9.3
4089-->
4090
4091* Returns: {string\[]} An array with the names of the supported cipher
4092  algorithms.
4093
4094```mjs
4095const {
4096  getCiphers,
4097} = await import('node:crypto');
4098
4099console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
4100```
4101
4102```cjs
4103const {
4104  getCiphers,
4105} = require('node:crypto');
4106
4107console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
4108```
4109
4110### `crypto.getCurves()`
4111
4112<!-- YAML
4113added: v2.3.0
4114-->
4115
4116* Returns: {string\[]} An array with the names of the supported elliptic curves.
4117
4118```mjs
4119const {
4120  getCurves,
4121} = await import('node:crypto');
4122
4123console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
4124```
4125
4126```cjs
4127const {
4128  getCurves,
4129} = require('node:crypto');
4130
4131console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
4132```
4133
4134### `crypto.getDiffieHellman(groupName)`
4135
4136<!-- YAML
4137added: v0.7.5
4138-->
4139
4140* `groupName` {string}
4141* Returns: {DiffieHellmanGroup}
4142
4143Creates a predefined `DiffieHellmanGroup` key exchange object. The
4144supported groups are listed in the documentation for [`DiffieHellmanGroup`][].
4145
4146The returned object mimics the interface of objects created by
4147[`crypto.createDiffieHellman()`][], but will not allow changing
4148the keys (with [`diffieHellman.setPublicKey()`][], for example). The
4149advantage of using this method is that the parties do not have to
4150generate nor exchange a group modulus beforehand, saving both processor
4151and communication time.
4152
4153Example (obtaining a shared secret):
4154
4155```mjs
4156const {
4157  getDiffieHellman,
4158} = await import('node:crypto');
4159const alice = getDiffieHellman('modp14');
4160const bob = getDiffieHellman('modp14');
4161
4162alice.generateKeys();
4163bob.generateKeys();
4164
4165const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
4166const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
4167
4168/* aliceSecret and bobSecret should be the same */
4169console.log(aliceSecret === bobSecret);
4170```
4171
4172```cjs
4173const {
4174  getDiffieHellman,
4175} = require('node:crypto');
4176
4177const alice = getDiffieHellman('modp14');
4178const bob = getDiffieHellman('modp14');
4179
4180alice.generateKeys();
4181bob.generateKeys();
4182
4183const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
4184const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
4185
4186/* aliceSecret and bobSecret should be the same */
4187console.log(aliceSecret === bobSecret);
4188```
4189
4190### `crypto.getFips()`
4191
4192<!-- YAML
4193added: v10.0.0
4194-->
4195
4196* Returns: {number} `1` if and only if a FIPS compliant crypto provider is
4197  currently in use, `0` otherwise. A future semver-major release may change
4198  the return type of this API to a {boolean}.
4199
4200### `crypto.getHashes()`
4201
4202<!-- YAML
4203added: v0.9.3
4204-->
4205
4206* Returns: {string\[]} An array of the names of the supported hash algorithms,
4207  such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms.
4208
4209```mjs
4210const {
4211  getHashes,
4212} = await import('node:crypto');
4213
4214console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
4215```
4216
4217```cjs
4218const {
4219  getHashes,
4220} = require('node:crypto');
4221
4222console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
4223```
4224
4225### `crypto.getRandomValues(typedArray)`
4226
4227<!-- YAML
4228added: v17.4.0
4229-->
4230
4231* `typedArray` {Buffer|TypedArray|DataView|ArrayBuffer}
4232* Returns: {Buffer|TypedArray|DataView|ArrayBuffer} Returns `typedArray`.
4233
4234A convenient alias for [`crypto.webcrypto.getRandomValues()`][]. This
4235implementation is not compliant with the Web Crypto spec, to write
4236web-compatible code use [`crypto.webcrypto.getRandomValues()`][] instead.
4237
4238### `crypto.hkdf(digest, ikm, salt, info, keylen, callback)`
4239
4240<!-- YAML
4241added: v15.0.0
4242changes:
4243  - version: v18.8.0
4244    pr-url: https://github.com/nodejs/node/pull/44201
4245    description: The input keying material can now be zero-length.
4246  - version: v18.0.0
4247    pr-url: https://github.com/nodejs/node/pull/41678
4248    description: Passing an invalid callback to the `callback` argument
4249                 now throws `ERR_INVALID_ARG_TYPE` instead of
4250                 `ERR_INVALID_CALLBACK`.
4251-->
4252
4253* `digest` {string} The digest algorithm to use.
4254* `ikm` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject} The input
4255  keying material. Must be provided but can be zero-length.
4256* `salt` {string|ArrayBuffer|Buffer|TypedArray|DataView} The salt value. Must
4257  be provided but can be zero-length.
4258* `info` {string|ArrayBuffer|Buffer|TypedArray|DataView} Additional info value.
4259  Must be provided but can be zero-length, and cannot be more than 1024 bytes.
4260* `keylen` {number} The length of the key to generate. Must be greater than 0.
4261  The maximum allowable value is `255` times the number of bytes produced by
4262  the selected digest function (e.g. `sha512` generates 64-byte hashes, making
4263  the maximum HKDF output 16320 bytes).
4264* `callback` {Function}
4265  * `err` {Error}
4266  * `derivedKey` {ArrayBuffer}
4267
4268HKDF is a simple key derivation function defined in RFC 5869. The given `ikm`,
4269`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes.
4270
4271The supplied `callback` function is called with two arguments: `err` and
4272`derivedKey`. If an errors occurs while deriving the key, `err` will be set;
4273otherwise `err` will be `null`. The successfully generated `derivedKey` will
4274be passed to the callback as an {ArrayBuffer}. An error will be thrown if any
4275of the input arguments specify invalid values or types.
4276
4277```mjs
4278import { Buffer } from 'node:buffer';
4279const {
4280  hkdf,
4281} = await import('node:crypto');
4282
4283hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
4284  if (err) throw err;
4285  console.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'
4286});
4287```
4288
4289```cjs
4290const {
4291  hkdf,
4292} = require('node:crypto');
4293const { Buffer } = require('node:buffer');
4294
4295hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
4296  if (err) throw err;
4297  console.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'
4298});
4299```
4300
4301### `crypto.hkdfSync(digest, ikm, salt, info, keylen)`
4302
4303<!-- YAML
4304added: v15.0.0
4305changes:
4306  - version: v18.8.0
4307    pr-url: https://github.com/nodejs/node/pull/44201
4308    description: The input keying material can now be zero-length.
4309-->
4310
4311* `digest` {string} The digest algorithm to use.
4312* `ikm` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject} The input
4313  keying material. Must be provided but can be zero-length.
4314* `salt` {string|ArrayBuffer|Buffer|TypedArray|DataView} The salt value. Must
4315  be provided but can be zero-length.
4316* `info` {string|ArrayBuffer|Buffer|TypedArray|DataView} Additional info value.
4317  Must be provided but can be zero-length, and cannot be more than 1024 bytes.
4318* `keylen` {number} The length of the key to generate. Must be greater than 0.
4319  The maximum allowable value is `255` times the number of bytes produced by
4320  the selected digest function (e.g. `sha512` generates 64-byte hashes, making
4321  the maximum HKDF output 16320 bytes).
4322* Returns: {ArrayBuffer}
4323
4324Provides a synchronous HKDF key derivation function as defined in RFC 5869. The
4325given `ikm`, `salt` and `info` are used with the `digest` to derive a key of
4326`keylen` bytes.
4327
4328The successfully generated `derivedKey` will be returned as an {ArrayBuffer}.
4329
4330An error will be thrown if any of the input arguments specify invalid values or
4331types, or if the derived key cannot be generated.
4332
4333```mjs
4334import { Buffer } from 'node:buffer';
4335const {
4336  hkdfSync,
4337} = await import('node:crypto');
4338
4339const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
4340console.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'
4341```
4342
4343```cjs
4344const {
4345  hkdfSync,
4346} = require('node:crypto');
4347const { Buffer } = require('node:buffer');
4348
4349const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
4350console.log(Buffer.from(derivedKey).toString('hex'));  // '24156e2...5391653'
4351```
4352
4353### `crypto.pbkdf2(password, salt, iterations, keylen, digest, callback)`
4354
4355<!-- YAML
4356added: v0.5.5
4357changes:
4358  - version: v18.0.0
4359    pr-url: https://github.com/nodejs/node/pull/41678
4360    description: Passing an invalid callback to the `callback` argument
4361                 now throws `ERR_INVALID_ARG_TYPE` instead of
4362                 `ERR_INVALID_CALLBACK`.
4363  - version: v15.0.0
4364    pr-url: https://github.com/nodejs/node/pull/35093
4365    description: The password and salt arguments can also be ArrayBuffer
4366                 instances.
4367  - version: v14.0.0
4368    pr-url: https://github.com/nodejs/node/pull/30578
4369    description: The `iterations` parameter is now restricted to positive
4370                 values. Earlier releases treated other values as one.
4371  - version: v8.0.0
4372    pr-url: https://github.com/nodejs/node/pull/11305
4373    description: The `digest` parameter is always required now.
4374  - version: v6.0.0
4375    pr-url: https://github.com/nodejs/node/pull/4047
4376    description: Calling this function without passing the `digest` parameter
4377                 is deprecated now and will emit a warning.
4378  - version: v6.0.0
4379    pr-url: https://github.com/nodejs/node/pull/5522
4380    description: The default encoding for `password` if it is a string changed
4381                 from `binary` to `utf8`.
4382-->
4383
4384* `password` {string|ArrayBuffer|Buffer|TypedArray|DataView}
4385* `salt` {string|ArrayBuffer|Buffer|TypedArray|DataView}
4386* `iterations` {number}
4387* `keylen` {number}
4388* `digest` {string}
4389* `callback` {Function}
4390  * `err` {Error}
4391  * `derivedKey` {Buffer}
4392
4393Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)
4394implementation. A selected HMAC digest algorithm specified by `digest` is
4395applied to derive a key of the requested byte length (`keylen`) from the
4396`password`, `salt` and `iterations`.
4397
4398The supplied `callback` function is called with two arguments: `err` and
4399`derivedKey`. If an error occurs while deriving the key, `err` will be set;
4400otherwise `err` will be `null`. By default, the successfully generated
4401`derivedKey` will be passed to the callback as a [`Buffer`][]. An error will be
4402thrown if any of the input arguments specify invalid values or types.
4403
4404The `iterations` argument must be a number set as high as possible. The
4405higher the number of iterations, the more secure the derived key will be,
4406but will take a longer amount of time to complete.
4407
4408The `salt` should be as unique as possible. It is recommended that a salt is
4409random and at least 16 bytes long. See [NIST SP 800-132][] for details.
4410
4411When passing strings for `password` or `salt`, please consider
4412[caveats when using strings as inputs to cryptographic APIs][].
4413
4414```mjs
4415const {
4416  pbkdf2,
4417} = await import('node:crypto');
4418
4419pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
4420  if (err) throw err;
4421  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
4422});
4423```
4424
4425```cjs
4426const {
4427  pbkdf2,
4428} = require('node:crypto');
4429
4430pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
4431  if (err) throw err;
4432  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
4433});
4434```
4435
4436An array of supported digest functions can be retrieved using
4437[`crypto.getHashes()`][].
4438
4439This API uses libuv's threadpool, which can have surprising and
4440negative performance implications for some applications; see the
4441[`UV_THREADPOOL_SIZE`][] documentation for more information.
4442
4443### `crypto.pbkdf2Sync(password, salt, iterations, keylen, digest)`
4444
4445<!-- YAML
4446added: v0.9.3
4447changes:
4448  - version: v14.0.0
4449    pr-url: https://github.com/nodejs/node/pull/30578
4450    description: The `iterations` parameter is now restricted to positive
4451                 values. Earlier releases treated other values as one.
4452  - version: v6.0.0
4453    pr-url: https://github.com/nodejs/node/pull/4047
4454    description: Calling this function without passing the `digest` parameter
4455                 is deprecated now and will emit a warning.
4456  - version: v6.0.0
4457    pr-url: https://github.com/nodejs/node/pull/5522
4458    description: The default encoding for `password` if it is a string changed
4459                 from `binary` to `utf8`.
4460-->
4461
4462* `password` {string|Buffer|TypedArray|DataView}
4463* `salt` {string|Buffer|TypedArray|DataView}
4464* `iterations` {number}
4465* `keylen` {number}
4466* `digest` {string}
4467* Returns: {Buffer}
4468
4469Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)
4470implementation. A selected HMAC digest algorithm specified by `digest` is
4471applied to derive a key of the requested byte length (`keylen`) from the
4472`password`, `salt` and `iterations`.
4473
4474If an error occurs an `Error` will be thrown, otherwise the derived key will be
4475returned as a [`Buffer`][].
4476
4477The `iterations` argument must be a number set as high as possible. The
4478higher the number of iterations, the more secure the derived key will be,
4479but will take a longer amount of time to complete.
4480
4481The `salt` should be as unique as possible. It is recommended that a salt is
4482random and at least 16 bytes long. See [NIST SP 800-132][] for details.
4483
4484When passing strings for `password` or `salt`, please consider
4485[caveats when using strings as inputs to cryptographic APIs][].
4486
4487```mjs
4488const {
4489  pbkdf2Sync,
4490} = await import('node:crypto');
4491
4492const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
4493console.log(key.toString('hex'));  // '3745e48...08d59ae'
4494```
4495
4496```cjs
4497const {
4498  pbkdf2Sync,
4499} = require('node:crypto');
4500
4501const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
4502console.log(key.toString('hex'));  // '3745e48...08d59ae'
4503```
4504
4505An array of supported digest functions can be retrieved using
4506[`crypto.getHashes()`][].
4507
4508### `crypto.privateDecrypt(privateKey, buffer)`
4509
4510<!-- YAML
4511added: v0.11.14
4512changes:
4513  - version: v15.0.0
4514    pr-url: https://github.com/nodejs/node/pull/35093
4515    description: Added string, ArrayBuffer, and CryptoKey as allowable key
4516                 types. The oaepLabel can be an ArrayBuffer. The buffer can
4517                 be a string or ArrayBuffer. All types that accept buffers
4518                 are limited to a maximum of 2 ** 31 - 1 bytes.
4519  - version: v12.11.0
4520    pr-url: https://github.com/nodejs/node/pull/29489
4521    description: The `oaepLabel` option was added.
4522  - version: v12.9.0
4523    pr-url: https://github.com/nodejs/node/pull/28335
4524    description: The `oaepHash` option was added.
4525  - version: v11.6.0
4526    pr-url: https://github.com/nodejs/node/pull/24234
4527    description: This function now supports key objects.
4528-->
4529
4530<!--lint disable maximum-line-length remark-lint-->
4531
4532* `privateKey` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
4533  * `oaepHash` {string} The hash function to use for OAEP padding and MGF1.
4534    **Default:** `'sha1'`
4535  * `oaepLabel` {string|ArrayBuffer|Buffer|TypedArray|DataView} The label to
4536    use for OAEP padding. If not specified, no label is used.
4537  * `padding` {crypto.constants} An optional padding value defined in
4538    `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`,
4539    `crypto.constants.RSA_PKCS1_PADDING`, or
4540    `crypto.constants.RSA_PKCS1_OAEP_PADDING`.
4541* `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}
4542* Returns: {Buffer} A new `Buffer` with the decrypted content.
4543
4544<!--lint enable maximum-line-length remark-lint-->
4545
4546Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using
4547the corresponding public key, for example using [`crypto.publicEncrypt()`][].
4548
4549If `privateKey` is not a [`KeyObject`][], this function behaves as if
4550`privateKey` had been passed to [`crypto.createPrivateKey()`][]. If it is an
4551object, the `padding` property can be passed. Otherwise, this function uses
4552`RSA_PKCS1_OAEP_PADDING`.
4553
4554### `crypto.privateEncrypt(privateKey, buffer)`
4555
4556<!-- YAML
4557added: v1.1.0
4558changes:
4559  - version: v15.0.0
4560    pr-url: https://github.com/nodejs/node/pull/35093
4561    description: Added string, ArrayBuffer, and CryptoKey as allowable key
4562                 types. The passphrase can be an ArrayBuffer. The buffer can
4563                 be a string or ArrayBuffer. All types that accept buffers
4564                 are limited to a maximum of 2 ** 31 - 1 bytes.
4565  - version: v11.6.0
4566    pr-url: https://github.com/nodejs/node/pull/24234
4567    description: This function now supports key objects.
4568-->
4569
4570<!--lint disable maximum-line-length remark-lint-->
4571
4572* `privateKey` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
4573  * `key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
4574    A PEM encoded private key.
4575  * `passphrase` {string|ArrayBuffer|Buffer|TypedArray|DataView} An optional
4576    passphrase for the private key.
4577  * `padding` {crypto.constants} An optional padding value defined in
4578    `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or
4579    `crypto.constants.RSA_PKCS1_PADDING`.
4580  * `encoding` {string} The string encoding to use when `buffer`, `key`,
4581    or `passphrase` are strings.
4582* `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}
4583* Returns: {Buffer} A new `Buffer` with the encrypted content.
4584
4585<!--lint enable maximum-line-length remark-lint-->
4586
4587Encrypts `buffer` with `privateKey`. The returned data can be decrypted using
4588the corresponding public key, for example using [`crypto.publicDecrypt()`][].
4589
4590If `privateKey` is not a [`KeyObject`][], this function behaves as if
4591`privateKey` had been passed to [`crypto.createPrivateKey()`][]. If it is an
4592object, the `padding` property can be passed. Otherwise, this function uses
4593`RSA_PKCS1_PADDING`.
4594
4595### `crypto.publicDecrypt(key, buffer)`
4596
4597<!-- YAML
4598added: v1.1.0
4599changes:
4600  - version: v15.0.0
4601    pr-url: https://github.com/nodejs/node/pull/35093
4602    description: Added string, ArrayBuffer, and CryptoKey as allowable key
4603                 types. The passphrase can be an ArrayBuffer. The buffer can
4604                 be a string or ArrayBuffer. All types that accept buffers
4605                 are limited to a maximum of 2 ** 31 - 1 bytes.
4606  - version: v11.6.0
4607    pr-url: https://github.com/nodejs/node/pull/24234
4608    description: This function now supports key objects.
4609-->
4610
4611<!--lint disable maximum-line-length remark-lint-->
4612
4613* `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
4614  * `passphrase` {string|ArrayBuffer|Buffer|TypedArray|DataView} An optional
4615    passphrase for the private key.
4616  * `padding` {crypto.constants} An optional padding value defined in
4617    `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING` or
4618    `crypto.constants.RSA_PKCS1_PADDING`.
4619  * `encoding` {string} The string encoding to use when `buffer`, `key`,
4620    or `passphrase` are strings.
4621* `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}
4622* Returns: {Buffer} A new `Buffer` with the decrypted content.
4623
4624<!--lint enable maximum-line-length remark-lint-->
4625
4626Decrypts `buffer` with `key`.`buffer` was previously encrypted using
4627the corresponding private key, for example using [`crypto.privateEncrypt()`][].
4628
4629If `key` is not a [`KeyObject`][], this function behaves as if
4630`key` had been passed to [`crypto.createPublicKey()`][]. If it is an
4631object, the `padding` property can be passed. Otherwise, this function uses
4632`RSA_PKCS1_PADDING`.
4633
4634Because RSA public keys can be derived from private keys, a private key may
4635be passed instead of a public key.
4636
4637### `crypto.publicEncrypt(key, buffer)`
4638
4639<!-- YAML
4640added: v0.11.14
4641changes:
4642  - version: v15.0.0
4643    pr-url: https://github.com/nodejs/node/pull/35093
4644    description: Added string, ArrayBuffer, and CryptoKey as allowable key
4645                 types. The oaepLabel and passphrase can be ArrayBuffers. The
4646                 buffer can be a string or ArrayBuffer. All types that accept
4647                 buffers are limited to a maximum of 2 ** 31 - 1 bytes.
4648  - version: v12.11.0
4649    pr-url: https://github.com/nodejs/node/pull/29489
4650    description: The `oaepLabel` option was added.
4651  - version: v12.9.0
4652    pr-url: https://github.com/nodejs/node/pull/28335
4653    description: The `oaepHash` option was added.
4654  - version: v11.6.0
4655    pr-url: https://github.com/nodejs/node/pull/24234
4656    description: This function now supports key objects.
4657-->
4658
4659<!--lint disable maximum-line-length remark-lint-->
4660
4661* `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
4662  * `key` {string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
4663    A PEM encoded public or private key, {KeyObject}, or {CryptoKey}.
4664  * `oaepHash` {string} The hash function to use for OAEP padding and MGF1.
4665    **Default:** `'sha1'`
4666  * `oaepLabel` {string|ArrayBuffer|Buffer|TypedArray|DataView} The label to
4667    use for OAEP padding. If not specified, no label is used.
4668  * `passphrase` {string|ArrayBuffer|Buffer|TypedArray|DataView} An optional
4669    passphrase for the private key.
4670  * `padding` {crypto.constants} An optional padding value defined in
4671    `crypto.constants`, which may be: `crypto.constants.RSA_NO_PADDING`,
4672    `crypto.constants.RSA_PKCS1_PADDING`, or
4673    `crypto.constants.RSA_PKCS1_OAEP_PADDING`.
4674  * `encoding` {string} The string encoding to use when `buffer`, `key`,
4675    `oaepLabel`, or `passphrase` are strings.
4676* `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}
4677* Returns: {Buffer} A new `Buffer` with the encrypted content.
4678
4679<!--lint enable maximum-line-length remark-lint-->
4680
4681Encrypts the content of `buffer` with `key` and returns a new
4682[`Buffer`][] with encrypted content. The returned data can be decrypted using
4683the corresponding private key, for example using [`crypto.privateDecrypt()`][].
4684
4685If `key` is not a [`KeyObject`][], this function behaves as if
4686`key` had been passed to [`crypto.createPublicKey()`][]. If it is an
4687object, the `padding` property can be passed. Otherwise, this function uses
4688`RSA_PKCS1_OAEP_PADDING`.
4689
4690Because RSA public keys can be derived from private keys, a private key may
4691be passed instead of a public key.
4692
4693### `crypto.randomBytes(size[, callback])`
4694
4695<!-- YAML
4696added: v0.5.8
4697changes:
4698  - version: v18.0.0
4699    pr-url: https://github.com/nodejs/node/pull/41678
4700    description: Passing an invalid callback to the `callback` argument
4701                 now throws `ERR_INVALID_ARG_TYPE` instead of
4702                 `ERR_INVALID_CALLBACK`.
4703  - version: v9.0.0
4704    pr-url: https://github.com/nodejs/node/pull/16454
4705    description: Passing `null` as the `callback` argument now throws
4706                 `ERR_INVALID_CALLBACK`.
4707-->
4708
4709* `size` {number} The number of bytes to generate.  The `size` must
4710  not be larger than `2**31 - 1`.
4711* `callback` {Function}
4712  * `err` {Error}
4713  * `buf` {Buffer}
4714* Returns: {Buffer} if the `callback` function is not provided.
4715
4716Generates cryptographically strong pseudorandom data. The `size` argument
4717is a number indicating the number of bytes to generate.
4718
4719If a `callback` function is provided, the bytes are generated asynchronously
4720and the `callback` function is invoked with two arguments: `err` and `buf`.
4721If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The
4722`buf` argument is a [`Buffer`][] containing the generated bytes.
4723
4724```mjs
4725// Asynchronous
4726const {
4727  randomBytes,
4728} = await import('node:crypto');
4729
4730randomBytes(256, (err, buf) => {
4731  if (err) throw err;
4732  console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
4733});
4734```
4735
4736```cjs
4737// Asynchronous
4738const {
4739  randomBytes,
4740} = require('node:crypto');
4741
4742randomBytes(256, (err, buf) => {
4743  if (err) throw err;
4744  console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
4745});
4746```
4747
4748If the `callback` function is not provided, the random bytes are generated
4749synchronously and returned as a [`Buffer`][]. An error will be thrown if
4750there is a problem generating the bytes.
4751
4752```mjs
4753// Synchronous
4754const {
4755  randomBytes,
4756} = await import('node:crypto');
4757
4758const buf = randomBytes(256);
4759console.log(
4760  `${buf.length} bytes of random data: ${buf.toString('hex')}`);
4761```
4762
4763```cjs
4764// Synchronous
4765const {
4766  randomBytes,
4767} = require('node:crypto');
4768
4769const buf = randomBytes(256);
4770console.log(
4771  `${buf.length} bytes of random data: ${buf.toString('hex')}`);
4772```
4773
4774The `crypto.randomBytes()` method will not complete until there is
4775sufficient entropy available.
4776This should normally never take longer than a few milliseconds. The only time
4777when generating the random bytes may conceivably block for a longer period of
4778time is right after boot, when the whole system is still low on entropy.
4779
4780This API uses libuv's threadpool, which can have surprising and
4781negative performance implications for some applications; see the
4782[`UV_THREADPOOL_SIZE`][] documentation for more information.
4783
4784The asynchronous version of `crypto.randomBytes()` is carried out in a single
4785threadpool request. To minimize threadpool task length variation, partition
4786large `randomBytes` requests when doing so as part of fulfilling a client
4787request.
4788
4789### `crypto.randomFillSync(buffer[, offset][, size])`
4790
4791<!-- YAML
4792added:
4793  - v7.10.0
4794  - v6.13.0
4795changes:
4796  - version: v9.0.0
4797    pr-url: https://github.com/nodejs/node/pull/15231
4798    description: The `buffer` argument may be any `TypedArray` or `DataView`.
4799-->
4800
4801* `buffer` {ArrayBuffer|Buffer|TypedArray|DataView} Must be supplied. The
4802  size of the provided `buffer` must not be larger than `2**31 - 1`.
4803* `offset` {number} **Default:** `0`
4804* `size` {number} **Default:** `buffer.length - offset`. The `size` must
4805  not be larger than `2**31 - 1`.
4806* Returns: {ArrayBuffer|Buffer|TypedArray|DataView} The object passed as
4807  `buffer` argument.
4808
4809Synchronous version of [`crypto.randomFill()`][].
4810
4811```mjs
4812import { Buffer } from 'node:buffer';
4813const { randomFillSync } = await import('node:crypto');
4814
4815const buf = Buffer.alloc(10);
4816console.log(randomFillSync(buf).toString('hex'));
4817
4818randomFillSync(buf, 5);
4819console.log(buf.toString('hex'));
4820
4821// The above is equivalent to the following:
4822randomFillSync(buf, 5, 5);
4823console.log(buf.toString('hex'));
4824```
4825
4826```cjs
4827const { randomFillSync } = require('node:crypto');
4828const { Buffer } = require('node:buffer');
4829
4830const buf = Buffer.alloc(10);
4831console.log(randomFillSync(buf).toString('hex'));
4832
4833randomFillSync(buf, 5);
4834console.log(buf.toString('hex'));
4835
4836// The above is equivalent to the following:
4837randomFillSync(buf, 5, 5);
4838console.log(buf.toString('hex'));
4839```
4840
4841Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as
4842`buffer`.
4843
4844```mjs
4845import { Buffer } from 'node:buffer';
4846const { randomFillSync } = await import('node:crypto');
4847
4848const a = new Uint32Array(10);
4849console.log(Buffer.from(randomFillSync(a).buffer,
4850                        a.byteOffset, a.byteLength).toString('hex'));
4851
4852const b = new DataView(new ArrayBuffer(10));
4853console.log(Buffer.from(randomFillSync(b).buffer,
4854                        b.byteOffset, b.byteLength).toString('hex'));
4855
4856const c = new ArrayBuffer(10);
4857console.log(Buffer.from(randomFillSync(c)).toString('hex'));
4858```
4859
4860```cjs
4861const { randomFillSync } = require('node:crypto');
4862const { Buffer } = require('node:buffer');
4863
4864const a = new Uint32Array(10);
4865console.log(Buffer.from(randomFillSync(a).buffer,
4866                        a.byteOffset, a.byteLength).toString('hex'));
4867
4868const b = new DataView(new ArrayBuffer(10));
4869console.log(Buffer.from(randomFillSync(b).buffer,
4870                        b.byteOffset, b.byteLength).toString('hex'));
4871
4872const c = new ArrayBuffer(10);
4873console.log(Buffer.from(randomFillSync(c)).toString('hex'));
4874```
4875
4876### `crypto.randomFill(buffer[, offset][, size], callback)`
4877
4878<!-- YAML
4879added:
4880  - v7.10.0
4881  - v6.13.0
4882changes:
4883  - version: v18.0.0
4884    pr-url: https://github.com/nodejs/node/pull/41678
4885    description: Passing an invalid callback to the `callback` argument
4886                 now throws `ERR_INVALID_ARG_TYPE` instead of
4887                 `ERR_INVALID_CALLBACK`.
4888  - version: v9.0.0
4889    pr-url: https://github.com/nodejs/node/pull/15231
4890    description: The `buffer` argument may be any `TypedArray` or `DataView`.
4891-->
4892
4893* `buffer` {ArrayBuffer|Buffer|TypedArray|DataView} Must be supplied. The
4894  size of the provided `buffer` must not be larger than `2**31 - 1`.
4895* `offset` {number} **Default:** `0`
4896* `size` {number} **Default:** `buffer.length - offset`. The `size` must
4897  not be larger than `2**31 - 1`.
4898* `callback` {Function} `function(err, buf) {}`.
4899
4900This function is similar to [`crypto.randomBytes()`][] but requires the first
4901argument to be a [`Buffer`][] that will be filled. It also
4902requires that a callback is passed in.
4903
4904If the `callback` function is not provided, an error will be thrown.
4905
4906```mjs
4907import { Buffer } from 'node:buffer';
4908const { randomFill } = await import('node:crypto');
4909
4910const buf = Buffer.alloc(10);
4911randomFill(buf, (err, buf) => {
4912  if (err) throw err;
4913  console.log(buf.toString('hex'));
4914});
4915
4916randomFill(buf, 5, (err, buf) => {
4917  if (err) throw err;
4918  console.log(buf.toString('hex'));
4919});
4920
4921// The above is equivalent to the following:
4922randomFill(buf, 5, 5, (err, buf) => {
4923  if (err) throw err;
4924  console.log(buf.toString('hex'));
4925});
4926```
4927
4928```cjs
4929const { randomFill } = require('node:crypto');
4930const { Buffer } = require('node:buffer');
4931
4932const buf = Buffer.alloc(10);
4933randomFill(buf, (err, buf) => {
4934  if (err) throw err;
4935  console.log(buf.toString('hex'));
4936});
4937
4938randomFill(buf, 5, (err, buf) => {
4939  if (err) throw err;
4940  console.log(buf.toString('hex'));
4941});
4942
4943// The above is equivalent to the following:
4944randomFill(buf, 5, 5, (err, buf) => {
4945  if (err) throw err;
4946  console.log(buf.toString('hex'));
4947});
4948```
4949
4950Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as
4951`buffer`.
4952
4953While this includes instances of `Float32Array` and `Float64Array`, this
4954function should not be used to generate random floating-point numbers. The
4955result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array
4956contains finite numbers only, they are not drawn from a uniform random
4957distribution and have no meaningful lower or upper bounds.
4958
4959```mjs
4960import { Buffer } from 'node:buffer';
4961const { randomFill } = await import('node:crypto');
4962
4963const a = new Uint32Array(10);
4964randomFill(a, (err, buf) => {
4965  if (err) throw err;
4966  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
4967    .toString('hex'));
4968});
4969
4970const b = new DataView(new ArrayBuffer(10));
4971randomFill(b, (err, buf) => {
4972  if (err) throw err;
4973  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
4974    .toString('hex'));
4975});
4976
4977const c = new ArrayBuffer(10);
4978randomFill(c, (err, buf) => {
4979  if (err) throw err;
4980  console.log(Buffer.from(buf).toString('hex'));
4981});
4982```
4983
4984```cjs
4985const { randomFill } = require('node:crypto');
4986const { Buffer } = require('node:buffer');
4987
4988const a = new Uint32Array(10);
4989randomFill(a, (err, buf) => {
4990  if (err) throw err;
4991  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
4992    .toString('hex'));
4993});
4994
4995const b = new DataView(new ArrayBuffer(10));
4996randomFill(b, (err, buf) => {
4997  if (err) throw err;
4998  console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
4999    .toString('hex'));
5000});
5001
5002const c = new ArrayBuffer(10);
5003randomFill(c, (err, buf) => {
5004  if (err) throw err;
5005  console.log(Buffer.from(buf).toString('hex'));
5006});
5007```
5008
5009This API uses libuv's threadpool, which can have surprising and
5010negative performance implications for some applications; see the
5011[`UV_THREADPOOL_SIZE`][] documentation for more information.
5012
5013The asynchronous version of `crypto.randomFill()` is carried out in a single
5014threadpool request. To minimize threadpool task length variation, partition
5015large `randomFill` requests when doing so as part of fulfilling a client
5016request.
5017
5018### `crypto.randomInt([min, ]max[, callback])`
5019
5020<!-- YAML
5021added:
5022  - v14.10.0
5023  - v12.19.0
5024changes:
5025  - version: v18.0.0
5026    pr-url: https://github.com/nodejs/node/pull/41678
5027    description: Passing an invalid callback to the `callback` argument
5028                 now throws `ERR_INVALID_ARG_TYPE` instead of
5029                 `ERR_INVALID_CALLBACK`.
5030-->
5031
5032* `min` {integer} Start of random range (inclusive). **Default:** `0`.
5033* `max` {integer} End of random range (exclusive).
5034* `callback` {Function} `function(err, n) {}`.
5035
5036Return a random integer `n` such that `min <= n < max`.  This
5037implementation avoids [modulo bias][].
5038
5039The range (`max - min`) must be less than 2<sup>48</sup>. `min` and `max` must
5040be [safe integers][].
5041
5042If the `callback` function is not provided, the random integer is
5043generated synchronously.
5044
5045```mjs
5046// Asynchronous
5047const {
5048  randomInt,
5049} = await import('node:crypto');
5050
5051randomInt(3, (err, n) => {
5052  if (err) throw err;
5053  console.log(`Random number chosen from (0, 1, 2): ${n}`);
5054});
5055```
5056
5057```cjs
5058// Asynchronous
5059const {
5060  randomInt,
5061} = require('node:crypto');
5062
5063randomInt(3, (err, n) => {
5064  if (err) throw err;
5065  console.log(`Random number chosen from (0, 1, 2): ${n}`);
5066});
5067```
5068
5069```mjs
5070// Synchronous
5071const {
5072  randomInt,
5073} = await import('node:crypto');
5074
5075const n = randomInt(3);
5076console.log(`Random number chosen from (0, 1, 2): ${n}`);
5077```
5078
5079```cjs
5080// Synchronous
5081const {
5082  randomInt,
5083} = require('node:crypto');
5084
5085const n = randomInt(3);
5086console.log(`Random number chosen from (0, 1, 2): ${n}`);
5087```
5088
5089```mjs
5090// With `min` argument
5091const {
5092  randomInt,
5093} = await import('node:crypto');
5094
5095const n = randomInt(1, 7);
5096console.log(`The dice rolled: ${n}`);
5097```
5098
5099```cjs
5100// With `min` argument
5101const {
5102  randomInt,
5103} = require('node:crypto');
5104
5105const n = randomInt(1, 7);
5106console.log(`The dice rolled: ${n}`);
5107```
5108
5109### `crypto.randomUUID([options])`
5110
5111<!-- YAML
5112added:
5113  - v15.6.0
5114  - v14.17.0
5115-->
5116
5117* `options` {Object}
5118  * `disableEntropyCache` {boolean} By default, to improve performance,
5119    Node.js generates and caches enough
5120    random data to generate up to 128 random UUIDs. To generate a UUID
5121    without using the cache, set `disableEntropyCache` to `true`.
5122    **Default:** `false`.
5123* Returns: {string}
5124
5125Generates a random [RFC 4122][] version 4 UUID. The UUID is generated using a
5126cryptographic pseudorandom number generator.
5127
5128### `crypto.scrypt(password, salt, keylen[, options], callback)`
5129
5130<!-- YAML
5131added: v10.5.0
5132changes:
5133  - version: v18.0.0
5134    pr-url: https://github.com/nodejs/node/pull/41678
5135    description: Passing an invalid callback to the `callback` argument
5136                 now throws `ERR_INVALID_ARG_TYPE` instead of
5137                 `ERR_INVALID_CALLBACK`.
5138  - version: v15.0.0
5139    pr-url: https://github.com/nodejs/node/pull/35093
5140    description: The password and salt arguments can also be ArrayBuffer
5141                 instances.
5142  - version:
5143     - v12.8.0
5144     - v10.17.0
5145    pr-url: https://github.com/nodejs/node/pull/28799
5146    description: The `maxmem` value can now be any safe integer.
5147  - version: v10.9.0
5148    pr-url: https://github.com/nodejs/node/pull/21525
5149    description: The `cost`, `blockSize` and `parallelization` option names
5150                 have been added.
5151-->
5152
5153* `password` {string|ArrayBuffer|Buffer|TypedArray|DataView}
5154* `salt` {string|ArrayBuffer|Buffer|TypedArray|DataView}
5155* `keylen` {number}
5156* `options` {Object}
5157  * `cost` {number} CPU/memory cost parameter. Must be a power of two greater
5158    than one. **Default:** `16384`.
5159  * `blockSize` {number} Block size parameter. **Default:** `8`.
5160  * `parallelization` {number} Parallelization parameter. **Default:** `1`.
5161  * `N` {number} Alias for `cost`. Only one of both may be specified.
5162  * `r` {number} Alias for `blockSize`. Only one of both may be specified.
5163  * `p` {number} Alias for `parallelization`. Only one of both may be specified.
5164  * `maxmem` {number} Memory upper bound. It is an error when (approximately)
5165    `128 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.
5166* `callback` {Function}
5167  * `err` {Error}
5168  * `derivedKey` {Buffer}
5169
5170Provides an asynchronous [scrypt][] implementation. Scrypt is a password-based
5171key derivation function that is designed to be expensive computationally and
5172memory-wise in order to make brute-force attacks unrewarding.
5173
5174The `salt` should be as unique as possible. It is recommended that a salt is
5175random and at least 16 bytes long. See [NIST SP 800-132][] for details.
5176
5177When passing strings for `password` or `salt`, please consider
5178[caveats when using strings as inputs to cryptographic APIs][].
5179
5180The `callback` function is called with two arguments: `err` and `derivedKey`.
5181`err` is an exception object when key derivation fails, otherwise `err` is
5182`null`. `derivedKey` is passed to the callback as a [`Buffer`][].
5183
5184An exception is thrown when any of the input arguments specify invalid values
5185or types.
5186
5187```mjs
5188const {
5189  scrypt,
5190} = await import('node:crypto');
5191
5192// Using the factory defaults.
5193scrypt('password', 'salt', 64, (err, derivedKey) => {
5194  if (err) throw err;
5195  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
5196});
5197// Using a custom N parameter. Must be a power of two.
5198scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
5199  if (err) throw err;
5200  console.log(derivedKey.toString('hex'));  // '3745e48...aa39b34'
5201});
5202```
5203
5204```cjs
5205const {
5206  scrypt,
5207} = require('node:crypto');
5208
5209// Using the factory defaults.
5210scrypt('password', 'salt', 64, (err, derivedKey) => {
5211  if (err) throw err;
5212  console.log(derivedKey.toString('hex'));  // '3745e48...08d59ae'
5213});
5214// Using a custom N parameter. Must be a power of two.
5215scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
5216  if (err) throw err;
5217  console.log(derivedKey.toString('hex'));  // '3745e48...aa39b34'
5218});
5219```
5220
5221### `crypto.scryptSync(password, salt, keylen[, options])`
5222
5223<!-- YAML
5224added: v10.5.0
5225changes:
5226  - version:
5227     - v12.8.0
5228     - v10.17.0
5229    pr-url: https://github.com/nodejs/node/pull/28799
5230    description: The `maxmem` value can now be any safe integer.
5231  - version: v10.9.0
5232    pr-url: https://github.com/nodejs/node/pull/21525
5233    description: The `cost`, `blockSize` and `parallelization` option names
5234                 have been added.
5235-->
5236
5237* `password` {string|Buffer|TypedArray|DataView}
5238* `salt` {string|Buffer|TypedArray|DataView}
5239* `keylen` {number}
5240* `options` {Object}
5241  * `cost` {number} CPU/memory cost parameter. Must be a power of two greater
5242    than one. **Default:** `16384`.
5243  * `blockSize` {number} Block size parameter. **Default:** `8`.
5244  * `parallelization` {number} Parallelization parameter. **Default:** `1`.
5245  * `N` {number} Alias for `cost`. Only one of both may be specified.
5246  * `r` {number} Alias for `blockSize`. Only one of both may be specified.
5247  * `p` {number} Alias for `parallelization`. Only one of both may be specified.
5248  * `maxmem` {number} Memory upper bound. It is an error when (approximately)
5249    `128 * N * r > maxmem`. **Default:** `32 * 1024 * 1024`.
5250* Returns: {Buffer}
5251
5252Provides a synchronous [scrypt][] implementation. Scrypt is a password-based
5253key derivation function that is designed to be expensive computationally and
5254memory-wise in order to make brute-force attacks unrewarding.
5255
5256The `salt` should be as unique as possible. It is recommended that a salt is
5257random and at least 16 bytes long. See [NIST SP 800-132][] for details.
5258
5259When passing strings for `password` or `salt`, please consider
5260[caveats when using strings as inputs to cryptographic APIs][].
5261
5262An exception is thrown when key derivation fails, otherwise the derived key is
5263returned as a [`Buffer`][].
5264
5265An exception is thrown when any of the input arguments specify invalid values
5266or types.
5267
5268```mjs
5269const {
5270  scryptSync,
5271} = await import('node:crypto');
5272// Using the factory defaults.
5273
5274const key1 = scryptSync('password', 'salt', 64);
5275console.log(key1.toString('hex'));  // '3745e48...08d59ae'
5276// Using a custom N parameter. Must be a power of two.
5277const key2 = scryptSync('password', 'salt', 64, { N: 1024 });
5278console.log(key2.toString('hex'));  // '3745e48...aa39b34'
5279```
5280
5281```cjs
5282const {
5283  scryptSync,
5284} = require('node:crypto');
5285// Using the factory defaults.
5286
5287const key1 = scryptSync('password', 'salt', 64);
5288console.log(key1.toString('hex'));  // '3745e48...08d59ae'
5289// Using a custom N parameter. Must be a power of two.
5290const key2 = scryptSync('password', 'salt', 64, { N: 1024 });
5291console.log(key2.toString('hex'));  // '3745e48...aa39b34'
5292```
5293
5294### `crypto.secureHeapUsed()`
5295
5296<!-- YAML
5297added: v15.6.0
5298-->
5299
5300* Returns: {Object}
5301  * `total` {number} The total allocated secure heap size as specified
5302    using the `--secure-heap=n` command-line flag.
5303  * `min` {number} The minimum allocation from the secure heap as
5304    specified using the `--secure-heap-min` command-line flag.
5305  * `used` {number} The total number of bytes currently allocated from
5306    the secure heap.
5307  * `utilization` {number} The calculated ratio of `used` to `total`
5308    allocated bytes.
5309
5310### `crypto.setEngine(engine[, flags])`
5311
5312<!-- YAML
5313added: v0.11.11
5314-->
5315
5316* `engine` {string}
5317* `flags` {crypto.constants} **Default:** `crypto.constants.ENGINE_METHOD_ALL`
5318
5319Load and set the `engine` for some or all OpenSSL functions (selected by flags).
5320
5321`engine` could be either an id or a path to the engine's shared library.
5322
5323The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags`
5324is a bit field taking one of or a mix of the following flags (defined in
5325`crypto.constants`):
5326
5327* `crypto.constants.ENGINE_METHOD_RSA`
5328* `crypto.constants.ENGINE_METHOD_DSA`
5329* `crypto.constants.ENGINE_METHOD_DH`
5330* `crypto.constants.ENGINE_METHOD_RAND`
5331* `crypto.constants.ENGINE_METHOD_EC`
5332* `crypto.constants.ENGINE_METHOD_CIPHERS`
5333* `crypto.constants.ENGINE_METHOD_DIGESTS`
5334* `crypto.constants.ENGINE_METHOD_PKEY_METHS`
5335* `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS`
5336* `crypto.constants.ENGINE_METHOD_ALL`
5337* `crypto.constants.ENGINE_METHOD_NONE`
5338
5339### `crypto.setFips(bool)`
5340
5341<!-- YAML
5342added: v10.0.0
5343-->
5344
5345* `bool` {boolean} `true` to enable FIPS mode.
5346
5347Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build.
5348Throws an error if FIPS mode is not available.
5349
5350### `crypto.sign(algorithm, data, key[, callback])`
5351
5352<!-- YAML
5353added: v12.0.0
5354changes:
5355  - version: v18.0.0
5356    pr-url: https://github.com/nodejs/node/pull/41678
5357    description: Passing an invalid callback to the `callback` argument
5358                 now throws `ERR_INVALID_ARG_TYPE` instead of
5359                 `ERR_INVALID_CALLBACK`.
5360  - version: v15.12.0
5361    pr-url: https://github.com/nodejs/node/pull/37500
5362    description: Optional callback argument added.
5363  - version:
5364     - v13.2.0
5365     - v12.16.0
5366    pr-url: https://github.com/nodejs/node/pull/29292
5367    description: This function now supports IEEE-P1363 DSA and ECDSA signatures.
5368-->
5369
5370<!--lint disable maximum-line-length remark-lint-->
5371
5372* `algorithm` {string | null | undefined}
5373* `data` {ArrayBuffer|Buffer|TypedArray|DataView}
5374* `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
5375* `callback` {Function}
5376  * `err` {Error}
5377  * `signature` {Buffer}
5378* Returns: {Buffer} if the `callback` function is not provided.
5379
5380<!--lint enable maximum-line-length remark-lint-->
5381
5382Calculates and returns the signature for `data` using the given private key and
5383algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is
5384dependent upon the key type (especially Ed25519 and Ed448).
5385
5386If `key` is not a [`KeyObject`][], this function behaves as if `key` had been
5387passed to [`crypto.createPrivateKey()`][]. If it is an object, the following
5388additional properties can be passed:
5389
5390* `dsaEncoding` {string} For DSA and ECDSA, this option specifies the
5391  format of the generated signature. It can be one of the following:
5392  * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`.
5393  * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363.
5394* `padding` {integer} Optional padding value for RSA, one of the following:
5395
5396  * `crypto.constants.RSA_PKCS1_PADDING` (default)
5397  * `crypto.constants.RSA_PKCS1_PSS_PADDING`
5398
5399  `RSA_PKCS1_PSS_PADDING` will use MGF1 with the same hash function
5400  used to sign the message as specified in section 3.1 of [RFC 4055][].
5401* `saltLength` {integer} Salt length for when padding is
5402  `RSA_PKCS1_PSS_PADDING`. The special value
5403  `crypto.constants.RSA_PSS_SALTLEN_DIGEST` sets the salt length to the digest
5404  size, `crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN` (default) sets it to the
5405  maximum permissible value.
5406
5407If the `callback` function is provided this function uses libuv's threadpool.
5408
5409### `crypto.subtle`
5410
5411<!-- YAML
5412added: v17.4.0
5413-->
5414
5415* Type: {SubtleCrypto}
5416
5417A convenient alias for [`crypto.webcrypto.subtle`][].
5418
5419### `crypto.timingSafeEqual(a, b)`
5420
5421<!-- YAML
5422added: v6.6.0
5423changes:
5424  - version: v15.0.0
5425    pr-url: https://github.com/nodejs/node/pull/35093
5426    description: The a and b arguments can also be ArrayBuffer.
5427-->
5428
5429* `a` {ArrayBuffer|Buffer|TypedArray|DataView}
5430* `b` {ArrayBuffer|Buffer|TypedArray|DataView}
5431* Returns: {boolean}
5432
5433This function compares the underlying bytes that represent the given
5434`ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time
5435algorithm.
5436
5437This function does not leak timing information that
5438would allow an attacker to guess one of the values. This is suitable for
5439comparing HMAC digests or secret values like authentication cookies or
5440[capability urls](https://www.w3.org/TR/capability-urls/).
5441
5442`a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they
5443must have the same byte length. An error is thrown if `a` and `b` have
5444different byte lengths.
5445
5446If at least one of `a` and `b` is a `TypedArray` with more than one byte per
5447entry, such as `Uint16Array`, the result will be computed using the platform
5448byte order.
5449
5450<strong class="critical">When both of the inputs are `Float32Array`s or
5451`Float64Array`s, this function might return unexpected results due to IEEE 754
5452encoding of floating-point numbers. In particular, neither `x === y` nor
5453`Object.is(x, y)` implies that the byte representations of two floating-point
5454numbers `x` and `y` are equal.</strong>
5455
5456Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code
5457is timing-safe. Care should be taken to ensure that the surrounding code does
5458not introduce timing vulnerabilities.
5459
5460### `crypto.verify(algorithm, data, key, signature[, callback])`
5461
5462<!-- YAML
5463added: v12.0.0
5464changes:
5465  - version: v18.0.0
5466    pr-url: https://github.com/nodejs/node/pull/41678
5467    description: Passing an invalid callback to the `callback` argument
5468                 now throws `ERR_INVALID_ARG_TYPE` instead of
5469                 `ERR_INVALID_CALLBACK`.
5470  - version: v15.12.0
5471    pr-url: https://github.com/nodejs/node/pull/37500
5472    description: Optional callback argument added.
5473  - version: v15.0.0
5474    pr-url: https://github.com/nodejs/node/pull/35093
5475    description: The data, key, and signature arguments can also be ArrayBuffer.
5476  - version:
5477     - v13.2.0
5478     - v12.16.0
5479    pr-url: https://github.com/nodejs/node/pull/29292
5480    description: This function now supports IEEE-P1363 DSA and ECDSA signatures.
5481-->
5482
5483<!--lint disable maximum-line-length remark-lint-->
5484
5485* `algorithm` {string|null|undefined}
5486* `data` {ArrayBuffer| Buffer|TypedArray|DataView}
5487* `key` {Object|string|ArrayBuffer|Buffer|TypedArray|DataView|KeyObject|CryptoKey}
5488* `signature` {ArrayBuffer|Buffer|TypedArray|DataView}
5489* `callback` {Function}
5490  * `err` {Error}
5491  * `result` {boolean}
5492* Returns: {boolean} `true` or `false` depending on the validity of the
5493  signature for the data and public key if the `callback` function is not
5494  provided.
5495
5496<!--lint enable maximum-line-length remark-lint-->
5497
5498Verifies the given signature for `data` using the given key and algorithm. If
5499`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the
5500key type (especially Ed25519 and Ed448).
5501
5502If `key` is not a [`KeyObject`][], this function behaves as if `key` had been
5503passed to [`crypto.createPublicKey()`][]. If it is an object, the following
5504additional properties can be passed:
5505
5506* `dsaEncoding` {string} For DSA and ECDSA, this option specifies the
5507  format of the signature. It can be one of the following:
5508  * `'der'` (default): DER-encoded ASN.1 signature structure encoding `(r, s)`.
5509  * `'ieee-p1363'`: Signature format `r || s` as proposed in IEEE-P1363.
5510* `padding` {integer} Optional padding value for RSA, one of the following:
5511
5512  * `crypto.constants.RSA_PKCS1_PADDING` (default)
5513  * `crypto.constants.RSA_PKCS1_PSS_PADDING`
5514
5515  `RSA_PKCS1_PSS_PADDING` will use MGF1 with the same hash function
5516  used to sign the message as specified in section 3.1 of [RFC 4055][].
5517* `saltLength` {integer} Salt length for when padding is
5518  `RSA_PKCS1_PSS_PADDING`. The special value
5519  `crypto.constants.RSA_PSS_SALTLEN_DIGEST` sets the salt length to the digest
5520  size, `crypto.constants.RSA_PSS_SALTLEN_MAX_SIGN` (default) sets it to the
5521  maximum permissible value.
5522
5523The `signature` argument is the previously calculated signature for the `data`.
5524
5525Because public keys can be derived from private keys, a private key or a public
5526key may be passed for `key`.
5527
5528If the `callback` function is provided this function uses libuv's threadpool.
5529
5530### `crypto.webcrypto`
5531
5532<!-- YAML
5533added: v15.0.0
5534-->
5535
5536Type: {Crypto} An implementation of the Web Crypto API standard.
5537
5538See the [Web Crypto API documentation][] for details.
5539
5540## Notes
5541
5542### Using strings as inputs to cryptographic APIs
5543
5544For historical reasons, many cryptographic APIs provided by Node.js accept
5545strings as inputs where the underlying cryptographic algorithm works on byte
5546sequences. These instances include plaintexts, ciphertexts, symmetric keys,
5547initialization vectors, passphrases, salts, authentication tags,
5548and additional authenticated data.
5549
5550When passing strings to cryptographic APIs, consider the following factors.
5551
5552* Not all byte sequences are valid UTF-8 strings. Therefore, when a byte
5553  sequence of length `n` is derived from a string, its entropy is generally
5554  lower than the entropy of a random or pseudorandom `n` byte sequence.
5555  For example, no UTF-8 string will result in the byte sequence `c0 af`. Secret
5556  keys should almost exclusively be random or pseudorandom byte sequences.
5557* Similarly, when converting random or pseudorandom byte sequences to UTF-8
5558  strings, subsequences that do not represent valid code points may be replaced
5559  by the Unicode replacement character (`U+FFFD`). The byte representation of
5560  the resulting Unicode string may, therefore, not be equal to the byte sequence
5561  that the string was created from.
5562
5563  ```js
5564  const original = [0xc0, 0xaf];
5565  const bytesAsString = Buffer.from(original).toString('utf8');
5566  const stringAsBytes = Buffer.from(bytesAsString, 'utf8');
5567  console.log(stringAsBytes);
5568  // Prints '<Buffer ef bf bd ef bf bd>'.
5569  ```
5570
5571  The outputs of ciphers, hash functions, signature algorithms, and key
5572  derivation functions are pseudorandom byte sequences and should not be
5573  used as Unicode strings.
5574* When strings are obtained from user input, some Unicode characters can be
5575  represented in multiple equivalent ways that result in different byte
5576  sequences. For example, when passing a user passphrase to a key derivation
5577  function, such as PBKDF2 or scrypt, the result of the key derivation function
5578  depends on whether the string uses composed or decomposed characters. Node.js
5579  does not normalize character representations. Developers should consider using
5580  [`String.prototype.normalize()`][] on user inputs before passing them to
5581  cryptographic APIs.
5582
5583### Legacy streams API (prior to Node.js 0.10)
5584
5585The Crypto module was added to Node.js before there was the concept of a
5586unified Stream API, and before there were [`Buffer`][] objects for handling
5587binary data. As such, many `crypto` classes have methods not
5588typically found on other Node.js classes that implement the [streams][stream]
5589API (e.g. `update()`, `final()`, or `digest()`). Also, many methods accepted
5590and returned `'latin1'` encoded strings by default rather than `Buffer`s. This
5591default was changed after Node.js v0.8 to use [`Buffer`][] objects by default
5592instead.
5593
5594### Support for weak or compromised algorithms
5595
5596The `node:crypto` module still supports some algorithms which are already
5597compromised and are not currently recommended for use. The API also allows
5598the use of ciphers and hashes with a small key size that are too weak for safe
5599use.
5600
5601Users should take full responsibility for selecting the crypto
5602algorithm and key size according to their security requirements.
5603
5604Based on the recommendations of [NIST SP 800-131A][]:
5605
5606* MD5 and SHA-1 are no longer acceptable where collision resistance is
5607  required such as digital signatures.
5608* The key used with RSA, DSA, and DH algorithms is recommended to have
5609  at least 2048 bits and that of the curve of ECDSA and ECDH at least
5610  224 bits, to be safe to use for several years.
5611* The DH groups of `modp1`, `modp2` and `modp5` have a key size
5612  smaller than 2048 bits and are not recommended.
5613
5614See the reference for other recommendations and details.
5615
5616Some algorithms that have known weaknesses and are of little relevance in
5617practice are only available through the [legacy provider][], which is not
5618enabled by default.
5619
5620### CCM mode
5621
5622CCM is one of the supported [AEAD algorithms][]. Applications which use this
5623mode must adhere to certain restrictions when using the cipher API:
5624
5625* The authentication tag length must be specified during cipher creation by
5626  setting the `authTagLength` option and must be one of 4, 6, 8, 10, 12, 14 or
5627  16 bytes.
5628* The length of the initialization vector (nonce) `N` must be between 7 and 13
5629  bytes (`7 ≤ N ≤ 13`).
5630* The length of the plaintext is limited to `2 ** (8 * (15 - N))` bytes.
5631* When decrypting, the authentication tag must be set via `setAuthTag()` before
5632  calling `update()`.
5633  Otherwise, decryption will fail and `final()` will throw an error in
5634  compliance with section 2.6 of [RFC 3610][].
5635* Using stream methods such as `write(data)`, `end(data)` or `pipe()` in CCM
5636  mode might fail as CCM cannot handle more than one chunk of data per instance.
5637* When passing additional authenticated data (AAD), the length of the actual
5638  message in bytes must be passed to `setAAD()` via the `plaintextLength`
5639  option.
5640  Many crypto libraries include the authentication tag in the ciphertext,
5641  which means that they produce ciphertexts of the length
5642  `plaintextLength + authTagLength`. Node.js does not include the authentication
5643  tag, so the ciphertext length is always `plaintextLength`.
5644  This is not necessary if no AAD is used.
5645* As CCM processes the whole message at once, `update()` must be called exactly
5646  once.
5647* Even though calling `update()` is sufficient to encrypt/decrypt the message,
5648  applications _must_ call `final()` to compute or verify the
5649  authentication tag.
5650
5651```mjs
5652import { Buffer } from 'node:buffer';
5653const {
5654  createCipheriv,
5655  createDecipheriv,
5656  randomBytes,
5657} = await import('node:crypto');
5658
5659const key = 'keykeykeykeykeykeykeykey';
5660const nonce = randomBytes(12);
5661
5662const aad = Buffer.from('0123456789', 'hex');
5663
5664const cipher = createCipheriv('aes-192-ccm', key, nonce, {
5665  authTagLength: 16,
5666});
5667const plaintext = 'Hello world';
5668cipher.setAAD(aad, {
5669  plaintextLength: Buffer.byteLength(plaintext),
5670});
5671const ciphertext = cipher.update(plaintext, 'utf8');
5672cipher.final();
5673const tag = cipher.getAuthTag();
5674
5675// Now transmit { ciphertext, nonce, tag }.
5676
5677const decipher = createDecipheriv('aes-192-ccm', key, nonce, {
5678  authTagLength: 16,
5679});
5680decipher.setAuthTag(tag);
5681decipher.setAAD(aad, {
5682  plaintextLength: ciphertext.length,
5683});
5684const receivedPlaintext = decipher.update(ciphertext, null, 'utf8');
5685
5686try {
5687  decipher.final();
5688} catch (err) {
5689  throw new Error('Authentication failed!', { cause: err });
5690}
5691
5692console.log(receivedPlaintext);
5693```
5694
5695```cjs
5696const { Buffer } = require('node:buffer');
5697const {
5698  createCipheriv,
5699  createDecipheriv,
5700  randomBytes,
5701} = require('node:crypto');
5702
5703const key = 'keykeykeykeykeykeykeykey';
5704const nonce = randomBytes(12);
5705
5706const aad = Buffer.from('0123456789', 'hex');
5707
5708const cipher = createCipheriv('aes-192-ccm', key, nonce, {
5709  authTagLength: 16,
5710});
5711const plaintext = 'Hello world';
5712cipher.setAAD(aad, {
5713  plaintextLength: Buffer.byteLength(plaintext),
5714});
5715const ciphertext = cipher.update(plaintext, 'utf8');
5716cipher.final();
5717const tag = cipher.getAuthTag();
5718
5719// Now transmit { ciphertext, nonce, tag }.
5720
5721const decipher = createDecipheriv('aes-192-ccm', key, nonce, {
5722  authTagLength: 16,
5723});
5724decipher.setAuthTag(tag);
5725decipher.setAAD(aad, {
5726  plaintextLength: ciphertext.length,
5727});
5728const receivedPlaintext = decipher.update(ciphertext, null, 'utf8');
5729
5730try {
5731  decipher.final();
5732} catch (err) {
5733  throw new Error('Authentication failed!', { cause: err });
5734}
5735
5736console.log(receivedPlaintext);
5737```
5738
5739### FIPS mode
5740
5741When using OpenSSL 3, Node.js supports FIPS 140-2 when used with an appropriate
5742OpenSSL 3 provider, such as the [FIPS provider from OpenSSL 3][] which can be
5743installed by following the instructions in [OpenSSL's FIPS README file][].
5744
5745For FIPS support in Node.js you will need:
5746
5747* A correctly installed OpenSSL 3 FIPS provider.
5748* An OpenSSL 3 [FIPS module configuration file][].
5749* An OpenSSL 3 configuration file that references the FIPS module
5750  configuration file.
5751
5752Node.js will need to be configured with an OpenSSL configuration file that
5753points to the FIPS provider. An example configuration file looks like this:
5754
5755```text
5756nodejs_conf = nodejs_init
5757
5758.include /<absolute path>/fipsmodule.cnf
5759
5760[nodejs_init]
5761providers = provider_sect
5762
5763[provider_sect]
5764default = default_sect
5765# The fips section name should match the section name inside the
5766# included fipsmodule.cnf.
5767fips = fips_sect
5768
5769[default_sect]
5770activate = 1
5771```
5772
5773where `fipsmodule.cnf` is the FIPS module configuration file generated from the
5774FIPS provider installation step:
5775
5776```bash
5777openssl fipsinstall
5778```
5779
5780Set the `OPENSSL_CONF` environment variable to point to
5781your configuration file and `OPENSSL_MODULES` to the location of the FIPS
5782provider dynamic library. e.g.
5783
5784```bash
5785export OPENSSL_CONF=/<path to configuration file>/nodejs.cnf
5786export OPENSSL_MODULES=/<path to openssl lib>/ossl-modules
5787```
5788
5789FIPS mode can then be enabled in Node.js either by:
5790
5791* Starting Node.js with `--enable-fips` or `--force-fips` command line flags.
5792* Programmatically calling `crypto.setFips(true)`.
5793
5794Optionally FIPS mode can be enabled in Node.js via the OpenSSL configuration
5795file. e.g.
5796
5797```text
5798nodejs_conf = nodejs_init
5799
5800.include /<absolute path>/fipsmodule.cnf
5801
5802[nodejs_init]
5803providers = provider_sect
5804alg_section = algorithm_sect
5805
5806[provider_sect]
5807default = default_sect
5808# The fips section name should match the section name inside the
5809# included fipsmodule.cnf.
5810fips = fips_sect
5811
5812[default_sect]
5813activate = 1
5814
5815[algorithm_sect]
5816default_properties = fips=yes
5817```
5818
5819## Crypto constants
5820
5821The following constants exported by `crypto.constants` apply to various uses of
5822the `node:crypto`, `node:tls`, and `node:https` modules and are generally
5823specific to OpenSSL.
5824
5825### OpenSSL options
5826
5827See the [list of SSL OP Flags][] for details.
5828
5829<table>
5830  <tr>
5831    <th>Constant</th>
5832    <th>Description</th>
5833  </tr>
5834  <tr>
5835    <td><code>SSL_OP_ALL</code></td>
5836    <td>Applies multiple bug workarounds within OpenSSL. See
5837    <a href="https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html">https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html</a>
5838    for detail.</td>
5839  </tr>
5840  <tr>
5841    <td><code>SSL_OP_ALLOW_NO_DHE_KEX</code></td>
5842    <td>Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode
5843    for TLS v1.3</td>
5844  </tr>
5845  <tr>
5846    <td><code>SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION</code></td>
5847    <td>Allows legacy insecure renegotiation between OpenSSL and unpatched
5848    clients or servers. See
5849    <a href="https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html">https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html</a>.</td>
5850  </tr>
5851  <tr>
5852    <td><code>SSL_OP_CIPHER_SERVER_PREFERENCE</code></td>
5853    <td>Attempts to use the server's preferences instead of the client's when
5854    selecting a cipher. Behavior depends on protocol version. See
5855    <a href="https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html">https://www.openssl.org/docs/man3.0/man3/SSL_CTX_set_options.html</a>.</td>
5856  </tr>
5857  <tr>
5858    <td><code>SSL_OP_CISCO_ANYCONNECT</code></td>
5859    <td>Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER.</td>
5860  </tr>
5861  <tr>
5862    <td><code>SSL_OP_COOKIE_EXCHANGE</code></td>
5863    <td>Instructs OpenSSL to turn on cookie exchange.</td>
5864  </tr>
5865  <tr>
5866    <td><code>SSL_OP_CRYPTOPRO_TLSEXT_BUG</code></td>
5867    <td>Instructs OpenSSL to add server-hello extension from an early version
5868    of the cryptopro draft.</td>
5869  </tr>
5870  <tr>
5871    <td><code>SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS</code></td>
5872    <td>Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability
5873    workaround added in OpenSSL 0.9.6d.</td>
5874  </tr>
5875  <tr>
5876    <td><code>SSL_OP_LEGACY_SERVER_CONNECT</code></td>
5877    <td>Allows initial connection to servers that do not support RI.</td>
5878  </tr>
5879  <tr>
5880    <td><code>SSL_OP_NO_COMPRESSION</code></td>
5881    <td>Instructs OpenSSL to disable support for SSL/TLS compression.</td>
5882  </tr>
5883  <tr>
5884    <td><code>SSL_OP_NO_ENCRYPT_THEN_MAC</code></td>
5885    <td>Instructs OpenSSL to disable encrypt-then-MAC.</td>
5886  </tr>
5887  <tr>
5888    <td><code>SSL_OP_NO_QUERY_MTU</code></td>
5889    <td></td>
5890  </tr>
5891  <tr>
5892    <td><code>SSL_OP_NO_RENEGOTIATION</code></td>
5893    <td>Instructs OpenSSL to disable renegotiation.</td>
5894  </tr>
5895  <tr>
5896    <td><code>SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION</code></td>
5897    <td>Instructs OpenSSL to always start a new session when performing
5898    renegotiation.</td>
5899  </tr>
5900  <tr>
5901    <td><code>SSL_OP_NO_SSLv2</code></td>
5902    <td>Instructs OpenSSL to turn off SSL v2</td>
5903  </tr>
5904  <tr>
5905    <td><code>SSL_OP_NO_SSLv3</code></td>
5906    <td>Instructs OpenSSL to turn off SSL v3</td>
5907  </tr>
5908  <tr>
5909    <td><code>SSL_OP_NO_TICKET</code></td>
5910    <td>Instructs OpenSSL to disable use of RFC4507bis tickets.</td>
5911  </tr>
5912  <tr>
5913    <td><code>SSL_OP_NO_TLSv1</code></td>
5914    <td>Instructs OpenSSL to turn off TLS v1</td>
5915  </tr>
5916  <tr>
5917    <td><code>SSL_OP_NO_TLSv1_1</code></td>
5918    <td>Instructs OpenSSL to turn off TLS v1.1</td>
5919  </tr>
5920  <tr>
5921    <td><code>SSL_OP_NO_TLSv1_2</code></td>
5922    <td>Instructs OpenSSL to turn off TLS v1.2</td>
5923  </tr>
5924  <tr>
5925    <td><code>SSL_OP_NO_TLSv1_3</code></td>
5926    <td>Instructs OpenSSL to turn off TLS v1.3</td>
5927  </tr>
5928  <tr>
5929    <td><code>SSL_OP_PRIORITIZE_CHACHA</code></td>
5930    <td>Instructs OpenSSL server to prioritize ChaCha20-Poly1305
5931    when the client does.
5932    This option has no effect if
5933    <code>SSL_OP_CIPHER_SERVER_PREFERENCE</code>
5934    is not enabled.</td>
5935  </tr>
5936  <tr>
5937    <td><code>SSL_OP_TLS_ROLLBACK_BUG</code></td>
5938    <td>Instructs OpenSSL to disable version rollback attack detection.</td>
5939  </tr>
5940</table>
5941
5942### OpenSSL engine constants
5943
5944<table>
5945  <tr>
5946    <th>Constant</th>
5947    <th>Description</th>
5948  </tr>
5949  <tr>
5950    <td><code>ENGINE_METHOD_RSA</code></td>
5951    <td>Limit engine usage to RSA</td>
5952  </tr>
5953  <tr>
5954    <td><code>ENGINE_METHOD_DSA</code></td>
5955    <td>Limit engine usage to DSA</td>
5956  </tr>
5957  <tr>
5958    <td><code>ENGINE_METHOD_DH</code></td>
5959    <td>Limit engine usage to DH</td>
5960  </tr>
5961  <tr>
5962    <td><code>ENGINE_METHOD_RAND</code></td>
5963    <td>Limit engine usage to RAND</td>
5964  </tr>
5965  <tr>
5966    <td><code>ENGINE_METHOD_EC</code></td>
5967    <td>Limit engine usage to EC</td>
5968  </tr>
5969  <tr>
5970    <td><code>ENGINE_METHOD_CIPHERS</code></td>
5971    <td>Limit engine usage to CIPHERS</td>
5972  </tr>
5973  <tr>
5974    <td><code>ENGINE_METHOD_DIGESTS</code></td>
5975    <td>Limit engine usage to DIGESTS</td>
5976  </tr>
5977  <tr>
5978    <td><code>ENGINE_METHOD_PKEY_METHS</code></td>
5979    <td>Limit engine usage to PKEY_METHDS</td>
5980  </tr>
5981  <tr>
5982    <td><code>ENGINE_METHOD_PKEY_ASN1_METHS</code></td>
5983    <td>Limit engine usage to PKEY_ASN1_METHS</td>
5984  </tr>
5985  <tr>
5986    <td><code>ENGINE_METHOD_ALL</code></td>
5987    <td></td>
5988  </tr>
5989  <tr>
5990    <td><code>ENGINE_METHOD_NONE</code></td>
5991    <td></td>
5992  </tr>
5993</table>
5994
5995### Other OpenSSL constants
5996
5997<table>
5998  <tr>
5999    <th>Constant</th>
6000    <th>Description</th>
6001  </tr>
6002  <tr>
6003    <td><code>DH_CHECK_P_NOT_SAFE_PRIME</code></td>
6004    <td></td>
6005  </tr>
6006  <tr>
6007    <td><code>DH_CHECK_P_NOT_PRIME</code></td>
6008    <td></td>
6009  </tr>
6010  <tr>
6011    <td><code>DH_UNABLE_TO_CHECK_GENERATOR</code></td>
6012    <td></td>
6013  </tr>
6014  <tr>
6015    <td><code>DH_NOT_SUITABLE_GENERATOR</code></td>
6016    <td></td>
6017  </tr>
6018  <tr>
6019    <td><code>ALPN_ENABLED</code></td>
6020    <td></td>
6021  </tr>
6022  <tr>
6023    <td><code>RSA_PKCS1_PADDING</code></td>
6024    <td></td>
6025  </tr>
6026  <tr>
6027    <td><code>RSA_SSLV23_PADDING</code></td>
6028    <td></td>
6029  </tr>
6030  <tr>
6031    <td><code>RSA_NO_PADDING</code></td>
6032    <td></td>
6033  </tr>
6034  <tr>
6035    <td><code>RSA_PKCS1_OAEP_PADDING</code></td>
6036    <td></td>
6037  </tr>
6038  <tr>
6039    <td><code>RSA_X931_PADDING</code></td>
6040    <td></td>
6041  </tr>
6042  <tr>
6043    <td><code>RSA_PKCS1_PSS_PADDING</code></td>
6044    <td></td>
6045  </tr>
6046  <tr>
6047    <td><code>RSA_PSS_SALTLEN_DIGEST</code></td>
6048    <td>Sets the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to the
6049        digest size when signing or verifying.</td>
6050  </tr>
6051  <tr>
6052    <td><code>RSA_PSS_SALTLEN_MAX_SIGN</code></td>
6053    <td>Sets the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to the
6054        maximum permissible value when signing data.</td>
6055  </tr>
6056  <tr>
6057    <td><code>RSA_PSS_SALTLEN_AUTO</code></td>
6058    <td>Causes the salt length for <code>RSA_PKCS1_PSS_PADDING</code> to be
6059        determined automatically when verifying a signature.</td>
6060  </tr>
6061  <tr>
6062    <td><code>POINT_CONVERSION_COMPRESSED</code></td>
6063    <td></td>
6064  </tr>
6065  <tr>
6066    <td><code>POINT_CONVERSION_UNCOMPRESSED</code></td>
6067    <td></td>
6068  </tr>
6069  <tr>
6070    <td><code>POINT_CONVERSION_HYBRID</code></td>
6071    <td></td>
6072  </tr>
6073</table>
6074
6075### Node.js crypto constants
6076
6077<table>
6078  <tr>
6079    <th>Constant</th>
6080    <th>Description</th>
6081  </tr>
6082  <tr>
6083    <td><code>defaultCoreCipherList</code></td>
6084    <td>Specifies the built-in default cipher list used by Node.js.</td>
6085  </tr>
6086  <tr>
6087    <td><code>defaultCipherList</code></td>
6088    <td>Specifies the active default cipher list used by the current Node.js
6089    process.</td>
6090  </tr>
6091</table>
6092
6093[AEAD algorithms]: https://en.wikipedia.org/wiki/Authenticated_encryption
6094[CCM mode]: #ccm-mode
6095[CVE-2021-44532]: https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532
6096[Caveats]: #support-for-weak-or-compromised-algorithms
6097[Crypto constants]: #crypto-constants
6098[FIPS module configuration file]: https://www.openssl.org/docs/man3.0/man5/fips_config.html
6099[FIPS provider from OpenSSL 3]: https://www.openssl.org/docs/man3.0/man7/crypto.html#FIPS-provider
6100[HTML 5.2]: https://www.w3.org/TR/html52/changes.html#features-removed
6101[JWK]: https://tools.ietf.org/html/rfc7517
6102[NIST SP 800-131A]: https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf
6103[NIST SP 800-132]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf
6104[NIST SP 800-38D]: https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-38d.pdf
6105[Nonce-Disrespecting Adversaries]: https://github.com/nonce-disrespect/nonce-disrespect
6106[OpenSSL's FIPS README file]: https://github.com/openssl/openssl/blob/openssl-3.0/README-FIPS.md
6107[OpenSSL's SPKAC implementation]: https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html
6108[RFC 1421]: https://www.rfc-editor.org/rfc/rfc1421.txt
6109[RFC 2409]: https://www.rfc-editor.org/rfc/rfc2409.txt
6110[RFC 2818]: https://www.rfc-editor.org/rfc/rfc2818.txt
6111[RFC 3526]: https://www.rfc-editor.org/rfc/rfc3526.txt
6112[RFC 3610]: https://www.rfc-editor.org/rfc/rfc3610.txt
6113[RFC 4055]: https://www.rfc-editor.org/rfc/rfc4055.txt
6114[RFC 4122]: https://www.rfc-editor.org/rfc/rfc4122.txt
6115[RFC 5208]: https://www.rfc-editor.org/rfc/rfc5208.txt
6116[RFC 5280]: https://www.rfc-editor.org/rfc/rfc5280.txt
6117[Web Crypto API documentation]: webcrypto.md
6118[`BN_is_prime_ex`]: https://www.openssl.org/docs/man1.1.1/man3/BN_is_prime_ex.html
6119[`Buffer`]: buffer.md
6120[`DH_generate_key()`]: https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html
6121[`DiffieHellmanGroup`]: #class-diffiehellmangroup
6122[`EVP_BytesToKey`]: https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html
6123[`KeyObject`]: #class-keyobject
6124[`Sign`]: #class-sign
6125[`String.prototype.normalize()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/normalize
6126[`UV_THREADPOOL_SIZE`]: cli.md#uv_threadpool_sizesize
6127[`Verify`]: #class-verify
6128[`cipher.final()`]: #cipherfinaloutputencoding
6129[`cipher.update()`]: #cipherupdatedata-inputencoding-outputencoding
6130[`crypto.createCipher()`]: #cryptocreatecipheralgorithm-password-options
6131[`crypto.createCipheriv()`]: #cryptocreatecipherivalgorithm-key-iv-options
6132[`crypto.createDecipher()`]: #cryptocreatedecipheralgorithm-password-options
6133[`crypto.createDecipheriv()`]: #cryptocreatedecipherivalgorithm-key-iv-options
6134[`crypto.createDiffieHellman()`]: #cryptocreatediffiehellmanprime-primeencoding-generator-generatorencoding
6135[`crypto.createECDH()`]: #cryptocreateecdhcurvename
6136[`crypto.createHash()`]: #cryptocreatehashalgorithm-options
6137[`crypto.createHmac()`]: #cryptocreatehmacalgorithm-key-options
6138[`crypto.createPrivateKey()`]: #cryptocreateprivatekeykey
6139[`crypto.createPublicKey()`]: #cryptocreatepublickeykey
6140[`crypto.createSecretKey()`]: #cryptocreatesecretkeykey-encoding
6141[`crypto.createSign()`]: #cryptocreatesignalgorithm-options
6142[`crypto.createVerify()`]: #cryptocreateverifyalgorithm-options
6143[`crypto.generateKey()`]: #cryptogeneratekeytype-options-callback
6144[`crypto.getCurves()`]: #cryptogetcurves
6145[`crypto.getDiffieHellman()`]: #cryptogetdiffiehellmangroupname
6146[`crypto.getHashes()`]: #cryptogethashes
6147[`crypto.privateDecrypt()`]: #cryptoprivatedecryptprivatekey-buffer
6148[`crypto.privateEncrypt()`]: #cryptoprivateencryptprivatekey-buffer
6149[`crypto.publicDecrypt()`]: #cryptopublicdecryptkey-buffer
6150[`crypto.publicEncrypt()`]: #cryptopublicencryptkey-buffer
6151[`crypto.randomBytes()`]: #cryptorandombytessize-callback
6152[`crypto.randomFill()`]: #cryptorandomfillbuffer-offset-size-callback
6153[`crypto.scrypt()`]: #cryptoscryptpassword-salt-keylen-options-callback
6154[`crypto.webcrypto.getRandomValues()`]: webcrypto.md#cryptogetrandomvaluestypedarray
6155[`crypto.webcrypto.subtle`]: webcrypto.md#class-subtlecrypto
6156[`decipher.final()`]: #decipherfinaloutputencoding
6157[`decipher.update()`]: #decipherupdatedata-inputencoding-outputencoding
6158[`diffieHellman.generateKeys()`]: #diffiehellmangeneratekeysencoding
6159[`diffieHellman.setPublicKey()`]: #diffiehellmansetpublickeypublickey-encoding
6160[`ecdh.generateKeys()`]: #ecdhgeneratekeysencoding-format
6161[`ecdh.setPrivateKey()`]: #ecdhsetprivatekeyprivatekey-encoding
6162[`hash.digest()`]: #hashdigestencoding
6163[`hash.update()`]: #hashupdatedata-inputencoding
6164[`hmac.digest()`]: #hmacdigestencoding
6165[`hmac.update()`]: #hmacupdatedata-inputencoding
6166[`import()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import
6167[`keyObject.export()`]: #keyobjectexportoptions
6168[`postMessage()`]: worker_threads.md#portpostmessagevalue-transferlist
6169[`sign.sign()`]: #signsignprivatekey-outputencoding
6170[`sign.update()`]: #signupdatedata-inputencoding
6171[`stream.Writable` options]: stream.md#new-streamwritableoptions
6172[`stream.transform` options]: stream.md#new-streamtransformoptions
6173[`util.promisify()`]: util.md#utilpromisifyoriginal
6174[`verify.update()`]: #verifyupdatedata-inputencoding
6175[`verify.verify()`]: #verifyverifyobject-signature-signatureencoding
6176[`x509.fingerprint256`]: #x509fingerprint256
6177[caveats when using strings as inputs to cryptographic APIs]: #using-strings-as-inputs-to-cryptographic-apis
6178[certificate object]: tls.md#certificate-object
6179[encoding]: buffer.md#buffers-and-character-encodings
6180[initialization vector]: https://en.wikipedia.org/wiki/Initialization_vector
6181[legacy provider]: cli.md#--openssl-legacy-provider
6182[list of SSL OP Flags]: https://wiki.openssl.org/index.php/List_of_SSL_OP_Flags#Table_of_Options
6183[modulo bias]: https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias
6184[safe integers]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger
6185[scrypt]: https://en.wikipedia.org/wiki/Scrypt
6186[stream]: stream.md
6187[stream-writable-write]: stream.md#writablewritechunk-encoding-callback
6188