@aligent/cdk-prerender-proxy 0.2.4 → 0.2.5-beta

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (150) hide show
  1. package/lib/handlers/cache-control.ts +7 -20
  2. package/lib/handlers/error-response.ts +8 -51
  3. package/lib/handlers/node_modules/.package-lock.json +32 -3
  4. package/lib/handlers/node_modules/@aligent/cdk-lambda-at-edge-handlers/index.d.ts +6 -0
  5. package/lib/handlers/node_modules/@aligent/cdk-lambda-at-edge-handlers/index.js +14 -0
  6. package/lib/handlers/node_modules/@aligent/cdk-lambda-at-edge-handlers/lib/cache-control.d.ts +3 -0
  7. package/lib/handlers/node_modules/@aligent/cdk-lambda-at-edge-handlers/lib/cache-control.js +24 -0
  8. package/lib/handlers/node_modules/@aligent/cdk-lambda-at-edge-handlers/lib/error-response.d.ts +3 -0
  9. package/lib/handlers/node_modules/@aligent/cdk-lambda-at-edge-handlers/lib/error-response.js +50 -0
  10. package/lib/handlers/node_modules/@aligent/cdk-lambda-at-edge-handlers/lib/prerender-check.d.ts +3 -0
  11. package/lib/handlers/node_modules/@aligent/cdk-lambda-at-edge-handlers/lib/prerender-check.js +28 -0
  12. package/lib/handlers/node_modules/@aligent/cdk-lambda-at-edge-handlers/lib/prerender.d.ts +3 -0
  13. package/lib/handlers/node_modules/@aligent/cdk-lambda-at-edge-handlers/lib/prerender.js +49 -0
  14. package/lib/handlers/node_modules/@aligent/cdk-lambda-at-edge-handlers/lib/redirect.d.ts +3 -0
  15. package/lib/handlers/node_modules/@aligent/cdk-lambda-at-edge-handlers/lib/redirect.js +33 -0
  16. package/lib/handlers/node_modules/@aligent/cdk-lambda-at-edge-handlers/package.json +27 -0
  17. package/lib/handlers/node_modules/@aligent/cdk-lambda-at-edge-handlers/tsconfig.json +3 -0
  18. package/lib/handlers/node_modules/@middy/core/LICENSE +21 -0
  19. package/lib/handlers/node_modules/@middy/core/README.md +65 -0
  20. package/lib/handlers/node_modules/@middy/core/index.cjs +207 -0
  21. package/lib/handlers/node_modules/@middy/core/index.d.ts +91 -0
  22. package/lib/handlers/node_modules/@middy/core/index.js +199 -0
  23. package/lib/handlers/node_modules/@middy/core/package.json +65 -0
  24. package/lib/handlers/node_modules/@types/node/README.md +4 -4
  25. package/lib/handlers/node_modules/@types/node/assert/strict.d.ts +5 -1
  26. package/lib/handlers/node_modules/@types/node/assert.d.ts +904 -67
  27. package/lib/handlers/node_modules/@types/node/async_hooks.d.ts +371 -96
  28. package/lib/handlers/node_modules/@types/node/buffer.d.ts +2199 -25
  29. package/lib/handlers/node_modules/@types/node/child_process.d.ts +1151 -308
  30. package/lib/handlers/node_modules/@types/node/cluster.d.ts +356 -208
  31. package/lib/handlers/node_modules/@types/node/console.d.ts +324 -45
  32. package/lib/handlers/node_modules/@types/node/constants.d.ts +8 -3
  33. package/lib/handlers/node_modules/@types/node/crypto.d.ts +3230 -846
  34. package/lib/handlers/node_modules/@types/node/dgram.d.ts +478 -74
  35. package/lib/handlers/node_modules/@types/node/diagnostics_channel.d.ts +153 -0
  36. package/lib/handlers/node_modules/@types/node/dns/promises.d.ts +308 -35
  37. package/lib/handlers/node_modules/@types/node/dns.d.ts +444 -107
  38. package/lib/handlers/node_modules/@types/node/dom-events.d.ts +126 -0
  39. package/lib/handlers/node_modules/@types/node/domain.d.ts +162 -16
  40. package/lib/handlers/node_modules/@types/node/events.d.ts +624 -39
  41. package/lib/handlers/node_modules/@types/node/fs/promises.d.ts +911 -365
  42. package/lib/handlers/node_modules/@types/node/fs.d.ts +2611 -978
  43. package/lib/handlers/node_modules/@types/node/globals.d.ts +66 -421
  44. package/lib/handlers/node_modules/@types/node/globals.global.d.ts +1 -1
  45. package/lib/handlers/node_modules/@types/node/http.d.ts +1416 -199
  46. package/lib/handlers/node_modules/@types/node/http2.d.ts +1688 -530
  47. package/lib/handlers/node_modules/@types/node/https.d.ts +532 -26
  48. package/lib/handlers/node_modules/@types/node/index.d.ts +92 -16
  49. package/lib/handlers/node_modules/@types/node/inspector.d.ts +511 -811
  50. package/lib/handlers/node_modules/@types/node/module.d.ts +75 -13
  51. package/lib/handlers/node_modules/@types/node/net.d.ts +710 -167
  52. package/lib/handlers/node_modules/@types/node/os.d.ts +252 -25
  53. package/lib/handlers/node_modules/@types/node/package.json +30 -25
  54. package/lib/handlers/node_modules/@types/node/path.d.ts +59 -31
  55. package/lib/handlers/node_modules/@types/node/perf_hooks.d.ts +420 -105
  56. package/lib/handlers/node_modules/@types/node/process.d.ts +1249 -228
  57. package/lib/handlers/node_modules/@types/node/punycode.d.ts +67 -25
  58. package/lib/handlers/node_modules/@types/node/querystring.d.ts +113 -10
  59. package/lib/handlers/node_modules/@types/node/readline/promises.d.ts +143 -0
  60. package/lib/handlers/node_modules/@types/node/readline.d.ts +570 -109
  61. package/lib/handlers/node_modules/@types/node/repl.d.ts +154 -125
  62. package/lib/handlers/node_modules/@types/node/stream/consumers.d.ts +12 -0
  63. package/lib/handlers/node_modules/@types/node/stream/promises.d.ts +18 -43
  64. package/lib/handlers/node_modules/@types/node/stream/web.d.ts +330 -0
  65. package/lib/handlers/node_modules/@types/node/stream.d.ts +1117 -248
  66. package/lib/handlers/node_modules/@types/node/string_decoder.d.ts +60 -0
  67. package/lib/handlers/node_modules/@types/node/test.d.ts +446 -0
  68. package/lib/handlers/node_modules/@types/node/timers/promises.d.ts +81 -9
  69. package/lib/handlers/node_modules/@types/node/timers.d.ts +84 -17
  70. package/lib/handlers/node_modules/@types/node/tls.d.ts +510 -275
  71. package/lib/handlers/node_modules/@types/node/trace_events.d.ts +120 -10
  72. package/lib/handlers/node_modules/@types/node/ts4.8/assert/strict.d.ts +8 -0
  73. package/lib/handlers/node_modules/@types/node/ts4.8/assert.d.ts +961 -0
  74. package/lib/handlers/node_modules/@types/node/ts4.8/async_hooks.d.ts +501 -0
  75. package/lib/handlers/node_modules/@types/node/ts4.8/buffer.d.ts +2259 -0
  76. package/lib/handlers/node_modules/@types/node/ts4.8/child_process.d.ts +1369 -0
  77. package/lib/handlers/node_modules/@types/node/ts4.8/cluster.d.ts +410 -0
  78. package/lib/handlers/node_modules/@types/node/ts4.8/console.d.ts +412 -0
  79. package/lib/handlers/node_modules/@types/node/ts4.8/constants.d.ts +18 -0
  80. package/lib/handlers/node_modules/@types/node/ts4.8/crypto.d.ts +3964 -0
  81. package/lib/handlers/node_modules/@types/node/ts4.8/dgram.d.ts +545 -0
  82. package/lib/handlers/node_modules/@types/node/ts4.8/diagnostics_channel.d.ts +153 -0
  83. package/lib/handlers/node_modules/@types/node/ts4.8/dns/promises.d.ts +370 -0
  84. package/lib/handlers/node_modules/@types/node/ts4.8/dns.d.ts +659 -0
  85. package/lib/handlers/node_modules/@types/node/ts4.8/dom-events.d.ts +126 -0
  86. package/lib/handlers/node_modules/@types/node/ts4.8/domain.d.ts +170 -0
  87. package/lib/handlers/node_modules/@types/node/ts4.8/events.d.ts +678 -0
  88. package/lib/handlers/node_modules/@types/node/ts4.8/fs/promises.d.ts +1138 -0
  89. package/lib/handlers/node_modules/@types/node/ts4.8/fs.d.ts +3872 -0
  90. package/lib/handlers/node_modules/@types/node/ts4.8/globals.d.ts +294 -0
  91. package/lib/handlers/node_modules/@types/node/ts4.8/globals.global.d.ts +1 -0
  92. package/lib/handlers/node_modules/@types/node/ts4.8/http.d.ts +1651 -0
  93. package/lib/handlers/node_modules/@types/node/ts4.8/http2.d.ts +2134 -0
  94. package/lib/handlers/node_modules/@types/node/ts4.8/https.d.ts +542 -0
  95. package/lib/handlers/node_modules/@types/node/ts4.8/index.d.ts +88 -0
  96. package/lib/handlers/node_modules/@types/node/ts4.8/inspector.d.ts +2741 -0
  97. package/lib/handlers/node_modules/@types/node/ts4.8/module.d.ts +114 -0
  98. package/lib/handlers/node_modules/@types/node/ts4.8/net.d.ts +869 -0
  99. package/lib/handlers/node_modules/@types/node/ts4.8/os.d.ts +466 -0
  100. package/lib/handlers/node_modules/@types/node/ts4.8/path.d.ts +191 -0
  101. package/lib/handlers/node_modules/@types/node/ts4.8/perf_hooks.d.ts +625 -0
  102. package/lib/handlers/node_modules/@types/node/ts4.8/process.d.ts +1482 -0
  103. package/lib/handlers/node_modules/@types/node/ts4.8/punycode.d.ts +117 -0
  104. package/lib/handlers/node_modules/@types/node/ts4.8/querystring.d.ts +131 -0
  105. package/lib/handlers/node_modules/@types/node/ts4.8/readline/promises.d.ts +143 -0
  106. package/lib/handlers/node_modules/@types/node/ts4.8/readline.d.ts +653 -0
  107. package/lib/handlers/node_modules/@types/node/ts4.8/repl.d.ts +424 -0
  108. package/lib/handlers/node_modules/@types/node/ts4.8/stream/consumers.d.ts +12 -0
  109. package/lib/handlers/node_modules/@types/node/ts4.8/stream/promises.d.ts +42 -0
  110. package/lib/handlers/node_modules/@types/node/ts4.8/stream/web.d.ts +330 -0
  111. package/lib/handlers/node_modules/@types/node/ts4.8/stream.d.ts +1340 -0
  112. package/lib/handlers/node_modules/@types/node/ts4.8/string_decoder.d.ts +67 -0
  113. package/lib/handlers/node_modules/@types/node/ts4.8/test.d.ts +446 -0
  114. package/lib/handlers/node_modules/@types/node/ts4.8/timers/promises.d.ts +93 -0
  115. package/lib/handlers/node_modules/@types/node/ts4.8/timers.d.ts +94 -0
  116. package/lib/handlers/node_modules/@types/node/ts4.8/tls.d.ts +1028 -0
  117. package/lib/handlers/node_modules/@types/node/ts4.8/trace_events.d.ts +171 -0
  118. package/lib/handlers/node_modules/@types/node/ts4.8/tty.d.ts +206 -0
  119. package/lib/handlers/node_modules/@types/node/ts4.8/url.d.ts +897 -0
  120. package/lib/handlers/node_modules/@types/node/ts4.8/util.d.ts +1926 -0
  121. package/lib/handlers/node_modules/@types/node/ts4.8/v8.d.ts +396 -0
  122. package/lib/handlers/node_modules/@types/node/ts4.8/vm.d.ts +509 -0
  123. package/lib/handlers/node_modules/@types/node/ts4.8/wasi.d.ts +158 -0
  124. package/lib/handlers/node_modules/@types/node/ts4.8/worker_threads.d.ts +689 -0
  125. package/lib/handlers/node_modules/@types/node/ts4.8/zlib.d.ts +517 -0
  126. package/lib/handlers/node_modules/@types/node/tty.d.ts +163 -23
  127. package/lib/handlers/node_modules/@types/node/url.d.ts +825 -44
  128. package/lib/handlers/node_modules/@types/node/util.d.ts +1842 -72
  129. package/lib/handlers/node_modules/@types/node/v8.d.ts +276 -78
  130. package/lib/handlers/node_modules/@types/node/vm.d.ts +410 -53
  131. package/lib/handlers/node_modules/@types/node/wasi.d.ts +102 -30
  132. package/lib/handlers/node_modules/@types/node/worker_threads.d.ts +559 -152
  133. package/lib/handlers/node_modules/@types/node/zlib.d.ts +234 -78
  134. package/lib/handlers/node_modules/esbuild/README.md +3 -0
  135. package/lib/handlers/node_modules/esbuild/bin/esbuild +0 -0
  136. package/lib/handlers/node_modules/esbuild/install.js +256 -0
  137. package/lib/handlers/node_modules/esbuild/lib/main.d.ts +397 -0
  138. package/lib/handlers/node_modules/esbuild/lib/main.js +1939 -0
  139. package/lib/handlers/node_modules/esbuild/package.json +15 -0
  140. package/lib/handlers/package-lock.json +62 -6
  141. package/lib/handlers/package.json +6 -1
  142. package/lib/handlers/prerender-check.ts +8 -27
  143. package/lib/handlers/prerender.ts +8 -43
  144. package/package.json +1 -1
  145. package/lib/handlers/node_modules/@types/node/base.d.ts +0 -19
  146. package/lib/handlers/node_modules/@types/node/diagnostic_channel.d.ts +0 -34
  147. package/lib/handlers/node_modules/@types/node/ts3.6/assert.d.ts +0 -98
  148. package/lib/handlers/node_modules/@types/node/ts3.6/base.d.ts +0 -68
  149. package/lib/handlers/node_modules/@types/node/ts3.6/index.d.ts +0 -7
  150. package/lib/handlers/node_modules/@types/node/util/types.d.ts +0 -53
@@ -1,8 +1,76 @@
1
+ /**
2
+ * The `crypto` module provides cryptographic functionality that includes a set of
3
+ * wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.
4
+ *
5
+ * ```js
6
+ * const { createHmac } = await import('crypto');
7
+ *
8
+ * const secret = 'abcdefg';
9
+ * const hash = createHmac('sha256', secret)
10
+ * .update('I love cupcakes')
11
+ * .digest('hex');
12
+ * console.log(hash);
13
+ * // Prints:
14
+ * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
15
+ * ```
16
+ * @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/crypto.js)
17
+ */
1
18
  declare module 'crypto' {
2
- import * as stream from 'stream';
3
- import { PeerCertificate } from 'tls';
4
-
5
- interface Certificate {
19
+ import * as stream from 'node:stream';
20
+ import { PeerCertificate } from 'node:tls';
21
+ /**
22
+ * SPKAC is a Certificate Signing Request mechanism originally implemented by
23
+ * Netscape and was specified formally as part of [HTML5's `keygen` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen).
24
+ *
25
+ * `<keygen>` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects
26
+ * should not use this element anymore.
27
+ *
28
+ * The `crypto` module provides the `Certificate` class for working with SPKAC
29
+ * data. The most common usage is handling output generated by the HTML5`<keygen>` element. Node.js uses [OpenSSL's SPKAC
30
+ * implementation](https://www.openssl.org/docs/man1.1.0/apps/openssl-spkac.html) internally.
31
+ * @since v0.11.8
32
+ */
33
+ class Certificate {
34
+ /**
35
+ * ```js
36
+ * const { Certificate } = await import('crypto');
37
+ * const spkac = getSpkacSomehow();
38
+ * const challenge = Certificate.exportChallenge(spkac);
39
+ * console.log(challenge.toString('utf8'));
40
+ * // Prints: the challenge as a UTF8 string
41
+ * ```
42
+ * @since v9.0.0
43
+ * @param encoding The `encoding` of the `spkac` string.
44
+ * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge.
45
+ */
46
+ static exportChallenge(spkac: BinaryLike): Buffer;
47
+ /**
48
+ * ```js
49
+ * const { Certificate } = await import('crypto');
50
+ * const spkac = getSpkacSomehow();
51
+ * const publicKey = Certificate.exportPublicKey(spkac);
52
+ * console.log(publicKey);
53
+ * // Prints: the public key as <Buffer ...>
54
+ * ```
55
+ * @since v9.0.0
56
+ * @param encoding The `encoding` of the `spkac` string.
57
+ * @return The public key component of the `spkac` data structure, which includes a public key and a challenge.
58
+ */
59
+ static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer;
60
+ /**
61
+ * ```js
62
+ * import { Buffer } from 'buffer';
63
+ * const { Certificate } = await import('crypto');
64
+ *
65
+ * const spkac = getSpkacSomehow();
66
+ * console.log(Certificate.verifySpkac(Buffer.from(spkac)));
67
+ * // Prints: true or false
68
+ * ```
69
+ * @since v9.0.0
70
+ * @param encoding The `encoding` of the `spkac` string.
71
+ * @return `true` if the given `spkac` data structure is valid, `false` otherwise.
72
+ */
73
+ static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean;
6
74
  /**
7
75
  * @deprecated
8
76
  * @param spkac
@@ -26,37 +94,9 @@ declare module 'crypto' {
26
94
  */
27
95
  verifySpkac(spkac: NodeJS.ArrayBufferView): boolean;
28
96
  }
29
- const Certificate: Certificate & {
30
- /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */
31
- new(): Certificate;
32
- /** @deprecated since v14.9.0 - Use static methods of `crypto.Certificate` instead. */
33
- (): Certificate;
34
-
35
- /**
36
- * @param spkac
37
- * @returns The challenge component of the `spkac` data structure,
38
- * which includes a public key and a challenge.
39
- */
40
- exportChallenge(spkac: BinaryLike): Buffer;
41
- /**
42
- * @param spkac
43
- * @param encoding The encoding of the spkac string.
44
- * @returns The public key component of the `spkac` data structure,
45
- * which includes a public key and a challenge.
46
- */
47
- exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer;
48
- /**
49
- * @param spkac
50
- * @returns `true` if the given `spkac` data structure is valid,
51
- * `false` otherwise.
52
- */
53
- verifySpkac(spkac: NodeJS.ArrayBufferView): boolean;
54
- };
55
-
56
97
  namespace constants {
57
98
  // https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants
58
99
  const OPENSSL_VERSION_NUMBER: number;
59
-
60
100
  /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */
61
101
  const SSL_OP_ALL: number;
62
102
  /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */
@@ -106,7 +146,6 @@ declare module 'crypto' {
106
146
  const SSL_OP_TLS_D5_BUG: number;
107
147
  /** Instructs OpenSSL to disable version rollback attack detection. */
108
148
  const SSL_OP_TLS_ROLLBACK_BUG: number;
109
-
110
149
  const ENGINE_METHOD_RSA: number;
111
150
  const ENGINE_METHOD_DSA: number;
112
151
  const ENGINE_METHOD_DH: number;
@@ -118,14 +157,11 @@ declare module 'crypto' {
118
157
  const ENGINE_METHOD_PKEY_ASN1_METHS: number;
119
158
  const ENGINE_METHOD_ALL: number;
120
159
  const ENGINE_METHOD_NONE: number;
121
-
122
160
  const DH_CHECK_P_NOT_SAFE_PRIME: number;
123
161
  const DH_CHECK_P_NOT_PRIME: number;
124
162
  const DH_UNABLE_TO_CHECK_GENERATOR: number;
125
163
  const DH_NOT_SUITABLE_GENERATOR: number;
126
-
127
164
  const ALPN_ENABLED: number;
128
-
129
165
  const RSA_PKCS1_PADDING: number;
130
166
  const RSA_SSLV23_PADDING: number;
131
167
  const RSA_NO_PADDING: number;
@@ -138,544 +174,2263 @@ declare module 'crypto' {
138
174
  const RSA_PSS_SALTLEN_MAX_SIGN: number;
139
175
  /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */
140
176
  const RSA_PSS_SALTLEN_AUTO: number;
141
-
142
177
  const POINT_CONVERSION_COMPRESSED: number;
143
178
  const POINT_CONVERSION_UNCOMPRESSED: number;
144
179
  const POINT_CONVERSION_HYBRID: number;
145
-
146
180
  /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */
147
181
  const defaultCoreCipherList: string;
148
182
  /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */
149
183
  const defaultCipherList: string;
150
184
  }
151
-
152
185
  interface HashOptions extends stream.TransformOptions {
153
186
  /**
154
187
  * For XOF hash functions such as `shake256`, the
155
188
  * outputLength option can be used to specify the desired output length in bytes.
156
189
  */
157
- outputLength?: number;
190
+ outputLength?: number | undefined;
158
191
  }
159
-
160
192
  /** @deprecated since v10.0.0 */
161
193
  const fips: boolean;
162
-
194
+ /**
195
+ * Creates and returns a `Hash` object that can be used to generate hash digests
196
+ * using the given `algorithm`. Optional `options` argument controls stream
197
+ * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option
198
+ * can be used to specify the desired output length in bytes.
199
+ *
200
+ * The `algorithm` is dependent on the available algorithms supported by the
201
+ * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
202
+ * On recent releases of OpenSSL, `openssl list -digest-algorithms` will
203
+ * display the available digest algorithms.
204
+ *
205
+ * Example: generating the sha256 sum of a file
206
+ *
207
+ * ```js
208
+ * import {
209
+ * createReadStream
210
+ * } from 'fs';
211
+ * import { argv } from 'process';
212
+ * const {
213
+ * createHash
214
+ * } = await import('crypto');
215
+ *
216
+ * const filename = argv[2];
217
+ *
218
+ * const hash = createHash('sha256');
219
+ *
220
+ * const input = createReadStream(filename);
221
+ * input.on('readable', () => {
222
+ * // Only one element is going to be produced by the
223
+ * // hash stream.
224
+ * const data = input.read();
225
+ * if (data)
226
+ * hash.update(data);
227
+ * else {
228
+ * console.log(`${hash.digest('hex')} ${filename}`);
229
+ * }
230
+ * });
231
+ * ```
232
+ * @since v0.1.92
233
+ * @param options `stream.transform` options
234
+ */
163
235
  function createHash(algorithm: string, options?: HashOptions): Hash;
236
+ /**
237
+ * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`.
238
+ * Optional `options` argument controls stream behavior.
239
+ *
240
+ * The `algorithm` is dependent on the available algorithms supported by the
241
+ * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
242
+ * On recent releases of OpenSSL, `openssl list -digest-algorithms` will
243
+ * display the available digest algorithms.
244
+ *
245
+ * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is
246
+ * a `KeyObject`, its type must be `secret`.
247
+ *
248
+ * Example: generating the sha256 HMAC of a file
249
+ *
250
+ * ```js
251
+ * import {
252
+ * createReadStream
253
+ * } from 'fs';
254
+ * import { argv } from 'process';
255
+ * const {
256
+ * createHmac
257
+ * } = await import('crypto');
258
+ *
259
+ * const filename = argv[2];
260
+ *
261
+ * const hmac = createHmac('sha256', 'a secret');
262
+ *
263
+ * const input = createReadStream(filename);
264
+ * input.on('readable', () => {
265
+ * // Only one element is going to be produced by the
266
+ * // hash stream.
267
+ * const data = input.read();
268
+ * if (data)
269
+ * hmac.update(data);
270
+ * else {
271
+ * console.log(`${hmac.digest('hex')} ${filename}`);
272
+ * }
273
+ * });
274
+ * ```
275
+ * @since v0.1.94
276
+ * @param options `stream.transform` options
277
+ */
164
278
  function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac;
165
-
166
279
  // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
167
- type BinaryToTextEncoding = 'base64' | 'hex';
280
+ type BinaryToTextEncoding = 'base64' | 'base64url' | 'hex' | 'binary';
168
281
  type CharacterEncoding = 'utf8' | 'utf-8' | 'utf16le' | 'latin1';
169
282
  type LegacyCharacterEncoding = 'ascii' | 'binary' | 'ucs2' | 'ucs-2';
170
-
171
283
  type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding;
172
-
173
284
  type ECDHKeyFormat = 'compressed' | 'uncompressed' | 'hybrid';
174
-
285
+ /**
286
+ * The `Hash` class is a utility for creating hash digests of data. It can be
287
+ * used in one of two ways:
288
+ *
289
+ * * As a `stream` that is both readable and writable, where data is written
290
+ * to produce a computed hash digest on the readable side, or
291
+ * * Using the `hash.update()` and `hash.digest()` methods to produce the
292
+ * computed hash.
293
+ *
294
+ * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword.
295
+ *
296
+ * Example: Using `Hash` objects as streams:
297
+ *
298
+ * ```js
299
+ * const {
300
+ * createHash
301
+ * } = await import('crypto');
302
+ *
303
+ * const hash = createHash('sha256');
304
+ *
305
+ * hash.on('readable', () => {
306
+ * // Only one element is going to be produced by the
307
+ * // hash stream.
308
+ * const data = hash.read();
309
+ * if (data) {
310
+ * console.log(data.toString('hex'));
311
+ * // Prints:
312
+ * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
313
+ * }
314
+ * });
315
+ *
316
+ * hash.write('some data to hash');
317
+ * hash.end();
318
+ * ```
319
+ *
320
+ * Example: Using `Hash` and piped streams:
321
+ *
322
+ * ```js
323
+ * import { createReadStream } from 'fs';
324
+ * import { stdout } from 'process';
325
+ * const { createHash } = await import('crypto');
326
+ *
327
+ * const hash = createHash('sha256');
328
+ *
329
+ * const input = createReadStream('test.js');
330
+ * input.pipe(hash).setEncoding('hex').pipe(stdout);
331
+ * ```
332
+ *
333
+ * Example: Using the `hash.update()` and `hash.digest()` methods:
334
+ *
335
+ * ```js
336
+ * const {
337
+ * createHash
338
+ * } = await import('crypto');
339
+ *
340
+ * const hash = createHash('sha256');
341
+ *
342
+ * hash.update('some data to hash');
343
+ * console.log(hash.digest('hex'));
344
+ * // Prints:
345
+ * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
346
+ * ```
347
+ * @since v0.1.92
348
+ */
175
349
  class Hash extends stream.Transform {
176
350
  private constructor();
177
- copy(): Hash;
351
+ /**
352
+ * Creates a new `Hash` object that contains a deep copy of the internal state
353
+ * of the current `Hash` object.
354
+ *
355
+ * The optional `options` argument controls stream behavior. For XOF hash
356
+ * functions such as `'shake256'`, the `outputLength` option can be used to
357
+ * specify the desired output length in bytes.
358
+ *
359
+ * An error is thrown when an attempt is made to copy the `Hash` object after
360
+ * its `hash.digest()` method has been called.
361
+ *
362
+ * ```js
363
+ * // Calculate a rolling hash.
364
+ * const {
365
+ * createHash
366
+ * } = await import('crypto');
367
+ *
368
+ * const hash = createHash('sha256');
369
+ *
370
+ * hash.update('one');
371
+ * console.log(hash.copy().digest('hex'));
372
+ *
373
+ * hash.update('two');
374
+ * console.log(hash.copy().digest('hex'));
375
+ *
376
+ * hash.update('three');
377
+ * console.log(hash.copy().digest('hex'));
378
+ *
379
+ * // Etc.
380
+ * ```
381
+ * @since v13.1.0
382
+ * @param options `stream.transform` options
383
+ */
384
+ copy(options?: stream.TransformOptions): Hash;
385
+ /**
386
+ * Updates the hash content with the given `data`, the encoding of which
387
+ * is given in `inputEncoding`.
388
+ * If `encoding` is not provided, and the `data` is a string, an
389
+ * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
390
+ *
391
+ * This can be called many times with new data as it is streamed.
392
+ * @since v0.1.92
393
+ * @param inputEncoding The `encoding` of the `data` string.
394
+ */
178
395
  update(data: BinaryLike): Hash;
179
- update(data: string, input_encoding: Encoding): Hash;
396
+ update(data: string, inputEncoding: Encoding): Hash;
397
+ /**
398
+ * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method).
399
+ * If `encoding` is provided a string will be returned; otherwise
400
+ * a `Buffer` is returned.
401
+ *
402
+ * The `Hash` object can not be used again after `hash.digest()` method has been
403
+ * called. Multiple calls will cause an error to be thrown.
404
+ * @since v0.1.92
405
+ * @param encoding The `encoding` of the return value.
406
+ */
180
407
  digest(): Buffer;
181
408
  digest(encoding: BinaryToTextEncoding): string;
182
409
  }
410
+ /**
411
+ * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can
412
+ * be used in one of two ways:
413
+ *
414
+ * * As a `stream` that is both readable and writable, where data is written
415
+ * to produce a computed HMAC digest on the readable side, or
416
+ * * Using the `hmac.update()` and `hmac.digest()` methods to produce the
417
+ * computed HMAC digest.
418
+ *
419
+ * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword.
420
+ *
421
+ * Example: Using `Hmac` objects as streams:
422
+ *
423
+ * ```js
424
+ * const {
425
+ * createHmac
426
+ * } = await import('crypto');
427
+ *
428
+ * const hmac = createHmac('sha256', 'a secret');
429
+ *
430
+ * hmac.on('readable', () => {
431
+ * // Only one element is going to be produced by the
432
+ * // hash stream.
433
+ * const data = hmac.read();
434
+ * if (data) {
435
+ * console.log(data.toString('hex'));
436
+ * // Prints:
437
+ * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
438
+ * }
439
+ * });
440
+ *
441
+ * hmac.write('some data to hash');
442
+ * hmac.end();
443
+ * ```
444
+ *
445
+ * Example: Using `Hmac` and piped streams:
446
+ *
447
+ * ```js
448
+ * import { createReadStream } from 'fs';
449
+ * import { stdout } from 'process';
450
+ * const {
451
+ * createHmac
452
+ * } = await import('crypto');
453
+ *
454
+ * const hmac = createHmac('sha256', 'a secret');
455
+ *
456
+ * const input = createReadStream('test.js');
457
+ * input.pipe(hmac).pipe(stdout);
458
+ * ```
459
+ *
460
+ * Example: Using the `hmac.update()` and `hmac.digest()` methods:
461
+ *
462
+ * ```js
463
+ * const {
464
+ * createHmac
465
+ * } = await import('crypto');
466
+ *
467
+ * const hmac = createHmac('sha256', 'a secret');
468
+ *
469
+ * hmac.update('some data to hash');
470
+ * console.log(hmac.digest('hex'));
471
+ * // Prints:
472
+ * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
473
+ * ```
474
+ * @since v0.1.94
475
+ */
183
476
  class Hmac extends stream.Transform {
184
477
  private constructor();
478
+ /**
479
+ * Updates the `Hmac` content with the given `data`, the encoding of which
480
+ * is given in `inputEncoding`.
481
+ * If `encoding` is not provided, and the `data` is a string, an
482
+ * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
483
+ *
484
+ * This can be called many times with new data as it is streamed.
485
+ * @since v0.1.94
486
+ * @param inputEncoding The `encoding` of the `data` string.
487
+ */
185
488
  update(data: BinaryLike): Hmac;
186
- update(data: string, input_encoding: Encoding): Hmac;
489
+ update(data: string, inputEncoding: Encoding): Hmac;
490
+ /**
491
+ * Calculates the HMAC digest of all of the data passed using `hmac.update()`.
492
+ * If `encoding` is
493
+ * provided a string is returned; otherwise a `Buffer` is returned;
494
+ *
495
+ * The `Hmac` object can not be used again after `hmac.digest()` has been
496
+ * called. Multiple calls to `hmac.digest()` will result in an error being thrown.
497
+ * @since v0.1.94
498
+ * @param encoding The `encoding` of the return value.
499
+ */
187
500
  digest(): Buffer;
188
501
  digest(encoding: BinaryToTextEncoding): string;
189
502
  }
190
-
191
503
  type KeyObjectType = 'secret' | 'public' | 'private';
192
-
193
504
  interface KeyExportOptions<T extends KeyFormat> {
194
505
  type: 'pkcs1' | 'spki' | 'pkcs8' | 'sec1';
195
506
  format: T;
196
- cipher?: string;
197
- passphrase?: string | Buffer;
507
+ cipher?: string | undefined;
508
+ passphrase?: string | Buffer | undefined;
198
509
  }
199
-
200
510
  interface JwkKeyExportOptions {
201
511
  format: 'jwk';
202
512
  }
203
-
204
513
  interface JsonWebKey {
205
- crv?: string;
206
- d?: string;
207
- dp?: string;
208
- dq?: string;
209
- e?: string;
210
- k?: string;
211
- kty?: string;
212
- n?: string;
213
- p?: string;
214
- q?: string;
215
- qi?: string;
216
- x?: string;
217
- y?: string;
514
+ crv?: string | undefined;
515
+ d?: string | undefined;
516
+ dp?: string | undefined;
517
+ dq?: string | undefined;
518
+ e?: string | undefined;
519
+ k?: string | undefined;
520
+ kty?: string | undefined;
521
+ n?: string | undefined;
522
+ p?: string | undefined;
523
+ q?: string | undefined;
524
+ qi?: string | undefined;
525
+ x?: string | undefined;
526
+ y?: string | undefined;
527
+ [key: string]: unknown;
218
528
  }
219
-
220
529
  interface AsymmetricKeyDetails {
221
530
  /**
222
531
  * Key size in bits (RSA, DSA).
223
532
  */
224
- modulusLength?: number;
533
+ modulusLength?: number | undefined;
225
534
  /**
226
535
  * Public exponent (RSA).
227
536
  */
228
- publicExponent?: bigint;
537
+ publicExponent?: bigint | undefined;
538
+ /**
539
+ * Name of the message digest (RSA-PSS).
540
+ */
541
+ hashAlgorithm?: string | undefined;
542
+ /**
543
+ * Name of the message digest used by MGF1 (RSA-PSS).
544
+ */
545
+ mgf1HashAlgorithm?: string | undefined;
546
+ /**
547
+ * Minimal salt length in bytes (RSA-PSS).
548
+ */
549
+ saltLength?: number | undefined;
229
550
  /**
230
551
  * Size of q in bits (DSA).
231
552
  */
232
- divisorLength?: number;
553
+ divisorLength?: number | undefined;
233
554
  /**
234
555
  * Name of the curve (EC).
235
556
  */
236
- namedCurve?: string;
557
+ namedCurve?: string | undefined;
237
558
  }
238
-
559
+ /**
560
+ * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key,
561
+ * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject`
562
+ * objects are not to be created directly using the `new`keyword.
563
+ *
564
+ * Most applications should consider using the new `KeyObject` API instead of
565
+ * passing keys as strings or `Buffer`s due to improved security features.
566
+ *
567
+ * `KeyObject` instances can be passed to other threads via `postMessage()`.
568
+ * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to
569
+ * be listed in the `transferList` argument.
570
+ * @since v11.6.0
571
+ */
239
572
  class KeyObject {
240
573
  private constructor();
241
- asymmetricKeyType?: KeyType;
574
+ /**
575
+ * Example: Converting a `CryptoKey` instance to a `KeyObject`:
576
+ *
577
+ * ```js
578
+ * const { webcrypto, KeyObject } = await import('crypto');
579
+ * const { subtle } = webcrypto;
580
+ *
581
+ * const key = await subtle.generateKey({
582
+ * name: 'HMAC',
583
+ * hash: 'SHA-256',
584
+ * length: 256
585
+ * }, true, ['sign', 'verify']);
586
+ *
587
+ * const keyObject = KeyObject.from(key);
588
+ * console.log(keyObject.symmetricKeySize);
589
+ * // Prints: 32 (symmetric key size in bytes)
590
+ * ```
591
+ * @since v15.0.0
592
+ */
593
+ static from(key: webcrypto.CryptoKey): KeyObject;
594
+ /**
595
+ * For asymmetric keys, this property represents the type of the key. Supported key
596
+ * types are:
597
+ *
598
+ * * `'rsa'` (OID 1.2.840.113549.1.1.1)
599
+ * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10)
600
+ * * `'dsa'` (OID 1.2.840.10040.4.1)
601
+ * * `'ec'` (OID 1.2.840.10045.2.1)
602
+ * * `'x25519'` (OID 1.3.101.110)
603
+ * * `'x448'` (OID 1.3.101.111)
604
+ * * `'ed25519'` (OID 1.3.101.112)
605
+ * * `'ed448'` (OID 1.3.101.113)
606
+ * * `'dh'` (OID 1.2.840.113549.1.3.1)
607
+ *
608
+ * This property is `undefined` for unrecognized `KeyObject` types and symmetric
609
+ * keys.
610
+ * @since v11.6.0
611
+ */
612
+ asymmetricKeyType?: KeyType | undefined;
242
613
  /**
243
614
  * For asymmetric keys, this property represents the size of the embedded key in
244
615
  * bytes. This property is `undefined` for symmetric keys.
245
616
  */
246
- asymmetricKeySize?: number;
617
+ asymmetricKeySize?: number | undefined;
247
618
  /**
248
619
  * This property exists only on asymmetric keys. Depending on the type of the key,
249
620
  * this object contains information about the key. None of the information obtained
250
- * through this property can be used to uniquely identify a key or to compromise the
251
- * security of the key.
621
+ * through this property can be used to uniquely identify a key or to compromise
622
+ * the security of the key.
623
+ *
624
+ * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence,
625
+ * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be
626
+ * set.
627
+ *
628
+ * Other key details might be exposed via this API using additional attributes.
629
+ * @since v15.7.0
630
+ */
631
+ asymmetricKeyDetails?: AsymmetricKeyDetails | undefined;
632
+ /**
633
+ * For symmetric keys, the following encoding options can be used:
634
+ *
635
+ * For public keys, the following encoding options can be used:
636
+ *
637
+ * For private keys, the following encoding options can be used:
638
+ *
639
+ * The result type depends on the selected encoding format, when PEM the
640
+ * result is a string, when DER it will be a buffer containing the data
641
+ * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object.
642
+ *
643
+ * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are
644
+ * ignored.
645
+ *
646
+ * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of
647
+ * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be
648
+ * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for
649
+ * encrypted private keys. Since PKCS#8 defines its own
650
+ * encryption mechanism, PEM-level encryption is not supported when encrypting
651
+ * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for
652
+ * PKCS#1 and SEC1 encryption.
653
+ * @since v11.6.0
252
654
  */
253
- asymmetricKeyDetails?: AsymmetricKeyDetails;
254
655
  export(options: KeyExportOptions<'pem'>): string | Buffer;
255
656
  export(options?: KeyExportOptions<'der'>): Buffer;
256
- symmetricKeySize?: number;
657
+ export(options?: JwkKeyExportOptions): JsonWebKey;
658
+ /**
659
+ * For secret keys, this property represents the size of the key in bytes. This
660
+ * property is `undefined` for asymmetric keys.
661
+ * @since v11.6.0
662
+ */
663
+ symmetricKeySize?: number | undefined;
664
+ /**
665
+ * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys
666
+ * or `'private'` for private (asymmetric) keys.
667
+ * @since v11.6.0
668
+ */
257
669
  type: KeyObjectType;
258
670
  }
259
-
260
671
  type CipherCCMTypes = 'aes-128-ccm' | 'aes-192-ccm' | 'aes-256-ccm' | 'chacha20-poly1305';
261
672
  type CipherGCMTypes = 'aes-128-gcm' | 'aes-192-gcm' | 'aes-256-gcm';
262
-
673
+ type CipherOCBTypes = 'aes-128-ocb' | 'aes-192-ocb' | 'aes-256-ocb';
263
674
  type BinaryLike = string | NodeJS.ArrayBufferView;
264
-
265
675
  type CipherKey = BinaryLike | KeyObject;
266
-
267
676
  interface CipherCCMOptions extends stream.TransformOptions {
268
677
  authTagLength: number;
269
678
  }
270
679
  interface CipherGCMOptions extends stream.TransformOptions {
271
- authTagLength?: number;
680
+ authTagLength?: number | undefined;
272
681
  }
273
- /** @deprecated since v10.0.0 use `createCipheriv()` */
682
+ interface CipherOCBOptions extends stream.TransformOptions {
683
+ authTagLength: number;
684
+ }
685
+ /**
686
+ * Creates and returns a `Cipher` object that uses the given `algorithm` and`password`.
687
+ *
688
+ * The `options` argument controls stream behavior and is optional except when a
689
+ * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the
690
+ * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication
691
+ * tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
692
+ * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
693
+ *
694
+ * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
695
+ * recent OpenSSL releases, `openssl list -cipher-algorithms` will
696
+ * display the available cipher algorithms.
697
+ *
698
+ * The `password` is used to derive the cipher key and initialization vector (IV).
699
+ * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`.
700
+ *
701
+ * The implementation of `crypto.createCipher()` derives keys using the OpenSSL
702
+ * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one
703
+ * iteration, and no salt. The lack of salt allows dictionary attacks as the same
704
+ * password always creates the same key. The low iteration count and
705
+ * non-cryptographically secure hash algorithm allow passwords to be tested very
706
+ * rapidly.
707
+ *
708
+ * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that
709
+ * developers derive a key and IV on
710
+ * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode
711
+ * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when
712
+ * they are used in order to avoid the risk of IV reuse that causes
713
+ * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details.
714
+ * @since v0.1.94
715
+ * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead.
716
+ * @param options `stream.transform` options
717
+ */
274
718
  function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM;
275
719
  /** @deprecated since v10.0.0 use `createCipheriv()` */
276
720
  function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM;
277
721
  /** @deprecated since v10.0.0 use `createCipheriv()` */
278
722
  function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher;
279
-
280
- function createCipheriv(
281
- algorithm: CipherCCMTypes,
282
- key: CipherKey,
283
- iv: BinaryLike | null,
284
- options: CipherCCMOptions,
285
- ): CipherCCM;
286
- function createCipheriv(
287
- algorithm: CipherGCMTypes,
288
- key: CipherKey,
289
- iv: BinaryLike | null,
290
- options?: CipherGCMOptions,
291
- ): CipherGCM;
292
- function createCipheriv(
293
- algorithm: string,
294
- key: CipherKey,
295
- iv: BinaryLike | null,
296
- options?: stream.TransformOptions,
297
- ): Cipher;
298
-
723
+ /**
724
+ * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and
725
+ * initialization vector (`iv`).
726
+ *
727
+ * The `options` argument controls stream behavior and is optional except when a
728
+ * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the
729
+ * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication
730
+ * tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
731
+ * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
732
+ *
733
+ * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
734
+ * recent OpenSSL releases, `openssl list -cipher-algorithms` will
735
+ * display the available cipher algorithms.
736
+ *
737
+ * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded
738
+ * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be
739
+ * a `KeyObject` of type `secret`. If the cipher does not need
740
+ * an initialization vector, `iv` may be `null`.
741
+ *
742
+ * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`.
743
+ *
744
+ * Initialization vectors should be unpredictable and unique; ideally, they will be
745
+ * cryptographically random. They do not have to be secret: IVs are typically just
746
+ * added to ciphertext messages unencrypted. It may sound contradictory that
747
+ * something has to be unpredictable and unique, but does not have to be secret;
748
+ * remember that an attacker must not be able to predict ahead of time what a
749
+ * given IV will be.
750
+ * @since v0.1.94
751
+ * @param options `stream.transform` options
752
+ */
753
+ function createCipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike, options: CipherCCMOptions): CipherCCM;
754
+ function createCipheriv(algorithm: CipherOCBTypes, key: CipherKey, iv: BinaryLike, options: CipherOCBOptions): CipherOCB;
755
+ function createCipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike, options?: CipherGCMOptions): CipherGCM;
756
+ function createCipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Cipher;
757
+ /**
758
+ * Instances of the `Cipher` class are used to encrypt data. The class can be
759
+ * used in one of two ways:
760
+ *
761
+ * * As a `stream` that is both readable and writable, where plain unencrypted
762
+ * data is written to produce encrypted data on the readable side, or
763
+ * * Using the `cipher.update()` and `cipher.final()` methods to produce
764
+ * the encrypted data.
765
+ *
766
+ * The {@link createCipher} or {@link createCipheriv} methods are
767
+ * used to create `Cipher` instances. `Cipher` objects are not to be created
768
+ * directly using the `new` keyword.
769
+ *
770
+ * Example: Using `Cipher` objects as streams:
771
+ *
772
+ * ```js
773
+ * const {
774
+ * scrypt,
775
+ * randomFill,
776
+ * createCipheriv
777
+ * } = await import('crypto');
778
+ *
779
+ * const algorithm = 'aes-192-cbc';
780
+ * const password = 'Password used to generate key';
781
+ *
782
+ * // First, we'll generate the key. The key length is dependent on the algorithm.
783
+ * // In this case for aes192, it is 24 bytes (192 bits).
784
+ * scrypt(password, 'salt', 24, (err, key) => {
785
+ * if (err) throw err;
786
+ * // Then, we'll generate a random initialization vector
787
+ * randomFill(new Uint8Array(16), (err, iv) => {
788
+ * if (err) throw err;
789
+ *
790
+ * // Once we have the key and iv, we can create and use the cipher...
791
+ * const cipher = createCipheriv(algorithm, key, iv);
792
+ *
793
+ * let encrypted = '';
794
+ * cipher.setEncoding('hex');
795
+ *
796
+ * cipher.on('data', (chunk) => encrypted += chunk);
797
+ * cipher.on('end', () => console.log(encrypted));
798
+ *
799
+ * cipher.write('some clear text data');
800
+ * cipher.end();
801
+ * });
802
+ * });
803
+ * ```
804
+ *
805
+ * Example: Using `Cipher` and piped streams:
806
+ *
807
+ * ```js
808
+ * import {
809
+ * createReadStream,
810
+ * createWriteStream,
811
+ * } from 'fs';
812
+ *
813
+ * import {
814
+ * pipeline
815
+ * } from 'stream';
816
+ *
817
+ * const {
818
+ * scrypt,
819
+ * randomFill,
820
+ * createCipheriv
821
+ * } = await import('crypto');
822
+ *
823
+ * const algorithm = 'aes-192-cbc';
824
+ * const password = 'Password used to generate key';
825
+ *
826
+ * // First, we'll generate the key. The key length is dependent on the algorithm.
827
+ * // In this case for aes192, it is 24 bytes (192 bits).
828
+ * scrypt(password, 'salt', 24, (err, key) => {
829
+ * if (err) throw err;
830
+ * // Then, we'll generate a random initialization vector
831
+ * randomFill(new Uint8Array(16), (err, iv) => {
832
+ * if (err) throw err;
833
+ *
834
+ * const cipher = createCipheriv(algorithm, key, iv);
835
+ *
836
+ * const input = createReadStream('test.js');
837
+ * const output = createWriteStream('test.enc');
838
+ *
839
+ * pipeline(input, cipher, output, (err) => {
840
+ * if (err) throw err;
841
+ * });
842
+ * });
843
+ * });
844
+ * ```
845
+ *
846
+ * Example: Using the `cipher.update()` and `cipher.final()` methods:
847
+ *
848
+ * ```js
849
+ * const {
850
+ * scrypt,
851
+ * randomFill,
852
+ * createCipheriv
853
+ * } = await import('crypto');
854
+ *
855
+ * const algorithm = 'aes-192-cbc';
856
+ * const password = 'Password used to generate key';
857
+ *
858
+ * // First, we'll generate the key. The key length is dependent on the algorithm.
859
+ * // In this case for aes192, it is 24 bytes (192 bits).
860
+ * scrypt(password, 'salt', 24, (err, key) => {
861
+ * if (err) throw err;
862
+ * // Then, we'll generate a random initialization vector
863
+ * randomFill(new Uint8Array(16), (err, iv) => {
864
+ * if (err) throw err;
865
+ *
866
+ * const cipher = createCipheriv(algorithm, key, iv);
867
+ *
868
+ * let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
869
+ * encrypted += cipher.final('hex');
870
+ * console.log(encrypted);
871
+ * });
872
+ * });
873
+ * ```
874
+ * @since v0.1.94
875
+ */
299
876
  class Cipher extends stream.Transform {
300
877
  private constructor();
878
+ /**
879
+ * Updates the cipher with `data`. If the `inputEncoding` argument is given,
880
+ * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or`DataView`. If `data` is a `Buffer`,
881
+ * `TypedArray`, or `DataView`, then`inputEncoding` is ignored.
882
+ *
883
+ * The `outputEncoding` specifies the output format of the enciphered
884
+ * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned.
885
+ *
886
+ * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being
887
+ * thrown.
888
+ * @since v0.1.94
889
+ * @param inputEncoding The `encoding` of the data.
890
+ * @param outputEncoding The `encoding` of the return value.
891
+ */
301
892
  update(data: BinaryLike): Buffer;
302
- update(data: string, input_encoding: Encoding): Buffer;
303
- update(data: NodeJS.ArrayBufferView, input_encoding: undefined, output_encoding: Encoding): string;
304
- update(data: string, input_encoding: Encoding | undefined, output_encoding: Encoding): string;
893
+ update(data: string, inputEncoding: Encoding): Buffer;
894
+ update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string;
895
+ update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string;
896
+ /**
897
+ * Once the `cipher.final()` method has been called, the `Cipher` object can no
898
+ * longer be used to encrypt data. Attempts to call `cipher.final()` more than
899
+ * once will result in an error being thrown.
900
+ * @since v0.1.94
901
+ * @param outputEncoding The `encoding` of the return value.
902
+ * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned.
903
+ */
305
904
  final(): Buffer;
306
- final(output_encoding: BufferEncoding): string;
307
- setAutoPadding(auto_padding?: boolean): this;
308
- // getAuthTag(): Buffer;
309
- // setAAD(buffer: NodeJS.ArrayBufferView): this;
905
+ final(outputEncoding: BufferEncoding): string;
906
+ /**
907
+ * When using block encryption algorithms, the `Cipher` class will automatically
908
+ * add padding to the input data to the appropriate block size. To disable the
909
+ * default padding call `cipher.setAutoPadding(false)`.
910
+ *
911
+ * When `autoPadding` is `false`, the length of the entire input data must be a
912
+ * multiple of the cipher's block size or `cipher.final()` will throw an error.
913
+ * Disabling automatic padding is useful for non-standard padding, for instance
914
+ * using `0x0` instead of PKCS padding.
915
+ *
916
+ * The `cipher.setAutoPadding()` method must be called before `cipher.final()`.
917
+ * @since v0.7.1
918
+ * @param [autoPadding=true]
919
+ * @return for method chaining.
920
+ */
921
+ setAutoPadding(autoPadding?: boolean): this;
310
922
  }
311
923
  interface CipherCCM extends Cipher {
312
- setAAD(buffer: NodeJS.ArrayBufferView, options: { plaintextLength: number }): this;
924
+ setAAD(
925
+ buffer: NodeJS.ArrayBufferView,
926
+ options: {
927
+ plaintextLength: number;
928
+ }
929
+ ): this;
313
930
  getAuthTag(): Buffer;
314
931
  }
315
932
  interface CipherGCM extends Cipher {
316
- setAAD(buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number }): this;
933
+ setAAD(
934
+ buffer: NodeJS.ArrayBufferView,
935
+ options?: {
936
+ plaintextLength: number;
937
+ }
938
+ ): this;
317
939
  getAuthTag(): Buffer;
318
940
  }
319
- /** @deprecated since v10.0.0 use `createDecipheriv()` */
941
+ interface CipherOCB extends Cipher {
942
+ setAAD(
943
+ buffer: NodeJS.ArrayBufferView,
944
+ options?: {
945
+ plaintextLength: number;
946
+ }
947
+ ): this;
948
+ getAuthTag(): Buffer;
949
+ }
950
+ /**
951
+ * Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key).
952
+ *
953
+ * The `options` argument controls stream behavior and is optional except when a
954
+ * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the
955
+ * authentication tag in bytes, see `CCM mode`.
956
+ * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
957
+ *
958
+ * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL
959
+ * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one
960
+ * iteration, and no salt. The lack of salt allows dictionary attacks as the same
961
+ * password always creates the same key. The low iteration count and
962
+ * non-cryptographically secure hash algorithm allow passwords to be tested very
963
+ * rapidly.
964
+ *
965
+ * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) it is recommended that
966
+ * developers derive a key and IV on
967
+ * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object.
968
+ * @since v0.1.94
969
+ * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead.
970
+ * @param options `stream.transform` options
971
+ */
320
972
  function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM;
321
973
  /** @deprecated since v10.0.0 use `createDecipheriv()` */
322
974
  function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM;
323
975
  /** @deprecated since v10.0.0 use `createDecipheriv()` */
324
976
  function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher;
325
-
326
- function createDecipheriv(
327
- algorithm: CipherCCMTypes,
328
- key: CipherKey,
329
- iv: BinaryLike | null,
330
- options: CipherCCMOptions,
331
- ): DecipherCCM;
332
- function createDecipheriv(
333
- algorithm: CipherGCMTypes,
334
- key: CipherKey,
335
- iv: BinaryLike | null,
336
- options?: CipherGCMOptions,
337
- ): DecipherGCM;
338
- function createDecipheriv(
339
- algorithm: string,
340
- key: CipherKey,
341
- iv: BinaryLike | null,
342
- options?: stream.TransformOptions,
343
- ): Decipher;
344
-
977
+ /**
978
+ * Creates and returns a `Decipher` object that uses the given `algorithm`, `key`and initialization vector (`iv`).
979
+ *
980
+ * The `options` argument controls stream behavior and is optional except when a
981
+ * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the
982
+ * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to restrict accepted authentication tags
983
+ * to those with the specified length.
984
+ * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
985
+ *
986
+ * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
987
+ * recent OpenSSL releases, `openssl list -cipher-algorithms` will
988
+ * display the available cipher algorithms.
989
+ *
990
+ * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded
991
+ * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be
992
+ * a `KeyObject` of type `secret`. If the cipher does not need
993
+ * an initialization vector, `iv` may be `null`.
994
+ *
995
+ * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`.
996
+ *
997
+ * Initialization vectors should be unpredictable and unique; ideally, they will be
998
+ * cryptographically random. They do not have to be secret: IVs are typically just
999
+ * added to ciphertext messages unencrypted. It may sound contradictory that
1000
+ * something has to be unpredictable and unique, but does not have to be secret;
1001
+ * remember that an attacker must not be able to predict ahead of time what a given
1002
+ * IV will be.
1003
+ * @since v0.1.94
1004
+ * @param options `stream.transform` options
1005
+ */
1006
+ function createDecipheriv(algorithm: CipherCCMTypes, key: CipherKey, iv: BinaryLike, options: CipherCCMOptions): DecipherCCM;
1007
+ function createDecipheriv(algorithm: CipherOCBTypes, key: CipherKey, iv: BinaryLike, options: CipherOCBOptions): DecipherOCB;
1008
+ function createDecipheriv(algorithm: CipherGCMTypes, key: CipherKey, iv: BinaryLike, options?: CipherGCMOptions): DecipherGCM;
1009
+ function createDecipheriv(algorithm: string, key: CipherKey, iv: BinaryLike | null, options?: stream.TransformOptions): Decipher;
1010
+ /**
1011
+ * Instances of the `Decipher` class are used to decrypt data. The class can be
1012
+ * used in one of two ways:
1013
+ *
1014
+ * * As a `stream` that is both readable and writable, where plain encrypted
1015
+ * data is written to produce unencrypted data on the readable side, or
1016
+ * * Using the `decipher.update()` and `decipher.final()` methods to
1017
+ * produce the unencrypted data.
1018
+ *
1019
+ * The {@link createDecipher} or {@link createDecipheriv} methods are
1020
+ * used to create `Decipher` instances. `Decipher` objects are not to be created
1021
+ * directly using the `new` keyword.
1022
+ *
1023
+ * Example: Using `Decipher` objects as streams:
1024
+ *
1025
+ * ```js
1026
+ * import { Buffer } from 'buffer';
1027
+ * const {
1028
+ * scryptSync,
1029
+ * createDecipheriv
1030
+ * } = await import('crypto');
1031
+ *
1032
+ * const algorithm = 'aes-192-cbc';
1033
+ * const password = 'Password used to generate key';
1034
+ * // Key length is dependent on the algorithm. In this case for aes192, it is
1035
+ * // 24 bytes (192 bits).
1036
+ * // Use the async `crypto.scrypt()` instead.
1037
+ * const key = scryptSync(password, 'salt', 24);
1038
+ * // The IV is usually passed along with the ciphertext.
1039
+ * const iv = Buffer.alloc(16, 0); // Initialization vector.
1040
+ *
1041
+ * const decipher = createDecipheriv(algorithm, key, iv);
1042
+ *
1043
+ * let decrypted = '';
1044
+ * decipher.on('readable', () => {
1045
+ * while (null !== (chunk = decipher.read())) {
1046
+ * decrypted += chunk.toString('utf8');
1047
+ * }
1048
+ * });
1049
+ * decipher.on('end', () => {
1050
+ * console.log(decrypted);
1051
+ * // Prints: some clear text data
1052
+ * });
1053
+ *
1054
+ * // Encrypted with same algorithm, key and iv.
1055
+ * const encrypted =
1056
+ * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
1057
+ * decipher.write(encrypted, 'hex');
1058
+ * decipher.end();
1059
+ * ```
1060
+ *
1061
+ * Example: Using `Decipher` and piped streams:
1062
+ *
1063
+ * ```js
1064
+ * import {
1065
+ * createReadStream,
1066
+ * createWriteStream,
1067
+ * } from 'fs';
1068
+ * import { Buffer } from 'buffer';
1069
+ * const {
1070
+ * scryptSync,
1071
+ * createDecipheriv
1072
+ * } = await import('crypto');
1073
+ *
1074
+ * const algorithm = 'aes-192-cbc';
1075
+ * const password = 'Password used to generate key';
1076
+ * // Use the async `crypto.scrypt()` instead.
1077
+ * const key = scryptSync(password, 'salt', 24);
1078
+ * // The IV is usually passed along with the ciphertext.
1079
+ * const iv = Buffer.alloc(16, 0); // Initialization vector.
1080
+ *
1081
+ * const decipher = createDecipheriv(algorithm, key, iv);
1082
+ *
1083
+ * const input = createReadStream('test.enc');
1084
+ * const output = createWriteStream('test.js');
1085
+ *
1086
+ * input.pipe(decipher).pipe(output);
1087
+ * ```
1088
+ *
1089
+ * Example: Using the `decipher.update()` and `decipher.final()` methods:
1090
+ *
1091
+ * ```js
1092
+ * import { Buffer } from 'buffer';
1093
+ * const {
1094
+ * scryptSync,
1095
+ * createDecipheriv
1096
+ * } = await import('crypto');
1097
+ *
1098
+ * const algorithm = 'aes-192-cbc';
1099
+ * const password = 'Password used to generate key';
1100
+ * // Use the async `crypto.scrypt()` instead.
1101
+ * const key = scryptSync(password, 'salt', 24);
1102
+ * // The IV is usually passed along with the ciphertext.
1103
+ * const iv = Buffer.alloc(16, 0); // Initialization vector.
1104
+ *
1105
+ * const decipher = createDecipheriv(algorithm, key, iv);
1106
+ *
1107
+ * // Encrypted using same algorithm, key and iv.
1108
+ * const encrypted =
1109
+ * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
1110
+ * let decrypted = decipher.update(encrypted, 'hex', 'utf8');
1111
+ * decrypted += decipher.final('utf8');
1112
+ * console.log(decrypted);
1113
+ * // Prints: some clear text data
1114
+ * ```
1115
+ * @since v0.1.94
1116
+ */
345
1117
  class Decipher extends stream.Transform {
346
1118
  private constructor();
1119
+ /**
1120
+ * Updates the decipher with `data`. If the `inputEncoding` argument is given,
1121
+ * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is
1122
+ * ignored.
1123
+ *
1124
+ * The `outputEncoding` specifies the output format of the enciphered
1125
+ * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned.
1126
+ *
1127
+ * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error
1128
+ * being thrown.
1129
+ * @since v0.1.94
1130
+ * @param inputEncoding The `encoding` of the `data` string.
1131
+ * @param outputEncoding The `encoding` of the return value.
1132
+ */
347
1133
  update(data: NodeJS.ArrayBufferView): Buffer;
348
- update(data: string, input_encoding: Encoding): Buffer;
349
- update(data: NodeJS.ArrayBufferView, input_encoding: undefined, output_encoding: Encoding): string;
350
- update(data: string, input_encoding: Encoding | undefined, output_encoding: Encoding): string;
1134
+ update(data: string, inputEncoding: Encoding): Buffer;
1135
+ update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string;
1136
+ update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string;
1137
+ /**
1138
+ * Once the `decipher.final()` method has been called, the `Decipher` object can
1139
+ * no longer be used to decrypt data. Attempts to call `decipher.final()` more
1140
+ * than once will result in an error being thrown.
1141
+ * @since v0.1.94
1142
+ * @param outputEncoding The `encoding` of the return value.
1143
+ * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned.
1144
+ */
351
1145
  final(): Buffer;
352
- final(output_encoding: BufferEncoding): string;
1146
+ final(outputEncoding: BufferEncoding): string;
1147
+ /**
1148
+ * When data has been encrypted without standard block padding, calling`decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and
1149
+ * removing padding.
1150
+ *
1151
+ * Turning auto padding off will only work if the input data's length is a
1152
+ * multiple of the ciphers block size.
1153
+ *
1154
+ * The `decipher.setAutoPadding()` method must be called before `decipher.final()`.
1155
+ * @since v0.7.1
1156
+ * @param [autoPadding=true]
1157
+ * @return for method chaining.
1158
+ */
353
1159
  setAutoPadding(auto_padding?: boolean): this;
354
- // setAuthTag(tag: NodeJS.ArrayBufferView): this;
355
- // setAAD(buffer: NodeJS.ArrayBufferView): this;
356
1160
  }
357
1161
  interface DecipherCCM extends Decipher {
358
1162
  setAuthTag(buffer: NodeJS.ArrayBufferView): this;
359
- setAAD(buffer: NodeJS.ArrayBufferView, options: { plaintextLength: number }): this;
1163
+ setAAD(
1164
+ buffer: NodeJS.ArrayBufferView,
1165
+ options: {
1166
+ plaintextLength: number;
1167
+ }
1168
+ ): this;
360
1169
  }
361
1170
  interface DecipherGCM extends Decipher {
362
1171
  setAuthTag(buffer: NodeJS.ArrayBufferView): this;
363
- setAAD(buffer: NodeJS.ArrayBufferView, options?: { plaintextLength: number }): this;
1172
+ setAAD(
1173
+ buffer: NodeJS.ArrayBufferView,
1174
+ options?: {
1175
+ plaintextLength: number;
1176
+ }
1177
+ ): this;
1178
+ }
1179
+ interface DecipherOCB extends Decipher {
1180
+ setAuthTag(buffer: NodeJS.ArrayBufferView): this;
1181
+ setAAD(
1182
+ buffer: NodeJS.ArrayBufferView,
1183
+ options?: {
1184
+ plaintextLength: number;
1185
+ }
1186
+ ): this;
364
1187
  }
365
-
366
1188
  interface PrivateKeyInput {
367
1189
  key: string | Buffer;
368
- format?: KeyFormat;
369
- type?: 'pkcs1' | 'pkcs8' | 'sec1';
370
- passphrase?: string | Buffer;
1190
+ format?: KeyFormat | undefined;
1191
+ type?: 'pkcs1' | 'pkcs8' | 'sec1' | undefined;
1192
+ passphrase?: string | Buffer | undefined;
371
1193
  }
372
-
373
1194
  interface PublicKeyInput {
374
1195
  key: string | Buffer;
375
- format?: KeyFormat;
376
- type?: 'pkcs1' | 'spki';
1196
+ format?: KeyFormat | undefined;
1197
+ type?: 'pkcs1' | 'spki' | undefined;
377
1198
  }
378
-
379
- function generateKey(type: 'hmac' | 'aes', options: {length: number}, callback: (err: Error | null, key: KeyObject) => void): void;
380
-
381
- function createPrivateKey(key: PrivateKeyInput | string | Buffer): KeyObject;
382
- function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject): KeyObject;
1199
+ /**
1200
+ * Asynchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`.
1201
+ *
1202
+ * ```js
1203
+ * const {
1204
+ * generateKey
1205
+ * } = await import('crypto');
1206
+ *
1207
+ * generateKey('hmac', { length: 64 }, (err, key) => {
1208
+ * if (err) throw err;
1209
+ * console.log(key.export().toString('hex')); // 46e..........620
1210
+ * });
1211
+ * ```
1212
+ * @since v15.0.0
1213
+ * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`.
1214
+ */
1215
+ function generateKey(
1216
+ type: 'hmac' | 'aes',
1217
+ options: {
1218
+ length: number;
1219
+ },
1220
+ callback: (err: Error | null, key: KeyObject) => void
1221
+ ): void;
1222
+ /**
1223
+ * Synchronously generates a new random secret key of the given `length`. The`type` will determine which validations will be performed on the `length`.
1224
+ *
1225
+ * ```js
1226
+ * const {
1227
+ * generateKeySync
1228
+ * } = await import('crypto');
1229
+ *
1230
+ * const key = generateKeySync('hmac', { length: 64 });
1231
+ * console.log(key.export().toString('hex')); // e89..........41e
1232
+ * ```
1233
+ * @since v15.0.0
1234
+ * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`.
1235
+ */
1236
+ function generateKeySync(
1237
+ type: 'hmac' | 'aes',
1238
+ options: {
1239
+ length: number;
1240
+ }
1241
+ ): KeyObject;
1242
+ interface JsonWebKeyInput {
1243
+ key: JsonWebKey;
1244
+ format: 'jwk';
1245
+ }
1246
+ /**
1247
+ * Creates and returns a new key object containing a private key. If `key` is a
1248
+ * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key`must be an object with the properties described above.
1249
+ *
1250
+ * If the private key is encrypted, a `passphrase` must be specified. The length
1251
+ * of the passphrase is limited to 1024 bytes.
1252
+ * @since v11.6.0
1253
+ */
1254
+ function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject;
1255
+ /**
1256
+ * Creates and returns a new key object containing a public key. If `key` is a
1257
+ * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject`with type `'private'`, the public key is derived from the given private key;
1258
+ * otherwise, `key` must be an object with the properties described above.
1259
+ *
1260
+ * If the format is `'pem'`, the `'key'` may also be an X.509 certificate.
1261
+ *
1262
+ * Because public keys can be derived from private keys, a private key may be
1263
+ * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the
1264
+ * returned `KeyObject` will be `'public'` and that the private key cannot be
1265
+ * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type`'private'` is given, a new `KeyObject` with type `'public'` will be returned
1266
+ * and it will be impossible to extract the private key from the returned object.
1267
+ * @since v11.6.0
1268
+ */
1269
+ function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject;
1270
+ /**
1271
+ * Creates and returns a new key object containing a secret key for symmetric
1272
+ * encryption or `Hmac`.
1273
+ * @since v11.6.0
1274
+ * @param encoding The string encoding when `key` is a string.
1275
+ */
383
1276
  function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject;
384
-
385
- function createSign(algorithm: string, options?: stream.WritableOptions): Signer;
386
-
1277
+ function createSecretKey(key: string, encoding: BufferEncoding): KeyObject;
1278
+ /**
1279
+ * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms.
1280
+ * Optional `options` argument controls the `stream.Writable` behavior.
1281
+ *
1282
+ * In some cases, a `Sign` instance can be created using the name of a signature
1283
+ * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
1284
+ * the corresponding digest algorithm. This does not work for all signature
1285
+ * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
1286
+ * algorithm names.
1287
+ * @since v0.1.92
1288
+ * @param options `stream.Writable` options
1289
+ */
1290
+ function createSign(algorithm: string, options?: stream.WritableOptions): Sign;
387
1291
  type DSAEncoding = 'der' | 'ieee-p1363';
388
-
389
1292
  interface SigningOptions {
390
1293
  /**
391
1294
  * @See crypto.constants.RSA_PKCS1_PADDING
392
1295
  */
393
- padding?: number;
394
- saltLength?: number;
395
- dsaEncoding?: DSAEncoding;
1296
+ padding?: number | undefined;
1297
+ saltLength?: number | undefined;
1298
+ dsaEncoding?: DSAEncoding | undefined;
396
1299
  }
397
-
398
- interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions { }
1300
+ interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {}
399
1301
  interface SignKeyObjectInput extends SigningOptions {
400
1302
  key: KeyObject;
401
1303
  }
402
- interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions { }
1304
+ interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {}
403
1305
  interface VerifyKeyObjectInput extends SigningOptions {
404
1306
  key: KeyObject;
405
1307
  }
406
-
407
1308
  type KeyLike = string | Buffer | KeyObject;
408
-
409
- class Signer extends stream.Writable {
1309
+ /**
1310
+ * The `Sign` class is a utility for generating signatures. It can be used in one
1311
+ * of two ways:
1312
+ *
1313
+ * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or
1314
+ * * Using the `sign.update()` and `sign.sign()` methods to produce the
1315
+ * signature.
1316
+ *
1317
+ * The {@link createSign} method is used to create `Sign` instances. The
1318
+ * argument is the string name of the hash function to use. `Sign` objects are not
1319
+ * to be created directly using the `new` keyword.
1320
+ *
1321
+ * Example: Using `Sign` and `Verify` objects as streams:
1322
+ *
1323
+ * ```js
1324
+ * const {
1325
+ * generateKeyPairSync,
1326
+ * createSign,
1327
+ * createVerify
1328
+ * } = await import('crypto');
1329
+ *
1330
+ * const { privateKey, publicKey } = generateKeyPairSync('ec', {
1331
+ * namedCurve: 'sect239k1'
1332
+ * });
1333
+ *
1334
+ * const sign = createSign('SHA256');
1335
+ * sign.write('some data to sign');
1336
+ * sign.end();
1337
+ * const signature = sign.sign(privateKey, 'hex');
1338
+ *
1339
+ * const verify = createVerify('SHA256');
1340
+ * verify.write('some data to sign');
1341
+ * verify.end();
1342
+ * console.log(verify.verify(publicKey, signature, 'hex'));
1343
+ * // Prints: true
1344
+ * ```
1345
+ *
1346
+ * Example: Using the `sign.update()` and `verify.update()` methods:
1347
+ *
1348
+ * ```js
1349
+ * const {
1350
+ * generateKeyPairSync,
1351
+ * createSign,
1352
+ * createVerify
1353
+ * } = await import('crypto');
1354
+ *
1355
+ * const { privateKey, publicKey } = generateKeyPairSync('rsa', {
1356
+ * modulusLength: 2048,
1357
+ * });
1358
+ *
1359
+ * const sign = createSign('SHA256');
1360
+ * sign.update('some data to sign');
1361
+ * sign.end();
1362
+ * const signature = sign.sign(privateKey);
1363
+ *
1364
+ * const verify = createVerify('SHA256');
1365
+ * verify.update('some data to sign');
1366
+ * verify.end();
1367
+ * console.log(verify.verify(publicKey, signature));
1368
+ * // Prints: true
1369
+ * ```
1370
+ * @since v0.1.92
1371
+ */
1372
+ class Sign extends stream.Writable {
410
1373
  private constructor();
411
-
412
- update(data: BinaryLike): Signer;
413
- update(data: string, input_encoding: Encoding): Signer;
414
- sign(private_key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer;
415
- sign(
416
- private_key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput,
417
- output_format: BinaryToTextEncoding,
418
- ): string;
1374
+ /**
1375
+ * Updates the `Sign` content with the given `data`, the encoding of which
1376
+ * is given in `inputEncoding`.
1377
+ * If `encoding` is not provided, and the `data` is a string, an
1378
+ * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
1379
+ *
1380
+ * This can be called many times with new data as it is streamed.
1381
+ * @since v0.1.92
1382
+ * @param inputEncoding The `encoding` of the `data` string.
1383
+ */
1384
+ update(data: BinaryLike): this;
1385
+ update(data: string, inputEncoding: Encoding): this;
1386
+ /**
1387
+ * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`.
1388
+ *
1389
+ * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an
1390
+ * object, the following additional properties can be passed:
1391
+ *
1392
+ * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned.
1393
+ *
1394
+ * The `Sign` object can not be again used after `sign.sign()` method has been
1395
+ * called. Multiple calls to `sign.sign()` will result in an error being thrown.
1396
+ * @since v0.1.92
1397
+ */
1398
+ sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer;
1399
+ sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, outputFormat: BinaryToTextEncoding): string;
419
1400
  }
420
-
1401
+ /**
1402
+ * Creates and returns a `Verify` object that uses the given algorithm.
1403
+ * Use {@link getHashes} to obtain an array of names of the available
1404
+ * signing algorithms. Optional `options` argument controls the`stream.Writable` behavior.
1405
+ *
1406
+ * In some cases, a `Verify` instance can be created using the name of a signature
1407
+ * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use
1408
+ * the corresponding digest algorithm. This does not work for all signature
1409
+ * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest
1410
+ * algorithm names.
1411
+ * @since v0.1.92
1412
+ * @param options `stream.Writable` options
1413
+ */
421
1414
  function createVerify(algorithm: string, options?: stream.WritableOptions): Verify;
1415
+ /**
1416
+ * The `Verify` class is a utility for verifying signatures. It can be used in one
1417
+ * of two ways:
1418
+ *
1419
+ * * As a writable `stream` where written data is used to validate against the
1420
+ * supplied signature, or
1421
+ * * Using the `verify.update()` and `verify.verify()` methods to verify
1422
+ * the signature.
1423
+ *
1424
+ * The {@link createVerify} method is used to create `Verify` instances.`Verify` objects are not to be created directly using the `new` keyword.
1425
+ *
1426
+ * See `Sign` for examples.
1427
+ * @since v0.1.92
1428
+ */
422
1429
  class Verify extends stream.Writable {
423
1430
  private constructor();
424
-
1431
+ /**
1432
+ * Updates the `Verify` content with the given `data`, the encoding of which
1433
+ * is given in `inputEncoding`.
1434
+ * If `inputEncoding` is not provided, and the `data` is a string, an
1435
+ * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
1436
+ *
1437
+ * This can be called many times with new data as it is streamed.
1438
+ * @since v0.1.92
1439
+ * @param inputEncoding The `encoding` of the `data` string.
1440
+ */
425
1441
  update(data: BinaryLike): Verify;
426
- update(data: string, input_encoding: Encoding): Verify;
427
- verify(
428
- object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput,
429
- signature: NodeJS.ArrayBufferView,
430
- ): boolean;
431
- verify(
432
- object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput,
433
- signature: string,
434
- signature_format?: BinaryToTextEncoding,
435
- ): boolean;
436
- // https://nodejs.org/api/crypto.html#crypto_verifier_verify_object_signature_signature_format
437
- // The signature field accepts a TypedArray type, but it is only available starting ES2017
1442
+ update(data: string, inputEncoding: Encoding): Verify;
1443
+ /**
1444
+ * Verifies the provided data using the given `object` and `signature`.
1445
+ *
1446
+ * If `object` is not a `KeyObject`, this function behaves as if`object` had been passed to {@link createPublicKey}. If it is an
1447
+ * object, the following additional properties can be passed:
1448
+ *
1449
+ * The `signature` argument is the previously calculated signature for the data, in
1450
+ * the `signatureEncoding`.
1451
+ * If a `signatureEncoding` is specified, the `signature` is expected to be a
1452
+ * string; otherwise `signature` is expected to be a `Buffer`,`TypedArray`, or `DataView`.
1453
+ *
1454
+ * The `verify` object can not be used again after `verify.verify()` has been
1455
+ * called. Multiple calls to `verify.verify()` will result in an error being
1456
+ * thrown.
1457
+ *
1458
+ * Because public keys can be derived from private keys, a private key may
1459
+ * be passed instead of a public key.
1460
+ * @since v0.1.92
1461
+ */
1462
+ verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean;
1463
+ verify(object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: string, signature_format?: BinaryToTextEncoding): boolean;
438
1464
  }
439
- function createDiffieHellman(prime_length: number, generator?: number | NodeJS.ArrayBufferView): DiffieHellman;
440
- function createDiffieHellman(prime: NodeJS.ArrayBufferView): DiffieHellman;
441
- function createDiffieHellman(prime: string, prime_encoding: BinaryToTextEncoding): DiffieHellman;
442
- function createDiffieHellman(
443
- prime: string,
444
- prime_encoding: BinaryToTextEncoding,
445
- generator: number | NodeJS.ArrayBufferView,
446
- ): DiffieHellman;
447
- function createDiffieHellman(
448
- prime: string,
449
- prime_encoding: BinaryToTextEncoding,
450
- generator: string,
451
- generator_encoding: BinaryToTextEncoding,
452
- ): DiffieHellman;
1465
+ /**
1466
+ * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an
1467
+ * optional specific `generator`.
1468
+ *
1469
+ * The `generator` argument can be a number, string, or `Buffer`. If`generator` is not specified, the value `2` is used.
1470
+ *
1471
+ * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise
1472
+ * a `Buffer`, `TypedArray`, or `DataView` is expected.
1473
+ *
1474
+ * If `generatorEncoding` is specified, `generator` is expected to be a string;
1475
+ * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected.
1476
+ * @since v0.11.12
1477
+ * @param primeEncoding The `encoding` of the `prime` string.
1478
+ * @param [generator=2]
1479
+ * @param generatorEncoding The `encoding` of the `generator` string.
1480
+ */
1481
+ function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman;
1482
+ function createDiffieHellman(prime: ArrayBuffer | NodeJS.ArrayBufferView, generator?: number | ArrayBuffer | NodeJS.ArrayBufferView): DiffieHellman;
1483
+ function createDiffieHellman(prime: ArrayBuffer | NodeJS.ArrayBufferView, generator: string, generatorEncoding: BinaryToTextEncoding): DiffieHellman;
1484
+ function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator?: number | ArrayBuffer | NodeJS.ArrayBufferView): DiffieHellman;
1485
+ function createDiffieHellman(prime: string, primeEncoding: BinaryToTextEncoding, generator: string, generatorEncoding: BinaryToTextEncoding): DiffieHellman;
1486
+ /**
1487
+ * The `DiffieHellman` class is a utility for creating Diffie-Hellman key
1488
+ * exchanges.
1489
+ *
1490
+ * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function.
1491
+ *
1492
+ * ```js
1493
+ * import assert from 'assert';
1494
+ *
1495
+ * const {
1496
+ * createDiffieHellman
1497
+ * } = await import('crypto');
1498
+ *
1499
+ * // Generate Alice's keys...
1500
+ * const alice = createDiffieHellman(2048);
1501
+ * const aliceKey = alice.generateKeys();
1502
+ *
1503
+ * // Generate Bob's keys...
1504
+ * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());
1505
+ * const bobKey = bob.generateKeys();
1506
+ *
1507
+ * // Exchange and generate the secret...
1508
+ * const aliceSecret = alice.computeSecret(bobKey);
1509
+ * const bobSecret = bob.computeSecret(aliceKey);
1510
+ *
1511
+ * // OK
1512
+ * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
1513
+ * ```
1514
+ * @since v0.5.0
1515
+ */
453
1516
  class DiffieHellman {
454
1517
  private constructor();
1518
+ /**
1519
+ * Generates private and public Diffie-Hellman key values, and returns
1520
+ * the public key in the specified `encoding`. This key should be
1521
+ * transferred to the other party.
1522
+ * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned.
1523
+ * @since v0.5.0
1524
+ * @param encoding The `encoding` of the return value.
1525
+ */
455
1526
  generateKeys(): Buffer;
456
1527
  generateKeys(encoding: BinaryToTextEncoding): string;
457
- computeSecret(other_public_key: NodeJS.ArrayBufferView): Buffer;
458
- computeSecret(other_public_key: string, input_encoding: BinaryToTextEncoding): Buffer;
459
- computeSecret(other_public_key: NodeJS.ArrayBufferView, output_encoding: BinaryToTextEncoding): string;
460
- computeSecret(
461
- other_public_key: string,
462
- input_encoding: BinaryToTextEncoding,
463
- output_encoding: BinaryToTextEncoding,
464
- ): string;
1528
+ /**
1529
+ * Computes the shared secret using `otherPublicKey` as the other
1530
+ * party's public key and returns the computed shared secret. The supplied
1531
+ * key is interpreted using the specified `inputEncoding`, and secret is
1532
+ * encoded using specified `outputEncoding`.
1533
+ * If the `inputEncoding` is not
1534
+ * provided, `otherPublicKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`.
1535
+ *
1536
+ * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned.
1537
+ * @since v0.5.0
1538
+ * @param inputEncoding The `encoding` of an `otherPublicKey` string.
1539
+ * @param outputEncoding The `encoding` of the return value.
1540
+ */
1541
+ computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding?: null, outputEncoding?: null): Buffer;
1542
+ computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding?: null): Buffer;
1543
+ computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding: null, outputEncoding: BinaryToTextEncoding): string;
1544
+ computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string;
1545
+ /**
1546
+ * Returns the Diffie-Hellman prime in the specified `encoding`.
1547
+ * If `encoding` is provided a string is
1548
+ * returned; otherwise a `Buffer` is returned.
1549
+ * @since v0.5.0
1550
+ * @param encoding The `encoding` of the return value.
1551
+ */
465
1552
  getPrime(): Buffer;
466
1553
  getPrime(encoding: BinaryToTextEncoding): string;
1554
+ /**
1555
+ * Returns the Diffie-Hellman generator in the specified `encoding`.
1556
+ * If `encoding` is provided a string is
1557
+ * returned; otherwise a `Buffer` is returned.
1558
+ * @since v0.5.0
1559
+ * @param encoding The `encoding` of the return value.
1560
+ */
467
1561
  getGenerator(): Buffer;
468
1562
  getGenerator(encoding: BinaryToTextEncoding): string;
1563
+ /**
1564
+ * Returns the Diffie-Hellman public key in the specified `encoding`.
1565
+ * If `encoding` is provided a
1566
+ * string is returned; otherwise a `Buffer` is returned.
1567
+ * @since v0.5.0
1568
+ * @param encoding The `encoding` of the return value.
1569
+ */
469
1570
  getPublicKey(): Buffer;
470
1571
  getPublicKey(encoding: BinaryToTextEncoding): string;
1572
+ /**
1573
+ * Returns the Diffie-Hellman private key in the specified `encoding`.
1574
+ * If `encoding` is provided a
1575
+ * string is returned; otherwise a `Buffer` is returned.
1576
+ * @since v0.5.0
1577
+ * @param encoding The `encoding` of the return value.
1578
+ */
471
1579
  getPrivateKey(): Buffer;
472
1580
  getPrivateKey(encoding: BinaryToTextEncoding): string;
473
- setPublicKey(public_key: NodeJS.ArrayBufferView): void;
474
- setPublicKey(public_key: string, encoding: BufferEncoding): void;
475
- setPrivateKey(private_key: NodeJS.ArrayBufferView): void;
476
- setPrivateKey(private_key: string, encoding: BufferEncoding): void;
1581
+ /**
1582
+ * Sets the Diffie-Hellman public key. If the `encoding` argument is provided,`publicKey` is expected
1583
+ * to be a string. If no `encoding` is provided, `publicKey` is expected
1584
+ * to be a `Buffer`, `TypedArray`, or `DataView`.
1585
+ * @since v0.5.0
1586
+ * @param encoding The `encoding` of the `publicKey` string.
1587
+ */
1588
+ setPublicKey(publicKey: NodeJS.ArrayBufferView): void;
1589
+ setPublicKey(publicKey: string, encoding: BufferEncoding): void;
1590
+ /**
1591
+ * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected
1592
+ * to be a string. If no `encoding` is provided, `privateKey` is expected
1593
+ * to be a `Buffer`, `TypedArray`, or `DataView`.
1594
+ * @since v0.5.0
1595
+ * @param encoding The `encoding` of the `privateKey` string.
1596
+ */
1597
+ setPrivateKey(privateKey: NodeJS.ArrayBufferView): void;
1598
+ setPrivateKey(privateKey: string, encoding: BufferEncoding): void;
1599
+ /**
1600
+ * A bit field containing any warnings and/or errors resulting from a check
1601
+ * performed during initialization of the `DiffieHellman` object.
1602
+ *
1603
+ * The following values are valid for this property (as defined in `constants`module):
1604
+ *
1605
+ * * `DH_CHECK_P_NOT_SAFE_PRIME`
1606
+ * * `DH_CHECK_P_NOT_PRIME`
1607
+ * * `DH_UNABLE_TO_CHECK_GENERATOR`
1608
+ * * `DH_NOT_SUITABLE_GENERATOR`
1609
+ * @since v0.11.12
1610
+ */
477
1611
  verifyError: number;
478
1612
  }
479
- function getDiffieHellman(group_name: string): DiffieHellman;
480
- function pbkdf2(
481
- password: BinaryLike,
482
- salt: BinaryLike,
483
- iterations: number,
484
- keylen: number,
485
- digest: string,
486
- callback: (err: Error | null, derivedKey: Buffer) => any,
487
- ): void;
488
- function pbkdf2Sync(
489
- password: BinaryLike,
490
- salt: BinaryLike,
491
- iterations: number,
492
- keylen: number,
493
- digest: string,
494
- ): Buffer;
495
-
1613
+ /**
1614
+ * The `DiffieHellmanGroup` class takes a well-known modp group as its argument.
1615
+ * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation.
1616
+ * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods.
1617
+ *
1618
+ * ```js
1619
+ * const { createDiffieHellmanGroup } = await import('node:crypto');
1620
+ * const dh = createDiffieHellmanGroup('modp1');
1621
+ * ```
1622
+ * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt):
1623
+ * ```bash
1624
+ * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h
1625
+ * modp1 # 768 bits
1626
+ * modp2 # 1024 bits
1627
+ * modp5 # 1536 bits
1628
+ * modp14 # 2048 bits
1629
+ * modp15 # etc.
1630
+ * modp16
1631
+ * modp17
1632
+ * modp18
1633
+ * ```
1634
+ * @since v0.7.5
1635
+ */
1636
+ const DiffieHellmanGroup: DiffieHellmanGroupConstructor;
1637
+ interface DiffieHellmanGroupConstructor {
1638
+ new(name: string): DiffieHellmanGroup;
1639
+ (name: string): DiffieHellmanGroup;
1640
+ readonly prototype: DiffieHellmanGroup;
1641
+ }
1642
+ type DiffieHellmanGroup = Omit<DiffieHellman, 'setPublicKey' | 'setPrivateKey'>;
1643
+ /**
1644
+ * Creates a predefined `DiffieHellmanGroup` key exchange object. The
1645
+ * supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt), but see `Caveats`) and `'modp14'`, `'modp15'`,`'modp16'`, `'modp17'`,
1646
+ * `'modp18'` (defined in [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt)). The
1647
+ * returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing
1648
+ * the keys (with `diffieHellman.setPublicKey()`, for example). The
1649
+ * advantage of using this method is that the parties do not have to
1650
+ * generate nor exchange a group modulus beforehand, saving both processor
1651
+ * and communication time.
1652
+ *
1653
+ * Example (obtaining a shared secret):
1654
+ *
1655
+ * ```js
1656
+ * const {
1657
+ * getDiffieHellman
1658
+ * } = await import('crypto');
1659
+ * const alice = getDiffieHellman('modp14');
1660
+ * const bob = getDiffieHellman('modp14');
1661
+ *
1662
+ * alice.generateKeys();
1663
+ * bob.generateKeys();
1664
+ *
1665
+ * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
1666
+ * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
1667
+ *
1668
+ * // aliceSecret and bobSecret should be the same
1669
+ * console.log(aliceSecret === bobSecret);
1670
+ * ```
1671
+ * @since v0.7.5
1672
+ */
1673
+ function getDiffieHellman(groupName: string): DiffieHellmanGroup;
1674
+ /**
1675
+ * An alias for {@link getDiffieHellman}
1676
+ * @since v0.9.3
1677
+ */
1678
+ function createDiffieHellmanGroup(name: string): DiffieHellmanGroup;
1679
+ /**
1680
+ * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)
1681
+ * implementation. A selected HMAC digest algorithm specified by `digest` is
1682
+ * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`.
1683
+ *
1684
+ * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an error occurs while deriving the key, `err` will be set;
1685
+ * otherwise `err` will be `null`. By default, the successfully generated`derivedKey` will be passed to the callback as a `Buffer`. An error will be
1686
+ * thrown if any of the input arguments specify invalid values or types.
1687
+ *
1688
+ * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated,
1689
+ * please specify a `digest` explicitly.
1690
+ *
1691
+ * The `iterations` argument must be a number set as high as possible. The
1692
+ * higher the number of iterations, the more secure the derived key will be,
1693
+ * but will take a longer amount of time to complete.
1694
+ *
1695
+ * The `salt` should be as unique as possible. It is recommended that a salt is
1696
+ * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
1697
+ *
1698
+ * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
1699
+ *
1700
+ * ```js
1701
+ * const {
1702
+ * pbkdf2
1703
+ * } = await import('crypto');
1704
+ *
1705
+ * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => {
1706
+ * if (err) throw err;
1707
+ * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
1708
+ * });
1709
+ * ```
1710
+ *
1711
+ * The `crypto.DEFAULT_ENCODING` property can be used to change the way the`derivedKey` is passed to the callback. This property, however, has been
1712
+ * deprecated and use should be avoided.
1713
+ *
1714
+ * ```js
1715
+ * import crypto from 'crypto';
1716
+ * crypto.DEFAULT_ENCODING = 'hex';
1717
+ * crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, derivedKey) => {
1718
+ * if (err) throw err;
1719
+ * console.log(derivedKey); // '3745e48...aa39b34'
1720
+ * });
1721
+ * ```
1722
+ *
1723
+ * An array of supported digest functions can be retrieved using {@link getHashes}.
1724
+ *
1725
+ * This API uses libuv's threadpool, which can have surprising and
1726
+ * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
1727
+ * @since v0.5.5
1728
+ */
1729
+ function pbkdf2(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string, callback: (err: Error | null, derivedKey: Buffer) => void): void;
1730
+ /**
1731
+ * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)
1732
+ * implementation. A selected HMAC digest algorithm specified by `digest` is
1733
+ * applied to derive a key of the requested byte length (`keylen`) from the`password`, `salt` and `iterations`.
1734
+ *
1735
+ * If an error occurs an `Error` will be thrown, otherwise the derived key will be
1736
+ * returned as a `Buffer`.
1737
+ *
1738
+ * If `digest` is `null`, `'sha1'` will be used. This behavior is deprecated,
1739
+ * please specify a `digest` explicitly.
1740
+ *
1741
+ * The `iterations` argument must be a number set as high as possible. The
1742
+ * higher the number of iterations, the more secure the derived key will be,
1743
+ * but will take a longer amount of time to complete.
1744
+ *
1745
+ * The `salt` should be as unique as possible. It is recommended that a salt is
1746
+ * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
1747
+ *
1748
+ * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
1749
+ *
1750
+ * ```js
1751
+ * const {
1752
+ * pbkdf2Sync
1753
+ * } = await import('crypto');
1754
+ *
1755
+ * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512');
1756
+ * console.log(key.toString('hex')); // '3745e48...08d59ae'
1757
+ * ```
1758
+ *
1759
+ * The `crypto.DEFAULT_ENCODING` property may be used to change the way the`derivedKey` is returned. This property, however, is deprecated and use
1760
+ * should be avoided.
1761
+ *
1762
+ * ```js
1763
+ * import crypto from 'crypto';
1764
+ * crypto.DEFAULT_ENCODING = 'hex';
1765
+ * const key = crypto.pbkdf2Sync('secret', 'salt', 100000, 512, 'sha512');
1766
+ * console.log(key); // '3745e48...aa39b34'
1767
+ * ```
1768
+ *
1769
+ * An array of supported digest functions can be retrieved using {@link getHashes}.
1770
+ * @since v0.9.3
1771
+ */
1772
+ function pbkdf2Sync(password: BinaryLike, salt: BinaryLike, iterations: number, keylen: number, digest: string): Buffer;
1773
+ /**
1774
+ * Generates cryptographically strong pseudorandom data. The `size` argument
1775
+ * is a number indicating the number of bytes to generate.
1776
+ *
1777
+ * If a `callback` function is provided, the bytes are generated asynchronously
1778
+ * and the `callback` function is invoked with two arguments: `err` and `buf`.
1779
+ * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The`buf` argument is a `Buffer` containing the generated bytes.
1780
+ *
1781
+ * ```js
1782
+ * // Asynchronous
1783
+ * const {
1784
+ * randomBytes
1785
+ * } = await import('crypto');
1786
+ *
1787
+ * randomBytes(256, (err, buf) => {
1788
+ * if (err) throw err;
1789
+ * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`);
1790
+ * });
1791
+ * ```
1792
+ *
1793
+ * If the `callback` function is not provided, the random bytes are generated
1794
+ * synchronously and returned as a `Buffer`. An error will be thrown if
1795
+ * there is a problem generating the bytes.
1796
+ *
1797
+ * ```js
1798
+ * // Synchronous
1799
+ * const {
1800
+ * randomBytes
1801
+ * } = await import('crypto');
1802
+ *
1803
+ * const buf = randomBytes(256);
1804
+ * console.log(
1805
+ * `${buf.length} bytes of random data: ${buf.toString('hex')}`);
1806
+ * ```
1807
+ *
1808
+ * The `crypto.randomBytes()` method will not complete until there is
1809
+ * sufficient entropy available.
1810
+ * This should normally never take longer than a few milliseconds. The only time
1811
+ * when generating the random bytes may conceivably block for a longer period of
1812
+ * time is right after boot, when the whole system is still low on entropy.
1813
+ *
1814
+ * This API uses libuv's threadpool, which can have surprising and
1815
+ * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
1816
+ *
1817
+ * The asynchronous version of `crypto.randomBytes()` is carried out in a single
1818
+ * threadpool request. To minimize threadpool task length variation, partition
1819
+ * large `randomBytes` requests when doing so as part of fulfilling a client
1820
+ * request.
1821
+ * @since v0.5.8
1822
+ * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`.
1823
+ * @return if the `callback` function is not provided.
1824
+ */
496
1825
  function randomBytes(size: number): Buffer;
497
1826
  function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
498
1827
  function pseudoRandomBytes(size: number): Buffer;
499
1828
  function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void;
500
-
1829
+ /**
1830
+ * Return a random integer `n` such that `min <= n < max`. This
1831
+ * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias).
1832
+ *
1833
+ * The range (`max - min`) must be less than 2^48. `min` and `max` must
1834
+ * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger).
1835
+ *
1836
+ * If the `callback` function is not provided, the random integer is
1837
+ * generated synchronously.
1838
+ *
1839
+ * ```js
1840
+ * // Asynchronous
1841
+ * const {
1842
+ * randomInt
1843
+ * } = await import('crypto');
1844
+ *
1845
+ * randomInt(3, (err, n) => {
1846
+ * if (err) throw err;
1847
+ * console.log(`Random number chosen from (0, 1, 2): ${n}`);
1848
+ * });
1849
+ * ```
1850
+ *
1851
+ * ```js
1852
+ * // Synchronous
1853
+ * const {
1854
+ * randomInt
1855
+ * } = await import('crypto');
1856
+ *
1857
+ * const n = randomInt(3);
1858
+ * console.log(`Random number chosen from (0, 1, 2): ${n}`);
1859
+ * ```
1860
+ *
1861
+ * ```js
1862
+ * // With `min` argument
1863
+ * const {
1864
+ * randomInt
1865
+ * } = await import('crypto');
1866
+ *
1867
+ * const n = randomInt(1, 7);
1868
+ * console.log(`The dice rolled: ${n}`);
1869
+ * ```
1870
+ * @since v14.10.0, v12.19.0
1871
+ * @param [min=0] Start of random range (inclusive).
1872
+ * @param max End of random range (exclusive).
1873
+ * @param callback `function(err, n) {}`.
1874
+ */
501
1875
  function randomInt(max: number): number;
502
1876
  function randomInt(min: number, max: number): number;
503
1877
  function randomInt(max: number, callback: (err: Error | null, value: number) => void): void;
504
1878
  function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void;
505
-
1879
+ /**
1880
+ * Synchronous version of {@link randomFill}.
1881
+ *
1882
+ * ```js
1883
+ * import { Buffer } from 'buffer';
1884
+ * const { randomFillSync } = await import('crypto');
1885
+ *
1886
+ * const buf = Buffer.alloc(10);
1887
+ * console.log(randomFillSync(buf).toString('hex'));
1888
+ *
1889
+ * randomFillSync(buf, 5);
1890
+ * console.log(buf.toString('hex'));
1891
+ *
1892
+ * // The above is equivalent to the following:
1893
+ * randomFillSync(buf, 5, 5);
1894
+ * console.log(buf.toString('hex'));
1895
+ * ```
1896
+ *
1897
+ * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`.
1898
+ *
1899
+ * ```js
1900
+ * import { Buffer } from 'buffer';
1901
+ * const { randomFillSync } = await import('crypto');
1902
+ *
1903
+ * const a = new Uint32Array(10);
1904
+ * console.log(Buffer.from(randomFillSync(a).buffer,
1905
+ * a.byteOffset, a.byteLength).toString('hex'));
1906
+ *
1907
+ * const b = new DataView(new ArrayBuffer(10));
1908
+ * console.log(Buffer.from(randomFillSync(b).buffer,
1909
+ * b.byteOffset, b.byteLength).toString('hex'));
1910
+ *
1911
+ * const c = new ArrayBuffer(10);
1912
+ * console.log(Buffer.from(randomFillSync(c)).toString('hex'));
1913
+ * ```
1914
+ * @since v7.10.0, v6.13.0
1915
+ * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`.
1916
+ * @param [offset=0]
1917
+ * @param [size=buffer.length - offset]
1918
+ * @return The object passed as `buffer` argument.
1919
+ */
506
1920
  function randomFillSync<T extends NodeJS.ArrayBufferView>(buffer: T, offset?: number, size?: number): T;
507
- function randomFill<T extends NodeJS.ArrayBufferView>(
508
- buffer: T,
509
- callback: (err: Error | null, buf: T) => void,
510
- ): void;
511
- function randomFill<T extends NodeJS.ArrayBufferView>(
512
- buffer: T,
513
- offset: number,
514
- callback: (err: Error | null, buf: T) => void,
515
- ): void;
516
- function randomFill<T extends NodeJS.ArrayBufferView>(
517
- buffer: T,
518
- offset: number,
519
- size: number,
520
- callback: (err: Error | null, buf: T) => void,
521
- ): void;
522
-
1921
+ /**
1922
+ * This function is similar to {@link randomBytes} but requires the first
1923
+ * argument to be a `Buffer` that will be filled. It also
1924
+ * requires that a callback is passed in.
1925
+ *
1926
+ * If the `callback` function is not provided, an error will be thrown.
1927
+ *
1928
+ * ```js
1929
+ * import { Buffer } from 'buffer';
1930
+ * const { randomFill } = await import('crypto');
1931
+ *
1932
+ * const buf = Buffer.alloc(10);
1933
+ * randomFill(buf, (err, buf) => {
1934
+ * if (err) throw err;
1935
+ * console.log(buf.toString('hex'));
1936
+ * });
1937
+ *
1938
+ * randomFill(buf, 5, (err, buf) => {
1939
+ * if (err) throw err;
1940
+ * console.log(buf.toString('hex'));
1941
+ * });
1942
+ *
1943
+ * // The above is equivalent to the following:
1944
+ * randomFill(buf, 5, 5, (err, buf) => {
1945
+ * if (err) throw err;
1946
+ * console.log(buf.toString('hex'));
1947
+ * });
1948
+ * ```
1949
+ *
1950
+ * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as`buffer`.
1951
+ *
1952
+ * While this includes instances of `Float32Array` and `Float64Array`, this
1953
+ * function should not be used to generate random floating-point numbers. The
1954
+ * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array
1955
+ * contains finite numbers only, they are not drawn from a uniform random
1956
+ * distribution and have no meaningful lower or upper bounds.
1957
+ *
1958
+ * ```js
1959
+ * import { Buffer } from 'buffer';
1960
+ * const { randomFill } = await import('crypto');
1961
+ *
1962
+ * const a = new Uint32Array(10);
1963
+ * randomFill(a, (err, buf) => {
1964
+ * if (err) throw err;
1965
+ * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
1966
+ * .toString('hex'));
1967
+ * });
1968
+ *
1969
+ * const b = new DataView(new ArrayBuffer(10));
1970
+ * randomFill(b, (err, buf) => {
1971
+ * if (err) throw err;
1972
+ * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)
1973
+ * .toString('hex'));
1974
+ * });
1975
+ *
1976
+ * const c = new ArrayBuffer(10);
1977
+ * randomFill(c, (err, buf) => {
1978
+ * if (err) throw err;
1979
+ * console.log(Buffer.from(buf).toString('hex'));
1980
+ * });
1981
+ * ```
1982
+ *
1983
+ * This API uses libuv's threadpool, which can have surprising and
1984
+ * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information.
1985
+ *
1986
+ * The asynchronous version of `crypto.randomFill()` is carried out in a single
1987
+ * threadpool request. To minimize threadpool task length variation, partition
1988
+ * large `randomFill` requests when doing so as part of fulfilling a client
1989
+ * request.
1990
+ * @since v7.10.0, v6.13.0
1991
+ * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`.
1992
+ * @param [offset=0]
1993
+ * @param [size=buffer.length - offset]
1994
+ * @param callback `function(err, buf) {}`.
1995
+ */
1996
+ function randomFill<T extends NodeJS.ArrayBufferView>(buffer: T, callback: (err: Error | null, buf: T) => void): void;
1997
+ function randomFill<T extends NodeJS.ArrayBufferView>(buffer: T, offset: number, callback: (err: Error | null, buf: T) => void): void;
1998
+ function randomFill<T extends NodeJS.ArrayBufferView>(buffer: T, offset: number, size: number, callback: (err: Error | null, buf: T) => void): void;
523
1999
  interface ScryptOptions {
524
- cost?: number;
525
- blockSize?: number;
526
- parallelization?: number;
527
- N?: number;
528
- r?: number;
529
- p?: number;
530
- maxmem?: number;
2000
+ cost?: number | undefined;
2001
+ blockSize?: number | undefined;
2002
+ parallelization?: number | undefined;
2003
+ N?: number | undefined;
2004
+ r?: number | undefined;
2005
+ p?: number | undefined;
2006
+ maxmem?: number | undefined;
531
2007
  }
532
- function scrypt(
533
- password: BinaryLike,
534
- salt: BinaryLike,
535
- keylen: number,
536
- callback: (err: Error | null, derivedKey: Buffer) => void,
537
- ): void;
538
- function scrypt(
539
- password: BinaryLike,
540
- salt: BinaryLike,
541
- keylen: number,
542
- options: ScryptOptions,
543
- callback: (err: Error | null, derivedKey: Buffer) => void,
544
- ): void;
2008
+ /**
2009
+ * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based
2010
+ * key derivation function that is designed to be expensive computationally and
2011
+ * memory-wise in order to make brute-force attacks unrewarding.
2012
+ *
2013
+ * The `salt` should be as unique as possible. It is recommended that a salt is
2014
+ * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
2015
+ *
2016
+ * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
2017
+ *
2018
+ * The `callback` function is called with two arguments: `err` and `derivedKey`.`err` is an exception object when key derivation fails, otherwise `err` is`null`. `derivedKey` is passed to the
2019
+ * callback as a `Buffer`.
2020
+ *
2021
+ * An exception is thrown when any of the input arguments specify invalid values
2022
+ * or types.
2023
+ *
2024
+ * ```js
2025
+ * const {
2026
+ * scrypt
2027
+ * } = await import('crypto');
2028
+ *
2029
+ * // Using the factory defaults.
2030
+ * scrypt('password', 'salt', 64, (err, derivedKey) => {
2031
+ * if (err) throw err;
2032
+ * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae'
2033
+ * });
2034
+ * // Using a custom N parameter. Must be a power of two.
2035
+ * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => {
2036
+ * if (err) throw err;
2037
+ * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34'
2038
+ * });
2039
+ * ```
2040
+ * @since v10.5.0
2041
+ */
2042
+ function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: Buffer) => void): void;
2043
+ function scrypt(password: BinaryLike, salt: BinaryLike, keylen: number, options: ScryptOptions, callback: (err: Error | null, derivedKey: Buffer) => void): void;
2044
+ /**
2045
+ * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based
2046
+ * key derivation function that is designed to be expensive computationally and
2047
+ * memory-wise in order to make brute-force attacks unrewarding.
2048
+ *
2049
+ * The `salt` should be as unique as possible. It is recommended that a salt is
2050
+ * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details.
2051
+ *
2052
+ * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`.
2053
+ *
2054
+ * An exception is thrown when key derivation fails, otherwise the derived key is
2055
+ * returned as a `Buffer`.
2056
+ *
2057
+ * An exception is thrown when any of the input arguments specify invalid values
2058
+ * or types.
2059
+ *
2060
+ * ```js
2061
+ * const {
2062
+ * scryptSync
2063
+ * } = await import('crypto');
2064
+ * // Using the factory defaults.
2065
+ *
2066
+ * const key1 = scryptSync('password', 'salt', 64);
2067
+ * console.log(key1.toString('hex')); // '3745e48...08d59ae'
2068
+ * // Using a custom N parameter. Must be a power of two.
2069
+ * const key2 = scryptSync('password', 'salt', 64, { N: 1024 });
2070
+ * console.log(key2.toString('hex')); // '3745e48...aa39b34'
2071
+ * ```
2072
+ * @since v10.5.0
2073
+ */
545
2074
  function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer;
546
-
547
2075
  interface RsaPublicKey {
548
2076
  key: KeyLike;
549
- padding?: number;
2077
+ padding?: number | undefined;
550
2078
  }
551
2079
  interface RsaPrivateKey {
552
2080
  key: KeyLike;
553
- passphrase?: string;
2081
+ passphrase?: string | undefined;
554
2082
  /**
555
2083
  * @default 'sha1'
556
2084
  */
557
- oaepHash?: string;
558
- oaepLabel?: NodeJS.TypedArray;
559
- padding?: number;
2085
+ oaepHash?: string | undefined;
2086
+ oaepLabel?: NodeJS.TypedArray | undefined;
2087
+ padding?: number | undefined;
560
2088
  }
2089
+ /**
2090
+ * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using
2091
+ * the corresponding private key, for example using {@link privateDecrypt}.
2092
+ *
2093
+ * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an
2094
+ * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`.
2095
+ *
2096
+ * Because RSA public keys can be derived from private keys, a private key may
2097
+ * be passed instead of a public key.
2098
+ * @since v0.11.14
2099
+ */
561
2100
  function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
2101
+ /**
2102
+ * Decrypts `buffer` with `key`.`buffer` was previously encrypted using
2103
+ * the corresponding private key, for example using {@link privateEncrypt}.
2104
+ *
2105
+ * If `key` is not a `KeyObject`, this function behaves as if`key` had been passed to {@link createPublicKey}. If it is an
2106
+ * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`.
2107
+ *
2108
+ * Because RSA public keys can be derived from private keys, a private key may
2109
+ * be passed instead of a public key.
2110
+ * @since v1.1.0
2111
+ */
562
2112
  function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
563
- function privateDecrypt(private_key: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
564
- function privateEncrypt(private_key: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
2113
+ /**
2114
+ * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using
2115
+ * the corresponding public key, for example using {@link publicEncrypt}.
2116
+ *
2117
+ * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an
2118
+ * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_OAEP_PADDING`.
2119
+ * @since v0.11.14
2120
+ */
2121
+ function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
2122
+ /**
2123
+ * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using
2124
+ * the corresponding public key, for example using {@link publicDecrypt}.
2125
+ *
2126
+ * If `privateKey` is not a `KeyObject`, this function behaves as if`privateKey` had been passed to {@link createPrivateKey}. If it is an
2127
+ * object, the `padding` property can be passed. Otherwise, this function uses`RSA_PKCS1_PADDING`.
2128
+ * @since v1.1.0
2129
+ */
2130
+ function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer;
2131
+ /**
2132
+ * ```js
2133
+ * const {
2134
+ * getCiphers
2135
+ * } = await import('crypto');
2136
+ *
2137
+ * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...]
2138
+ * ```
2139
+ * @since v0.9.3
2140
+ * @return An array with the names of the supported cipher algorithms.
2141
+ */
565
2142
  function getCiphers(): string[];
2143
+ /**
2144
+ * ```js
2145
+ * const {
2146
+ * getCurves
2147
+ * } = await import('crypto');
2148
+ *
2149
+ * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...]
2150
+ * ```
2151
+ * @since v2.3.0
2152
+ * @return An array with the names of the supported elliptic curves.
2153
+ */
566
2154
  function getCurves(): string[];
2155
+ /**
2156
+ * @since v10.0.0
2157
+ * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}.
2158
+ */
567
2159
  function getFips(): 1 | 0;
2160
+ /**
2161
+ * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. Throws an error if FIPS mode is not available.
2162
+ * @since v10.0.0
2163
+ * @param bool `true` to enable FIPS mode.
2164
+ */
2165
+ function setFips(bool: boolean): void;
2166
+ /**
2167
+ * ```js
2168
+ * const {
2169
+ * getHashes
2170
+ * } = await import('crypto');
2171
+ *
2172
+ * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...]
2173
+ * ```
2174
+ * @since v0.9.3
2175
+ * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms.
2176
+ */
568
2177
  function getHashes(): string[];
2178
+ /**
2179
+ * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)
2180
+ * key exchanges.
2181
+ *
2182
+ * Instances of the `ECDH` class can be created using the {@link createECDH} function.
2183
+ *
2184
+ * ```js
2185
+ * import assert from 'assert';
2186
+ *
2187
+ * const {
2188
+ * createECDH
2189
+ * } = await import('crypto');
2190
+ *
2191
+ * // Generate Alice's keys...
2192
+ * const alice = createECDH('secp521r1');
2193
+ * const aliceKey = alice.generateKeys();
2194
+ *
2195
+ * // Generate Bob's keys...
2196
+ * const bob = createECDH('secp521r1');
2197
+ * const bobKey = bob.generateKeys();
2198
+ *
2199
+ * // Exchange and generate the secret...
2200
+ * const aliceSecret = alice.computeSecret(bobKey);
2201
+ * const bobSecret = bob.computeSecret(aliceKey);
2202
+ *
2203
+ * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex'));
2204
+ * // OK
2205
+ * ```
2206
+ * @since v0.11.14
2207
+ */
569
2208
  class ECDH {
570
2209
  private constructor();
2210
+ /**
2211
+ * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the
2212
+ * format specified by `format`. The `format` argument specifies point encoding
2213
+ * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is
2214
+ * interpreted using the specified `inputEncoding`, and the returned key is encoded
2215
+ * using the specified `outputEncoding`.
2216
+ *
2217
+ * Use {@link getCurves} to obtain a list of available curve names.
2218
+ * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display
2219
+ * the name and description of each available elliptic curve.
2220
+ *
2221
+ * If `format` is not specified the point will be returned in `'uncompressed'`format.
2222
+ *
2223
+ * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`,`TypedArray`, or `DataView`.
2224
+ *
2225
+ * Example (uncompressing a key):
2226
+ *
2227
+ * ```js
2228
+ * const {
2229
+ * createECDH,
2230
+ * ECDH
2231
+ * } = await import('crypto');
2232
+ *
2233
+ * const ecdh = createECDH('secp256k1');
2234
+ * ecdh.generateKeys();
2235
+ *
2236
+ * const compressedKey = ecdh.getPublicKey('hex', 'compressed');
2237
+ *
2238
+ * const uncompressedKey = ECDH.convertKey(compressedKey,
2239
+ * 'secp256k1',
2240
+ * 'hex',
2241
+ * 'hex',
2242
+ * 'uncompressed');
2243
+ *
2244
+ * // The converted key and the uncompressed public key should be the same
2245
+ * console.log(uncompressedKey === ecdh.getPublicKey('hex'));
2246
+ * ```
2247
+ * @since v10.0.0
2248
+ * @param inputEncoding The `encoding` of the `key` string.
2249
+ * @param outputEncoding The `encoding` of the return value.
2250
+ * @param [format='uncompressed']
2251
+ */
571
2252
  static convertKey(
572
2253
  key: BinaryLike,
573
2254
  curve: string,
574
2255
  inputEncoding?: BinaryToTextEncoding,
575
- outputEncoding?: 'latin1' | 'hex' | 'base64',
576
- format?: 'uncompressed' | 'compressed' | 'hybrid',
2256
+ outputEncoding?: 'latin1' | 'hex' | 'base64' | 'base64url',
2257
+ format?: 'uncompressed' | 'compressed' | 'hybrid'
577
2258
  ): Buffer | string;
2259
+ /**
2260
+ * Generates private and public EC Diffie-Hellman key values, and returns
2261
+ * the public key in the specified `format` and `encoding`. This key should be
2262
+ * transferred to the other party.
2263
+ *
2264
+ * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format.
2265
+ *
2266
+ * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned.
2267
+ * @since v0.11.14
2268
+ * @param encoding The `encoding` of the return value.
2269
+ * @param [format='uncompressed']
2270
+ */
578
2271
  generateKeys(): Buffer;
579
2272
  generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string;
580
- computeSecret(other_public_key: NodeJS.ArrayBufferView): Buffer;
581
- computeSecret(other_public_key: string, input_encoding: BinaryToTextEncoding): Buffer;
582
- computeSecret(other_public_key: NodeJS.ArrayBufferView, output_encoding: BinaryToTextEncoding): string;
583
- computeSecret(
584
- other_public_key: string,
585
- input_encoding: BinaryToTextEncoding,
586
- output_encoding: BinaryToTextEncoding,
587
- ): string;
2273
+ /**
2274
+ * Computes the shared secret using `otherPublicKey` as the other
2275
+ * party's public key and returns the computed shared secret. The supplied
2276
+ * key is interpreted using specified `inputEncoding`, and the returned secret
2277
+ * is encoded using the specified `outputEncoding`.
2278
+ * If the `inputEncoding` is not
2279
+ * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or`DataView`.
2280
+ *
2281
+ * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned.
2282
+ *
2283
+ * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey`lies outside of the elliptic curve. Since `otherPublicKey` is
2284
+ * usually supplied from a remote user over an insecure network,
2285
+ * be sure to handle this exception accordingly.
2286
+ * @since v0.11.14
2287
+ * @param inputEncoding The `encoding` of the `otherPublicKey` string.
2288
+ * @param outputEncoding The `encoding` of the return value.
2289
+ */
2290
+ computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer;
2291
+ computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer;
2292
+ computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string;
2293
+ computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding: BinaryToTextEncoding): string;
2294
+ /**
2295
+ * If `encoding` is specified, a string is returned; otherwise a `Buffer` is
2296
+ * returned.
2297
+ * @since v0.11.14
2298
+ * @param encoding The `encoding` of the return value.
2299
+ * @return The EC Diffie-Hellman in the specified `encoding`.
2300
+ */
588
2301
  getPrivateKey(): Buffer;
589
2302
  getPrivateKey(encoding: BinaryToTextEncoding): string;
590
- getPublicKey(): Buffer;
2303
+ /**
2304
+ * The `format` argument specifies point encoding and can be `'compressed'` or`'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format.
2305
+ *
2306
+ * If `encoding` is specified, a string is returned; otherwise a `Buffer` is
2307
+ * returned.
2308
+ * @since v0.11.14
2309
+ * @param [encoding] The `encoding` of the return value.
2310
+ * @param [format='uncompressed']
2311
+ * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`.
2312
+ */
2313
+ getPublicKey(encoding?: null, format?: ECDHKeyFormat): Buffer;
591
2314
  getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string;
592
- setPrivateKey(private_key: NodeJS.ArrayBufferView): void;
593
- setPrivateKey(private_key: string, encoding: BinaryToTextEncoding): void;
2315
+ /**
2316
+ * Sets the EC Diffie-Hellman private key.
2317
+ * If `encoding` is provided, `privateKey` is expected
2318
+ * to be a string; otherwise `privateKey` is expected to be a `Buffer`,`TypedArray`, or `DataView`.
2319
+ *
2320
+ * If `privateKey` is not valid for the curve specified when the `ECDH` object was
2321
+ * created, an error is thrown. Upon setting the private key, the associated
2322
+ * public point (key) is also generated and set in the `ECDH` object.
2323
+ * @since v0.11.14
2324
+ * @param encoding The `encoding` of the `privateKey` string.
2325
+ */
2326
+ setPrivateKey(privateKey: NodeJS.ArrayBufferView): void;
2327
+ setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void;
594
2328
  }
595
- function createECDH(curve_name: string): ECDH;
2329
+ /**
2330
+ * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a
2331
+ * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent
2332
+ * OpenSSL releases, `openssl ecparam -list_curves` will also display the name
2333
+ * and description of each available elliptic curve.
2334
+ * @since v0.11.14
2335
+ */
2336
+ function createECDH(curveName: string): ECDH;
2337
+ /**
2338
+ * This function is based on a constant-time algorithm.
2339
+ * Returns true if `a` is equal to `b`, without leaking timing information that
2340
+ * would allow an attacker to guess one of the values. This is suitable for
2341
+ * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/).
2342
+ *
2343
+ * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they
2344
+ * must have the same byte length. An error is thrown if `a` and `b` have
2345
+ * different byte lengths.
2346
+ *
2347
+ * If at least one of `a` and `b` is a `TypedArray` with more than one byte per
2348
+ * entry, such as `Uint16Array`, the result will be computed using the platform
2349
+ * byte order.
2350
+ *
2351
+ * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code
2352
+ * is timing-safe. Care should be taken to ensure that the surrounding code does
2353
+ * not introduce timing vulnerabilities.
2354
+ * @since v6.6.0
2355
+ */
596
2356
  function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean;
597
2357
  /** @deprecated since v10.0.0 */
598
2358
  const DEFAULT_ENCODING: BufferEncoding;
599
-
600
- type KeyType = 'rsa' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448';
601
- type KeyFormat = 'pem' | 'der';
602
-
2359
+ type KeyType = 'rsa' | 'rsa-pss' | 'dsa' | 'ec' | 'ed25519' | 'ed448' | 'x25519' | 'x448';
2360
+ type KeyFormat = 'pem' | 'der' | 'jwk';
603
2361
  interface BasePrivateKeyEncodingOptions<T extends KeyFormat> {
604
2362
  format: T;
605
- cipher?: string;
606
- passphrase?: string;
2363
+ cipher?: string | undefined;
2364
+ passphrase?: string | undefined;
607
2365
  }
608
-
609
2366
  interface KeyPairKeyObjectResult {
610
2367
  publicKey: KeyObject;
611
2368
  privateKey: KeyObject;
612
2369
  }
613
-
614
- interface ED25519KeyPairKeyObjectOptions {
2370
+ interface ED25519KeyPairKeyObjectOptions {}
2371
+ interface ED448KeyPairKeyObjectOptions {}
2372
+ interface X25519KeyPairKeyObjectOptions {}
2373
+ interface X448KeyPairKeyObjectOptions {}
2374
+ interface ECKeyPairKeyObjectOptions {
615
2375
  /**
616
- * No options.
2376
+ * Name of the curve to use
617
2377
  */
2378
+ namedCurve: string;
618
2379
  }
619
-
620
- interface ED448KeyPairKeyObjectOptions {
2380
+ interface RSAKeyPairKeyObjectOptions {
621
2381
  /**
622
- * No options.
2382
+ * Key size in bits
623
2383
  */
624
- }
625
-
626
- interface X25519KeyPairKeyObjectOptions {
2384
+ modulusLength: number;
627
2385
  /**
628
- * No options.
2386
+ * Public exponent
2387
+ * @default 0x10001
629
2388
  */
2389
+ publicExponent?: number | undefined;
630
2390
  }
631
-
632
- interface X448KeyPairKeyObjectOptions {
2391
+ interface RSAPSSKeyPairKeyObjectOptions {
633
2392
  /**
634
- * No options.
2393
+ * Key size in bits
635
2394
  */
636
- }
637
-
638
- interface ECKeyPairKeyObjectOptions {
2395
+ modulusLength: number;
639
2396
  /**
640
- * Name of the curve to use.
2397
+ * Public exponent
2398
+ * @default 0x10001
641
2399
  */
642
- namedCurve: string;
643
- }
644
-
645
- interface RSAKeyPairKeyObjectOptions {
2400
+ publicExponent?: number | undefined;
646
2401
  /**
647
- * Key size in bits
2402
+ * Name of the message digest
648
2403
  */
649
- modulusLength: number;
650
-
2404
+ hashAlgorithm?: string;
651
2405
  /**
652
- * @default 0x10001
2406
+ * Name of the message digest used by MGF1
2407
+ */
2408
+ mgf1HashAlgorithm?: string;
2409
+ /**
2410
+ * Minimal salt length in bytes
653
2411
  */
654
- publicExponent?: number;
2412
+ saltLength?: string;
655
2413
  }
656
-
657
2414
  interface DSAKeyPairKeyObjectOptions {
658
2415
  /**
659
2416
  * Key size in bits
660
2417
  */
661
2418
  modulusLength: number;
662
-
663
2419
  /**
664
2420
  * Size of q in bits
665
2421
  */
666
2422
  divisorLength: number;
667
2423
  }
668
-
669
2424
  interface RSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
670
2425
  /**
671
2426
  * Key size in bits
672
2427
  */
673
2428
  modulusLength: number;
674
2429
  /**
2430
+ * Public exponent
675
2431
  * @default 0x10001
676
2432
  */
677
- publicExponent?: number;
678
-
2433
+ publicExponent?: number | undefined;
679
2434
  publicKeyEncoding: {
680
2435
  type: 'pkcs1' | 'spki';
681
2436
  format: PubF;
@@ -684,7 +2439,36 @@ declare module 'crypto' {
684
2439
  type: 'pkcs1' | 'pkcs8';
685
2440
  };
686
2441
  }
687
-
2442
+ interface RSAPSSKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
2443
+ /**
2444
+ * Key size in bits
2445
+ */
2446
+ modulusLength: number;
2447
+ /**
2448
+ * Public exponent
2449
+ * @default 0x10001
2450
+ */
2451
+ publicExponent?: number | undefined;
2452
+ /**
2453
+ * Name of the message digest
2454
+ */
2455
+ hashAlgorithm?: string;
2456
+ /**
2457
+ * Name of the message digest used by MGF1
2458
+ */
2459
+ mgf1HashAlgorithm?: string;
2460
+ /**
2461
+ * Minimal salt length in bytes
2462
+ */
2463
+ saltLength?: string;
2464
+ publicKeyEncoding: {
2465
+ type: 'spki';
2466
+ format: PubF;
2467
+ };
2468
+ privateKeyEncoding: BasePrivateKeyEncodingOptions<PrivF> & {
2469
+ type: 'pkcs8';
2470
+ };
2471
+ }
688
2472
  interface DSAKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
689
2473
  /**
690
2474
  * Key size in bits
@@ -694,7 +2478,6 @@ declare module 'crypto' {
694
2478
  * Size of q in bits
695
2479
  */
696
2480
  divisorLength: number;
697
-
698
2481
  publicKeyEncoding: {
699
2482
  type: 'spki';
700
2483
  format: PubF;
@@ -703,13 +2486,11 @@ declare module 'crypto' {
703
2486
  type: 'pkcs8';
704
2487
  };
705
2488
  }
706
-
707
2489
  interface ECKeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
708
2490
  /**
709
2491
  * Name of the curve to use.
710
2492
  */
711
2493
  namedCurve: string;
712
-
713
2494
  publicKeyEncoding: {
714
2495
  type: 'pkcs1' | 'spki';
715
2496
  format: PubF;
@@ -718,7 +2499,6 @@ declare module 'crypto' {
718
2499
  type: 'sec1' | 'pkcs8';
719
2500
  };
720
2501
  }
721
-
722
2502
  interface ED25519KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
723
2503
  publicKeyEncoding: {
724
2504
  type: 'spki';
@@ -728,7 +2508,6 @@ declare module 'crypto' {
728
2508
  type: 'pkcs8';
729
2509
  };
730
2510
  }
731
-
732
2511
  interface ED448KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
733
2512
  publicKeyEncoding: {
734
2513
  type: 'spki';
@@ -738,7 +2517,6 @@ declare module 'crypto' {
738
2517
  type: 'pkcs8';
739
2518
  };
740
2519
  }
741
-
742
2520
  interface X25519KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
743
2521
  publicKeyEncoding: {
744
2522
  type: 'spki';
@@ -748,7 +2526,6 @@ declare module 'crypto' {
748
2526
  type: 'pkcs8';
749
2527
  };
750
2528
  }
751
-
752
2529
  interface X448KeyPairOptions<PubF extends KeyFormat, PrivF extends KeyFormat> {
753
2530
  publicKeyEncoding: {
754
2531
  type: 'spki';
@@ -758,488 +2535,440 @@ declare module 'crypto' {
758
2535
  type: 'pkcs8';
759
2536
  };
760
2537
  }
761
-
762
2538
  interface KeyPairSyncResult<T1 extends string | Buffer, T2 extends string | Buffer> {
763
2539
  publicKey: T1;
764
2540
  privateKey: T2;
765
2541
  }
766
-
767
- function generateKeyPairSync(
768
- type: 'rsa',
769
- options: RSAKeyPairOptions<'pem', 'pem'>,
770
- ): KeyPairSyncResult<string, string>;
771
- function generateKeyPairSync(
772
- type: 'rsa',
773
- options: RSAKeyPairOptions<'pem', 'der'>,
774
- ): KeyPairSyncResult<string, Buffer>;
775
- function generateKeyPairSync(
776
- type: 'rsa',
777
- options: RSAKeyPairOptions<'der', 'pem'>,
778
- ): KeyPairSyncResult<Buffer, string>;
779
- function generateKeyPairSync(
780
- type: 'rsa',
781
- options: RSAKeyPairOptions<'der', 'der'>,
782
- ): KeyPairSyncResult<Buffer, Buffer>;
2542
+ /**
2543
+ * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC,
2544
+ * Ed25519, Ed448, X25519, X448, and DH are currently supported.
2545
+ *
2546
+ * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
2547
+ * behaves as if `keyObject.export()` had been called on its result. Otherwise,
2548
+ * the respective part of the key is returned as a `KeyObject`.
2549
+ *
2550
+ * When encoding public keys, it is recommended to use `'spki'`. When encoding
2551
+ * private keys, it is recommended to use `'pkcs8'` with a strong passphrase,
2552
+ * and to keep the passphrase confidential.
2553
+ *
2554
+ * ```js
2555
+ * const {
2556
+ * generateKeyPairSync
2557
+ * } = await import('crypto');
2558
+ *
2559
+ * const {
2560
+ * publicKey,
2561
+ * privateKey,
2562
+ * } = generateKeyPairSync('rsa', {
2563
+ * modulusLength: 4096,
2564
+ * publicKeyEncoding: {
2565
+ * type: 'spki',
2566
+ * format: 'pem'
2567
+ * },
2568
+ * privateKeyEncoding: {
2569
+ * type: 'pkcs8',
2570
+ * format: 'pem',
2571
+ * cipher: 'aes-256-cbc',
2572
+ * passphrase: 'top secret'
2573
+ * }
2574
+ * });
2575
+ * ```
2576
+ *
2577
+ * The return value `{ publicKey, privateKey }` represents the generated key pair.
2578
+ * When PEM encoding was selected, the respective key will be a string, otherwise
2579
+ * it will be a buffer containing the data encoded as DER.
2580
+ * @since v10.12.0
2581
+ * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.
2582
+ */
2583
+ function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
2584
+ function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
2585
+ function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
2586
+ function generateKeyPairSync(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
783
2587
  function generateKeyPairSync(type: 'rsa', options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
784
-
785
- function generateKeyPairSync(
786
- type: 'dsa',
787
- options: DSAKeyPairOptions<'pem', 'pem'>,
788
- ): KeyPairSyncResult<string, string>;
789
- function generateKeyPairSync(
790
- type: 'dsa',
791
- options: DSAKeyPairOptions<'pem', 'der'>,
792
- ): KeyPairSyncResult<string, Buffer>;
793
- function generateKeyPairSync(
794
- type: 'dsa',
795
- options: DSAKeyPairOptions<'der', 'pem'>,
796
- ): KeyPairSyncResult<Buffer, string>;
797
- function generateKeyPairSync(
798
- type: 'dsa',
799
- options: DSAKeyPairOptions<'der', 'der'>,
800
- ): KeyPairSyncResult<Buffer, Buffer>;
2588
+ function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
2589
+ function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
2590
+ function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
2591
+ function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
2592
+ function generateKeyPairSync(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
2593
+ function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
2594
+ function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
2595
+ function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
2596
+ function generateKeyPairSync(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
801
2597
  function generateKeyPairSync(type: 'dsa', options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
802
-
803
- function generateKeyPairSync(
804
- type: 'ec',
805
- options: ECKeyPairOptions<'pem', 'pem'>,
806
- ): KeyPairSyncResult<string, string>;
807
- function generateKeyPairSync(
808
- type: 'ec',
809
- options: ECKeyPairOptions<'pem', 'der'>,
810
- ): KeyPairSyncResult<string, Buffer>;
811
- function generateKeyPairSync(
812
- type: 'ec',
813
- options: ECKeyPairOptions<'der', 'pem'>,
814
- ): KeyPairSyncResult<Buffer, string>;
815
- function generateKeyPairSync(
816
- type: 'ec',
817
- options: ECKeyPairOptions<'der', 'der'>,
818
- ): KeyPairSyncResult<Buffer, Buffer>;
2598
+ function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
2599
+ function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
2600
+ function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
2601
+ function generateKeyPairSync(type: 'ec', options: ECKeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
819
2602
  function generateKeyPairSync(type: 'ec', options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult;
820
-
821
- function generateKeyPairSync(
822
- type: 'ed25519',
823
- options: ED25519KeyPairOptions<'pem', 'pem'>,
824
- ): KeyPairSyncResult<string, string>;
825
- function generateKeyPairSync(
826
- type: 'ed25519',
827
- options: ED25519KeyPairOptions<'pem', 'der'>,
828
- ): KeyPairSyncResult<string, Buffer>;
829
- function generateKeyPairSync(
830
- type: 'ed25519',
831
- options: ED25519KeyPairOptions<'der', 'pem'>,
832
- ): KeyPairSyncResult<Buffer, string>;
833
- function generateKeyPairSync(
834
- type: 'ed25519',
835
- options: ED25519KeyPairOptions<'der', 'der'>,
836
- ): KeyPairSyncResult<Buffer, Buffer>;
2603
+ function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
2604
+ function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
2605
+ function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
2606
+ function generateKeyPairSync(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
837
2607
  function generateKeyPairSync(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
838
-
839
- function generateKeyPairSync(
840
- type: 'ed448',
841
- options: ED448KeyPairOptions<'pem', 'pem'>,
842
- ): KeyPairSyncResult<string, string>;
843
- function generateKeyPairSync(
844
- type: 'ed448',
845
- options: ED448KeyPairOptions<'pem', 'der'>,
846
- ): KeyPairSyncResult<string, Buffer>;
847
- function generateKeyPairSync(
848
- type: 'ed448',
849
- options: ED448KeyPairOptions<'der', 'pem'>,
850
- ): KeyPairSyncResult<Buffer, string>;
851
- function generateKeyPairSync(
852
- type: 'ed448',
853
- options: ED448KeyPairOptions<'der', 'der'>,
854
- ): KeyPairSyncResult<Buffer, Buffer>;
2608
+ function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
2609
+ function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
2610
+ function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
2611
+ function generateKeyPairSync(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
855
2612
  function generateKeyPairSync(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
856
-
857
- function generateKeyPairSync(
858
- type: 'x25519',
859
- options: X25519KeyPairOptions<'pem', 'pem'>,
860
- ): KeyPairSyncResult<string, string>;
861
- function generateKeyPairSync(
862
- type: 'x25519',
863
- options: X25519KeyPairOptions<'pem', 'der'>,
864
- ): KeyPairSyncResult<string, Buffer>;
865
- function generateKeyPairSync(
866
- type: 'x25519',
867
- options: X25519KeyPairOptions<'der', 'pem'>,
868
- ): KeyPairSyncResult<Buffer, string>;
869
- function generateKeyPairSync(
870
- type: 'x25519',
871
- options: X25519KeyPairOptions<'der', 'der'>,
872
- ): KeyPairSyncResult<Buffer, Buffer>;
2613
+ function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
2614
+ function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
2615
+ function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
2616
+ function generateKeyPairSync(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
873
2617
  function generateKeyPairSync(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
874
-
875
- function generateKeyPairSync(
876
- type: 'x448',
877
- options: X448KeyPairOptions<'pem', 'pem'>,
878
- ): KeyPairSyncResult<string, string>;
879
- function generateKeyPairSync(
880
- type: 'x448',
881
- options: X448KeyPairOptions<'pem', 'der'>,
882
- ): KeyPairSyncResult<string, Buffer>;
883
- function generateKeyPairSync(
884
- type: 'x448',
885
- options: X448KeyPairOptions<'der', 'pem'>,
886
- ): KeyPairSyncResult<Buffer, string>;
887
- function generateKeyPairSync(
888
- type: 'x448',
889
- options: X448KeyPairOptions<'der', 'der'>,
890
- ): KeyPairSyncResult<Buffer, Buffer>;
2618
+ function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>): KeyPairSyncResult<string, string>;
2619
+ function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>): KeyPairSyncResult<string, Buffer>;
2620
+ function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>): KeyPairSyncResult<Buffer, string>;
2621
+ function generateKeyPairSync(type: 'x448', options: X448KeyPairOptions<'der', 'der'>): KeyPairSyncResult<Buffer, Buffer>;
891
2622
  function generateKeyPairSync(type: 'x448', options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult;
892
-
893
- function generateKeyPair(
894
- type: 'rsa',
895
- options: RSAKeyPairOptions<'pem', 'pem'>,
896
- callback: (err: Error | null, publicKey: string, privateKey: string) => void,
897
- ): void;
898
- function generateKeyPair(
899
- type: 'rsa',
900
- options: RSAKeyPairOptions<'pem', 'der'>,
901
- callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
902
- ): void;
903
- function generateKeyPair(
904
- type: 'rsa',
905
- options: RSAKeyPairOptions<'der', 'pem'>,
906
- callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
907
- ): void;
908
- function generateKeyPair(
909
- type: 'rsa',
910
- options: RSAKeyPairOptions<'der', 'der'>,
911
- callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
912
- ): void;
913
- function generateKeyPair(
914
- type: 'rsa',
915
- options: RSAKeyPairKeyObjectOptions,
916
- callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
917
- ): void;
918
-
919
- function generateKeyPair(
920
- type: 'dsa',
921
- options: DSAKeyPairOptions<'pem', 'pem'>,
922
- callback: (err: Error | null, publicKey: string, privateKey: string) => void,
923
- ): void;
924
- function generateKeyPair(
925
- type: 'dsa',
926
- options: DSAKeyPairOptions<'pem', 'der'>,
927
- callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
928
- ): void;
929
- function generateKeyPair(
930
- type: 'dsa',
931
- options: DSAKeyPairOptions<'der', 'pem'>,
932
- callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
933
- ): void;
934
- function generateKeyPair(
935
- type: 'dsa',
936
- options: DSAKeyPairOptions<'der', 'der'>,
937
- callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
938
- ): void;
939
- function generateKeyPair(
940
- type: 'dsa',
941
- options: DSAKeyPairKeyObjectOptions,
942
- callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
943
- ): void;
944
-
945
- function generateKeyPair(
946
- type: 'ec',
947
- options: ECKeyPairOptions<'pem', 'pem'>,
948
- callback: (err: Error | null, publicKey: string, privateKey: string) => void,
949
- ): void;
950
- function generateKeyPair(
951
- type: 'ec',
952
- options: ECKeyPairOptions<'pem', 'der'>,
953
- callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
954
- ): void;
955
- function generateKeyPair(
956
- type: 'ec',
957
- options: ECKeyPairOptions<'der', 'pem'>,
958
- callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
959
- ): void;
960
- function generateKeyPair(
961
- type: 'ec',
962
- options: ECKeyPairOptions<'der', 'der'>,
963
- callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
964
- ): void;
965
- function generateKeyPair(
966
- type: 'ec',
967
- options: ECKeyPairKeyObjectOptions,
968
- callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
969
- ): void;
970
-
971
- function generateKeyPair(
972
- type: 'ed25519',
973
- options: ED25519KeyPairOptions<'pem', 'pem'>,
974
- callback: (err: Error | null, publicKey: string, privateKey: string) => void,
975
- ): void;
976
- function generateKeyPair(
977
- type: 'ed25519',
978
- options: ED25519KeyPairOptions<'pem', 'der'>,
979
- callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
980
- ): void;
981
- function generateKeyPair(
982
- type: 'ed25519',
983
- options: ED25519KeyPairOptions<'der', 'pem'>,
984
- callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
985
- ): void;
986
- function generateKeyPair(
987
- type: 'ed25519',
988
- options: ED25519KeyPairOptions<'der', 'der'>,
989
- callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
990
- ): void;
991
- function generateKeyPair(
992
- type: 'ed25519',
993
- options: ED25519KeyPairKeyObjectOptions | undefined,
994
- callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
995
- ): void;
996
-
997
- function generateKeyPair(
998
- type: 'ed448',
999
- options: ED448KeyPairOptions<'pem', 'pem'>,
1000
- callback: (err: Error | null, publicKey: string, privateKey: string) => void,
1001
- ): void;
1002
- function generateKeyPair(
1003
- type: 'ed448',
1004
- options: ED448KeyPairOptions<'pem', 'der'>,
1005
- callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
1006
- ): void;
1007
- function generateKeyPair(
1008
- type: 'ed448',
1009
- options: ED448KeyPairOptions<'der', 'pem'>,
1010
- callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
1011
- ): void;
1012
- function generateKeyPair(
1013
- type: 'ed448',
1014
- options: ED448KeyPairOptions<'der', 'der'>,
1015
- callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
1016
- ): void;
1017
- function generateKeyPair(
1018
- type: 'ed448',
1019
- options: ED448KeyPairKeyObjectOptions | undefined,
1020
- callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
1021
- ): void;
1022
-
1023
- function generateKeyPair(
1024
- type: 'x25519',
1025
- options: X25519KeyPairOptions<'pem', 'pem'>,
1026
- callback: (err: Error | null, publicKey: string, privateKey: string) => void,
1027
- ): void;
1028
- function generateKeyPair(
1029
- type: 'x25519',
1030
- options: X25519KeyPairOptions<'pem', 'der'>,
1031
- callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
1032
- ): void;
1033
- function generateKeyPair(
1034
- type: 'x25519',
1035
- options: X25519KeyPairOptions<'der', 'pem'>,
1036
- callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
1037
- ): void;
1038
- function generateKeyPair(
1039
- type: 'x25519',
1040
- options: X25519KeyPairOptions<'der', 'der'>,
1041
- callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
1042
- ): void;
1043
- function generateKeyPair(
1044
- type: 'x25519',
1045
- options: X25519KeyPairKeyObjectOptions | undefined,
1046
- callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
1047
- ): void;
1048
-
1049
- function generateKeyPair(
1050
- type: 'x448',
1051
- options: X448KeyPairOptions<'pem', 'pem'>,
1052
- callback: (err: Error | null, publicKey: string, privateKey: string) => void,
1053
- ): void;
1054
- function generateKeyPair(
1055
- type: 'x448',
1056
- options: X448KeyPairOptions<'pem', 'der'>,
1057
- callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void,
1058
- ): void;
1059
- function generateKeyPair(
1060
- type: 'x448',
1061
- options: X448KeyPairOptions<'der', 'pem'>,
1062
- callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void,
1063
- ): void;
1064
- function generateKeyPair(
1065
- type: 'x448',
1066
- options: X448KeyPairOptions<'der', 'der'>,
1067
- callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void,
1068
- ): void;
1069
- function generateKeyPair(
1070
- type: 'x448',
1071
- options: X448KeyPairKeyObjectOptions | undefined,
1072
- callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void,
1073
- ): void;
1074
-
2623
+ /**
2624
+ * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC,
2625
+ * Ed25519, Ed448, X25519, X448, and DH are currently supported.
2626
+ *
2627
+ * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
2628
+ * behaves as if `keyObject.export()` had been called on its result. Otherwise,
2629
+ * the respective part of the key is returned as a `KeyObject`.
2630
+ *
2631
+ * It is recommended to encode public keys as `'spki'` and private keys as`'pkcs8'` with encryption for long-term storage:
2632
+ *
2633
+ * ```js
2634
+ * const {
2635
+ * generateKeyPair
2636
+ * } = await import('crypto');
2637
+ *
2638
+ * generateKeyPair('rsa', {
2639
+ * modulusLength: 4096,
2640
+ * publicKeyEncoding: {
2641
+ * type: 'spki',
2642
+ * format: 'pem'
2643
+ * },
2644
+ * privateKeyEncoding: {
2645
+ * type: 'pkcs8',
2646
+ * format: 'pem',
2647
+ * cipher: 'aes-256-cbc',
2648
+ * passphrase: 'top secret'
2649
+ * }
2650
+ * }, (err, publicKey, privateKey) => {
2651
+ * // Handle errors and use the generated key pair.
2652
+ * });
2653
+ * ```
2654
+ *
2655
+ * On completion, `callback` will be called with `err` set to `undefined` and`publicKey` / `privateKey` representing the generated key pair.
2656
+ *
2657
+ * If this method is invoked as its `util.promisify()` ed version, it returns
2658
+ * a `Promise` for an `Object` with `publicKey` and `privateKey` properties.
2659
+ * @since v10.12.0
2660
+ * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`.
2661
+ */
2662
+ function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
2663
+ function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
2664
+ function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
2665
+ function generateKeyPair(type: 'rsa', options: RSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
2666
+ function generateKeyPair(type: 'rsa', options: RSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
2667
+ function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
2668
+ function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
2669
+ function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
2670
+ function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
2671
+ function generateKeyPair(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
2672
+ function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
2673
+ function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
2674
+ function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
2675
+ function generateKeyPair(type: 'dsa', options: DSAKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
2676
+ function generateKeyPair(type: 'dsa', options: DSAKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
2677
+ function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
2678
+ function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
2679
+ function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
2680
+ function generateKeyPair(type: 'ec', options: ECKeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
2681
+ function generateKeyPair(type: 'ec', options: ECKeyPairKeyObjectOptions, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
2682
+ function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
2683
+ function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
2684
+ function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
2685
+ function generateKeyPair(type: 'ed25519', options: ED25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
2686
+ function generateKeyPair(type: 'ed25519', options: ED25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
2687
+ function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
2688
+ function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
2689
+ function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
2690
+ function generateKeyPair(type: 'ed448', options: ED448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
2691
+ function generateKeyPair(type: 'ed448', options: ED448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
2692
+ function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
2693
+ function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
2694
+ function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
2695
+ function generateKeyPair(type: 'x25519', options: X25519KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
2696
+ function generateKeyPair(type: 'x25519', options: X25519KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
2697
+ function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'pem'>, callback: (err: Error | null, publicKey: string, privateKey: string) => void): void;
2698
+ function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'pem', 'der'>, callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void): void;
2699
+ function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'pem'>, callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void): void;
2700
+ function generateKeyPair(type: 'x448', options: X448KeyPairOptions<'der', 'der'>, callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void): void;
2701
+ function generateKeyPair(type: 'x448', options: X448KeyPairKeyObjectOptions | undefined, callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void): void;
1075
2702
  namespace generateKeyPair {
1076
2703
  function __promisify__(
1077
2704
  type: 'rsa',
1078
- options: RSAKeyPairOptions<'pem', 'pem'>,
1079
- ): Promise<{ publicKey: string; privateKey: string }>;
2705
+ options: RSAKeyPairOptions<'pem', 'pem'>
2706
+ ): Promise<{
2707
+ publicKey: string;
2708
+ privateKey: string;
2709
+ }>;
1080
2710
  function __promisify__(
1081
2711
  type: 'rsa',
1082
- options: RSAKeyPairOptions<'pem', 'der'>,
1083
- ): Promise<{ publicKey: string; privateKey: Buffer }>;
2712
+ options: RSAKeyPairOptions<'pem', 'der'>
2713
+ ): Promise<{
2714
+ publicKey: string;
2715
+ privateKey: Buffer;
2716
+ }>;
1084
2717
  function __promisify__(
1085
2718
  type: 'rsa',
1086
- options: RSAKeyPairOptions<'der', 'pem'>,
1087
- ): Promise<{ publicKey: Buffer; privateKey: string }>;
2719
+ options: RSAKeyPairOptions<'der', 'pem'>
2720
+ ): Promise<{
2721
+ publicKey: Buffer;
2722
+ privateKey: string;
2723
+ }>;
1088
2724
  function __promisify__(
1089
2725
  type: 'rsa',
1090
- options: RSAKeyPairOptions<'der', 'der'>,
1091
- ): Promise<{ publicKey: Buffer; privateKey: Buffer }>;
2726
+ options: RSAKeyPairOptions<'der', 'der'>
2727
+ ): Promise<{
2728
+ publicKey: Buffer;
2729
+ privateKey: Buffer;
2730
+ }>;
1092
2731
  function __promisify__(type: 'rsa', options: RSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
1093
-
2732
+ function __promisify__(
2733
+ type: 'rsa-pss',
2734
+ options: RSAPSSKeyPairOptions<'pem', 'pem'>
2735
+ ): Promise<{
2736
+ publicKey: string;
2737
+ privateKey: string;
2738
+ }>;
2739
+ function __promisify__(
2740
+ type: 'rsa-pss',
2741
+ options: RSAPSSKeyPairOptions<'pem', 'der'>
2742
+ ): Promise<{
2743
+ publicKey: string;
2744
+ privateKey: Buffer;
2745
+ }>;
2746
+ function __promisify__(
2747
+ type: 'rsa-pss',
2748
+ options: RSAPSSKeyPairOptions<'der', 'pem'>
2749
+ ): Promise<{
2750
+ publicKey: Buffer;
2751
+ privateKey: string;
2752
+ }>;
2753
+ function __promisify__(
2754
+ type: 'rsa-pss',
2755
+ options: RSAPSSKeyPairOptions<'der', 'der'>
2756
+ ): Promise<{
2757
+ publicKey: Buffer;
2758
+ privateKey: Buffer;
2759
+ }>;
2760
+ function __promisify__(type: 'rsa-pss', options: RSAPSSKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
1094
2761
  function __promisify__(
1095
2762
  type: 'dsa',
1096
- options: DSAKeyPairOptions<'pem', 'pem'>,
1097
- ): Promise<{ publicKey: string; privateKey: string }>;
2763
+ options: DSAKeyPairOptions<'pem', 'pem'>
2764
+ ): Promise<{
2765
+ publicKey: string;
2766
+ privateKey: string;
2767
+ }>;
1098
2768
  function __promisify__(
1099
2769
  type: 'dsa',
1100
- options: DSAKeyPairOptions<'pem', 'der'>,
1101
- ): Promise<{ publicKey: string; privateKey: Buffer }>;
2770
+ options: DSAKeyPairOptions<'pem', 'der'>
2771
+ ): Promise<{
2772
+ publicKey: string;
2773
+ privateKey: Buffer;
2774
+ }>;
1102
2775
  function __promisify__(
1103
2776
  type: 'dsa',
1104
- options: DSAKeyPairOptions<'der', 'pem'>,
1105
- ): Promise<{ publicKey: Buffer; privateKey: string }>;
2777
+ options: DSAKeyPairOptions<'der', 'pem'>
2778
+ ): Promise<{
2779
+ publicKey: Buffer;
2780
+ privateKey: string;
2781
+ }>;
1106
2782
  function __promisify__(
1107
2783
  type: 'dsa',
1108
- options: DSAKeyPairOptions<'der', 'der'>,
1109
- ): Promise<{ publicKey: Buffer; privateKey: Buffer }>;
2784
+ options: DSAKeyPairOptions<'der', 'der'>
2785
+ ): Promise<{
2786
+ publicKey: Buffer;
2787
+ privateKey: Buffer;
2788
+ }>;
1110
2789
  function __promisify__(type: 'dsa', options: DSAKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
1111
-
1112
2790
  function __promisify__(
1113
2791
  type: 'ec',
1114
- options: ECKeyPairOptions<'pem', 'pem'>,
1115
- ): Promise<{ publicKey: string; privateKey: string }>;
2792
+ options: ECKeyPairOptions<'pem', 'pem'>
2793
+ ): Promise<{
2794
+ publicKey: string;
2795
+ privateKey: string;
2796
+ }>;
1116
2797
  function __promisify__(
1117
2798
  type: 'ec',
1118
- options: ECKeyPairOptions<'pem', 'der'>,
1119
- ): Promise<{ publicKey: string; privateKey: Buffer }>;
2799
+ options: ECKeyPairOptions<'pem', 'der'>
2800
+ ): Promise<{
2801
+ publicKey: string;
2802
+ privateKey: Buffer;
2803
+ }>;
1120
2804
  function __promisify__(
1121
2805
  type: 'ec',
1122
- options: ECKeyPairOptions<'der', 'pem'>,
1123
- ): Promise<{ publicKey: Buffer; privateKey: string }>;
2806
+ options: ECKeyPairOptions<'der', 'pem'>
2807
+ ): Promise<{
2808
+ publicKey: Buffer;
2809
+ privateKey: string;
2810
+ }>;
1124
2811
  function __promisify__(
1125
2812
  type: 'ec',
1126
- options: ECKeyPairOptions<'der', 'der'>,
1127
- ): Promise<{ publicKey: Buffer; privateKey: Buffer }>;
2813
+ options: ECKeyPairOptions<'der', 'der'>
2814
+ ): Promise<{
2815
+ publicKey: Buffer;
2816
+ privateKey: Buffer;
2817
+ }>;
1128
2818
  function __promisify__(type: 'ec', options: ECKeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
1129
-
1130
- function __promisify__(
1131
- type: 'ed25519',
1132
- options: ED25519KeyPairOptions<'pem', 'pem'>,
1133
- ): Promise<{ publicKey: string; privateKey: string }>;
1134
2819
  function __promisify__(
1135
2820
  type: 'ed25519',
1136
- options: ED25519KeyPairOptions<'pem', 'der'>,
1137
- ): Promise<{ publicKey: string; privateKey: Buffer }>;
2821
+ options: ED25519KeyPairOptions<'pem', 'pem'>
2822
+ ): Promise<{
2823
+ publicKey: string;
2824
+ privateKey: string;
2825
+ }>;
1138
2826
  function __promisify__(
1139
2827
  type: 'ed25519',
1140
- options: ED25519KeyPairOptions<'der', 'pem'>,
1141
- ): Promise<{ publicKey: Buffer; privateKey: string }>;
2828
+ options: ED25519KeyPairOptions<'pem', 'der'>
2829
+ ): Promise<{
2830
+ publicKey: string;
2831
+ privateKey: Buffer;
2832
+ }>;
1142
2833
  function __promisify__(
1143
2834
  type: 'ed25519',
1144
- options: ED25519KeyPairOptions<'der', 'der'>,
1145
- ): Promise<{ publicKey: Buffer; privateKey: Buffer }>;
2835
+ options: ED25519KeyPairOptions<'der', 'pem'>
2836
+ ): Promise<{
2837
+ publicKey: Buffer;
2838
+ privateKey: string;
2839
+ }>;
1146
2840
  function __promisify__(
1147
2841
  type: 'ed25519',
1148
- options?: ED25519KeyPairKeyObjectOptions,
1149
- ): Promise<KeyPairKeyObjectResult>;
1150
-
2842
+ options: ED25519KeyPairOptions<'der', 'der'>
2843
+ ): Promise<{
2844
+ publicKey: Buffer;
2845
+ privateKey: Buffer;
2846
+ }>;
2847
+ function __promisify__(type: 'ed25519', options?: ED25519KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
1151
2848
  function __promisify__(
1152
2849
  type: 'ed448',
1153
- options: ED448KeyPairOptions<'pem', 'pem'>,
1154
- ): Promise<{ publicKey: string; privateKey: string }>;
2850
+ options: ED448KeyPairOptions<'pem', 'pem'>
2851
+ ): Promise<{
2852
+ publicKey: string;
2853
+ privateKey: string;
2854
+ }>;
1155
2855
  function __promisify__(
1156
2856
  type: 'ed448',
1157
- options: ED448KeyPairOptions<'pem', 'der'>,
1158
- ): Promise<{ publicKey: string; privateKey: Buffer }>;
2857
+ options: ED448KeyPairOptions<'pem', 'der'>
2858
+ ): Promise<{
2859
+ publicKey: string;
2860
+ privateKey: Buffer;
2861
+ }>;
1159
2862
  function __promisify__(
1160
2863
  type: 'ed448',
1161
- options: ED448KeyPairOptions<'der', 'pem'>,
1162
- ): Promise<{ publicKey: Buffer; privateKey: string }>;
2864
+ options: ED448KeyPairOptions<'der', 'pem'>
2865
+ ): Promise<{
2866
+ publicKey: Buffer;
2867
+ privateKey: string;
2868
+ }>;
1163
2869
  function __promisify__(
1164
2870
  type: 'ed448',
1165
- options: ED448KeyPairOptions<'der', 'der'>,
1166
- ): Promise<{ publicKey: Buffer; privateKey: Buffer }>;
2871
+ options: ED448KeyPairOptions<'der', 'der'>
2872
+ ): Promise<{
2873
+ publicKey: Buffer;
2874
+ privateKey: Buffer;
2875
+ }>;
1167
2876
  function __promisify__(type: 'ed448', options?: ED448KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
1168
-
1169
- function __promisify__(
1170
- type: 'x25519',
1171
- options: X25519KeyPairOptions<'pem', 'pem'>,
1172
- ): Promise<{ publicKey: string; privateKey: string }>;
1173
2877
  function __promisify__(
1174
2878
  type: 'x25519',
1175
- options: X25519KeyPairOptions<'pem', 'der'>,
1176
- ): Promise<{ publicKey: string; privateKey: Buffer }>;
2879
+ options: X25519KeyPairOptions<'pem', 'pem'>
2880
+ ): Promise<{
2881
+ publicKey: string;
2882
+ privateKey: string;
2883
+ }>;
1177
2884
  function __promisify__(
1178
2885
  type: 'x25519',
1179
- options: X25519KeyPairOptions<'der', 'pem'>,
1180
- ): Promise<{ publicKey: Buffer; privateKey: string }>;
2886
+ options: X25519KeyPairOptions<'pem', 'der'>
2887
+ ): Promise<{
2888
+ publicKey: string;
2889
+ privateKey: Buffer;
2890
+ }>;
1181
2891
  function __promisify__(
1182
2892
  type: 'x25519',
1183
- options: X25519KeyPairOptions<'der', 'der'>,
1184
- ): Promise<{ publicKey: Buffer; privateKey: Buffer }>;
2893
+ options: X25519KeyPairOptions<'der', 'pem'>
2894
+ ): Promise<{
2895
+ publicKey: Buffer;
2896
+ privateKey: string;
2897
+ }>;
1185
2898
  function __promisify__(
1186
2899
  type: 'x25519',
1187
- options?: X25519KeyPairKeyObjectOptions,
1188
- ): Promise<KeyPairKeyObjectResult>;
1189
-
2900
+ options: X25519KeyPairOptions<'der', 'der'>
2901
+ ): Promise<{
2902
+ publicKey: Buffer;
2903
+ privateKey: Buffer;
2904
+ }>;
2905
+ function __promisify__(type: 'x25519', options?: X25519KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
1190
2906
  function __promisify__(
1191
2907
  type: 'x448',
1192
- options: X448KeyPairOptions<'pem', 'pem'>,
1193
- ): Promise<{ publicKey: string; privateKey: string }>;
2908
+ options: X448KeyPairOptions<'pem', 'pem'>
2909
+ ): Promise<{
2910
+ publicKey: string;
2911
+ privateKey: string;
2912
+ }>;
1194
2913
  function __promisify__(
1195
2914
  type: 'x448',
1196
- options: X448KeyPairOptions<'pem', 'der'>,
1197
- ): Promise<{ publicKey: string; privateKey: Buffer }>;
2915
+ options: X448KeyPairOptions<'pem', 'der'>
2916
+ ): Promise<{
2917
+ publicKey: string;
2918
+ privateKey: Buffer;
2919
+ }>;
1198
2920
  function __promisify__(
1199
2921
  type: 'x448',
1200
- options: X448KeyPairOptions<'der', 'pem'>,
1201
- ): Promise<{ publicKey: Buffer; privateKey: string }>;
2922
+ options: X448KeyPairOptions<'der', 'pem'>
2923
+ ): Promise<{
2924
+ publicKey: Buffer;
2925
+ privateKey: string;
2926
+ }>;
1202
2927
  function __promisify__(
1203
2928
  type: 'x448',
1204
- options: X448KeyPairOptions<'der', 'der'>,
1205
- ): Promise<{ publicKey: Buffer; privateKey: Buffer }>;
2929
+ options: X448KeyPairOptions<'der', 'der'>
2930
+ ): Promise<{
2931
+ publicKey: Buffer;
2932
+ privateKey: Buffer;
2933
+ }>;
1206
2934
  function __promisify__(type: 'x448', options?: X448KeyPairKeyObjectOptions): Promise<KeyPairKeyObjectResult>;
1207
2935
  }
1208
-
1209
2936
  /**
1210
2937
  * Calculates and returns the signature for `data` using the given private key and
1211
2938
  * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is
1212
2939
  * dependent upon the key type (especially Ed25519 and Ed448).
1213
2940
  *
1214
2941
  * If `key` is not a `KeyObject`, this function behaves as if `key` had been
1215
- * passed to `crypto.createPrivateKey().
2942
+ * passed to {@link createPrivateKey}. If it is an object, the following
2943
+ * additional properties can be passed:
2944
+ *
2945
+ * If the `callback` function is provided this function uses libuv's threadpool.
2946
+ * @since v12.0.0
1216
2947
  */
1217
- function sign(
1218
- algorithm: string | null | undefined,
1219
- data: NodeJS.ArrayBufferView,
1220
- key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput,
1221
- ): Buffer;
2948
+ function sign(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer;
1222
2949
  function sign(
1223
2950
  algorithm: string | null | undefined,
1224
2951
  data: NodeJS.ArrayBufferView,
1225
2952
  key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput,
1226
2953
  callback: (error: Error | null, data: Buffer) => void
1227
2954
  ): void;
1228
-
1229
2955
  /**
1230
- * Calculates and returns the signature for `data` using the given private key and
1231
- * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is
1232
- * dependent upon the key type (especially Ed25519 and Ed448).
2956
+ * Verifies the given signature for `data` using the given key and algorithm. If`algorithm` is `null` or `undefined`, then the algorithm is dependent upon the
2957
+ * key type (especially Ed25519 and Ed448).
1233
2958
  *
1234
2959
  * If `key` is not a `KeyObject`, this function behaves as if `key` had been
1235
- * passed to `crypto.createPublicKey()`.
2960
+ * passed to {@link createPublicKey}. If it is an object, the following
2961
+ * additional properties can be passed:
2962
+ *
2963
+ * The `signature` argument is the previously calculated signature for the `data`.
2964
+ *
2965
+ * Because public keys can be derived from private keys, a private key or a public
2966
+ * key may be passed for `key`.
2967
+ *
2968
+ * If the `callback` function is provided this function uses libuv's threadpool.
2969
+ * @since v12.0.0
1236
2970
  */
1237
- function verify(
1238
- algorithm: string | null | undefined,
1239
- data: NodeJS.ArrayBufferView,
1240
- key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput,
1241
- signature: NodeJS.ArrayBufferView,
1242
- ): boolean;
2971
+ function verify(algorithm: string | null | undefined, data: NodeJS.ArrayBufferView, key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput, signature: NodeJS.ArrayBufferView): boolean;
1243
2972
  function verify(
1244
2973
  algorithm: string | null | undefined,
1245
2974
  data: NodeJS.ArrayBufferView,
@@ -1247,27 +2976,23 @@ declare module 'crypto' {
1247
2976
  signature: NodeJS.ArrayBufferView,
1248
2977
  callback: (error: Error | null, result: boolean) => void
1249
2978
  ): void;
1250
-
1251
2979
  /**
1252
- * Computes the Diffie-Hellman secret based on a privateKey and a publicKey.
1253
- * Both keys must have the same asymmetricKeyType, which must be one of
1254
- * 'dh' (for Diffie-Hellman), 'ec' (for ECDH), 'x448', or 'x25519' (for ECDH-ES).
2980
+ * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`.
2981
+ * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'`(for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES).
2982
+ * @since v13.9.0, v12.17.0
1255
2983
  */
1256
2984
  function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer;
1257
-
1258
2985
  type CipherMode = 'cbc' | 'ccm' | 'cfb' | 'ctr' | 'ecb' | 'gcm' | 'ocb' | 'ofb' | 'stream' | 'wrap' | 'xts';
1259
-
1260
2986
  interface CipherInfoOptions {
1261
2987
  /**
1262
2988
  * A test key length.
1263
2989
  */
1264
- keyLength?: number;
2990
+ keyLength?: number | undefined;
1265
2991
  /**
1266
2992
  * A test IV length.
1267
2993
  */
1268
- ivLength?: number;
2994
+ ivLength?: number | undefined;
1269
2995
  }
1270
-
1271
2996
  interface CipherInfo {
1272
2997
  /**
1273
2998
  * The name of the cipher.
@@ -1281,12 +3006,12 @@ declare module 'crypto' {
1281
3006
  * The block size of the cipher in bytes.
1282
3007
  * This property is omitted when mode is 'stream'.
1283
3008
  */
1284
- blockSize?: number;
3009
+ blockSize?: number | undefined;
1285
3010
  /**
1286
3011
  * The expected or default initialization vector length in bytes.
1287
3012
  * This property is omitted if the cipher does not use an initialization vector.
1288
3013
  */
1289
- ivLength?: number;
3014
+ ivLength?: number | undefined;
1290
3015
  /**
1291
3016
  * The expected or default key length in bytes.
1292
3017
  */
@@ -1296,66 +3021,95 @@ declare module 'crypto' {
1296
3021
  */
1297
3022
  mode: CipherMode;
1298
3023
  }
1299
-
1300
3024
  /**
1301
3025
  * Returns information about a given cipher.
1302
3026
  *
1303
- * Some ciphers accept variable length keys and initialization vectors.
1304
- * By default, the `crypto.getCipherInfo()` method will return the default
1305
- * values for these ciphers. To test if a given key length or iv length
1306
- * is acceptable for given cipher, use the `keyLenth` and `ivLenth` options.
1307
- * If the given values are unacceptable, `undefined` will be returned.
3027
+ * Some ciphers accept variable length keys and initialization vectors. By default,
3028
+ * the `crypto.getCipherInfo()` method will return the default values for these
3029
+ * ciphers. To test if a given key length or iv length is acceptable for given
3030
+ * cipher, use the `keyLength` and `ivLength` options. If the given values are
3031
+ * unacceptable, `undefined` will be returned.
3032
+ * @since v15.0.0
1308
3033
  * @param nameOrNid The name or nid of the cipher to query.
1309
3034
  */
1310
3035
  function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined;
1311
-
1312
3036
  /**
1313
- * HKDF is a simple key derivation function defined in RFC 5869.
1314
- * The given `key`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes.
3037
+ * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`,`salt` and `info` are used with the `digest` to derive a key of `keylen` bytes.
3038
+ *
3039
+ * The supplied `callback` function is called with two arguments: `err` and`derivedKey`. If an errors occurs while deriving the key, `err` will be set;
3040
+ * otherwise `err` will be `null`. The successfully generated `derivedKey` will
3041
+ * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any
3042
+ * of the input arguments specify invalid values or types.
1315
3043
  *
1316
- * The supplied `callback` function is called with two arguments: `err` and `derivedKey`.
1317
- * If an errors occurs while deriving the key, `err` will be set; otherwise `err` will be `null`.
1318
- * The successfully generated `derivedKey` will be passed to the callback as an `ArrayBuffer`.
1319
- * An error will be thrown if any of the input aguments specify invalid values or types.
3044
+ * ```js
3045
+ * import { Buffer } from 'buffer';
3046
+ * const {
3047
+ * hkdf
3048
+ * } = await import('crypto');
3049
+ *
3050
+ * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => {
3051
+ * if (err) throw err;
3052
+ * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
3053
+ * });
3054
+ * ```
3055
+ * @since v15.0.0
3056
+ * @param digest The digest algorithm to use.
3057
+ * @param ikm The input keying material. It must be at least one byte in length.
3058
+ * @param salt The salt value. Must be provided but can be zero-length.
3059
+ * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.
3060
+ * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512`
3061
+ * generates 64-byte hashes, making the maximum HKDF output 16320 bytes).
1320
3062
  */
1321
- function hkdf(digest: string, key: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: ArrayBuffer) => any): void;
1322
-
3063
+ function hkdf(digest: string, irm: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number, callback: (err: Error | null, derivedKey: ArrayBuffer) => void): void;
1323
3064
  /**
1324
- * Provides a synchronous HKDF key derivation function as defined in RFC 5869.
1325
- * The given `key`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes.
3065
+ * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The
3066
+ * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of`keylen` bytes.
3067
+ *
3068
+ * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer).
3069
+ *
3070
+ * An error will be thrown if any of the input arguments specify invalid values or
3071
+ * types, or if the derived key cannot be generated.
3072
+ *
3073
+ * ```js
3074
+ * import { Buffer } from 'buffer';
3075
+ * const {
3076
+ * hkdfSync
3077
+ * } = await import('crypto');
1326
3078
  *
1327
- * The successfully generated `derivedKey` will be returned as an `ArrayBuffer`.
1328
- * An error will be thrown if any of the input aguments specify invalid values or types,
1329
- * or if the derived key cannot be generated.
3079
+ * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64);
3080
+ * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653'
3081
+ * ```
3082
+ * @since v15.0.0
3083
+ * @param digest The digest algorithm to use.
3084
+ * @param ikm The input keying material. It must be at least one byte in length.
3085
+ * @param salt The salt value. Must be provided but can be zero-length.
3086
+ * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes.
3087
+ * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512`
3088
+ * generates 64-byte hashes, making the maximum HKDF output 16320 bytes).
1330
3089
  */
1331
- function hkdfSync(digest: string, key: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number): ArrayBuffer;
1332
-
3090
+ function hkdfSync(digest: string, ikm: BinaryLike | KeyObject, salt: BinaryLike, info: BinaryLike, keylen: number): ArrayBuffer;
1333
3091
  interface SecureHeapUsage {
1334
3092
  /**
1335
3093
  * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag.
1336
3094
  */
1337
3095
  total: number;
1338
-
1339
3096
  /**
1340
3097
  * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag.
1341
3098
  */
1342
3099
  min: number;
1343
-
1344
3100
  /**
1345
3101
  * The total number of bytes currently allocated from the secure heap.
1346
3102
  */
1347
3103
  used: number;
1348
-
1349
3104
  /**
1350
3105
  * The calculated ratio of `used` to `total` allocated bytes.
1351
3106
  */
1352
3107
  utilization: number;
1353
3108
  }
1354
-
3109
+ /**
3110
+ * @since v15.6.0
3111
+ */
1355
3112
  function secureHeapUsed(): SecureHeapUsage;
1356
-
1357
- // TODO: X509Certificate
1358
-
1359
3113
  interface RandomUUIDOptions {
1360
3114
  /**
1361
3115
  * By default, to improve performance,
@@ -1365,216 +3119,846 @@ declare module 'crypto' {
1365
3119
  *
1366
3120
  * @default `false`
1367
3121
  */
1368
- disableEntropyCache?: boolean;
3122
+ disableEntropyCache?: boolean | undefined;
1369
3123
  }
1370
-
3124
+ /**
3125
+ * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a
3126
+ * cryptographic pseudorandom number generator.
3127
+ * @since v15.6.0, v14.17.0
3128
+ */
1371
3129
  function randomUUID(options?: RandomUUIDOptions): string;
1372
-
1373
3130
  interface X509CheckOptions {
1374
3131
  /**
1375
3132
  * @default 'always'
1376
3133
  */
1377
- subject: 'always' | 'never';
1378
-
3134
+ subject?: 'always' | 'default' | 'never';
1379
3135
  /**
1380
3136
  * @default true
1381
3137
  */
1382
- wildcards: boolean;
1383
-
3138
+ wildcards?: boolean;
1384
3139
  /**
1385
3140
  * @default true
1386
3141
  */
1387
- partialWildcards: boolean;
1388
-
3142
+ partialWildcards?: boolean;
1389
3143
  /**
1390
3144
  * @default false
1391
3145
  */
1392
- multiLabelWildcards: boolean;
1393
-
3146
+ multiLabelWildcards?: boolean;
1394
3147
  /**
1395
3148
  * @default false
1396
3149
  */
1397
- singleLabelSubdomains: boolean;
3150
+ singleLabelSubdomains?: boolean;
1398
3151
  }
1399
-
3152
+ /**
3153
+ * Encapsulates an X509 certificate and provides read-only access to
3154
+ * its information.
3155
+ *
3156
+ * ```js
3157
+ * const { X509Certificate } = await import('crypto');
3158
+ *
3159
+ * const x509 = new X509Certificate('{... pem encoded cert ...}');
3160
+ *
3161
+ * console.log(x509.subject);
3162
+ * ```
3163
+ * @since v15.6.0
3164
+ */
1400
3165
  class X509Certificate {
1401
3166
  /**
1402
- * Will be `true` if this is a Certificate Authority (ca) certificate.
3167
+ * Will be \`true\` if this is a Certificate Authority (CA) certificate.
3168
+ * @since v15.6.0
1403
3169
  */
1404
3170
  readonly ca: boolean;
1405
-
1406
3171
  /**
1407
3172
  * The SHA-1 fingerprint of this certificate.
3173
+ *
3174
+ * Because SHA-1 is cryptographically broken and because the security of SHA-1 is
3175
+ * significantly worse than that of algorithms that are commonly used to sign
3176
+ * certificates, consider using `x509.fingerprint256` instead.
3177
+ * @since v15.6.0
1408
3178
  */
1409
3179
  readonly fingerprint: string;
1410
-
1411
3180
  /**
1412
3181
  * The SHA-256 fingerprint of this certificate.
3182
+ * @since v15.6.0
1413
3183
  */
1414
3184
  readonly fingerprint256: string;
1415
-
3185
+ /**
3186
+ * The SHA-512 fingerprint of this certificate.
3187
+ * @since v16.14.0
3188
+ */
3189
+ readonly fingerprint512: string;
1416
3190
  /**
1417
3191
  * The complete subject of this certificate.
3192
+ * @since v15.6.0
1418
3193
  */
1419
3194
  readonly subject: string;
1420
-
1421
3195
  /**
1422
- * The subject alternative name specified for this certificate.
3196
+ * The subject alternative name specified for this certificate or `undefined`
3197
+ * if not available.
3198
+ * @since v15.6.0
1423
3199
  */
1424
- readonly subjectAltName: string;
1425
-
3200
+ readonly subjectAltName: string | undefined;
1426
3201
  /**
1427
- * The information access content of this certificate.
3202
+ * The information access content of this certificate or `undefined` if not
3203
+ * available.
3204
+ * @since v15.6.0
1428
3205
  */
1429
- readonly infoAccess: string;
1430
-
3206
+ readonly infoAccess: string | undefined;
1431
3207
  /**
1432
3208
  * An array detailing the key usages for this certificate.
3209
+ * @since v15.6.0
1433
3210
  */
1434
3211
  readonly keyUsage: string[];
1435
-
1436
3212
  /**
1437
3213
  * The issuer identification included in this certificate.
3214
+ * @since v15.6.0
1438
3215
  */
1439
3216
  readonly issuer: string;
1440
-
1441
3217
  /**
1442
- * The issuer certificate or `undefined` if the issuer certificate is not available.
3218
+ * The issuer certificate or `undefined` if the issuer certificate is not
3219
+ * available.
3220
+ * @since v15.9.0
1443
3221
  */
1444
- readonly issuerCertificate?: X509Certificate;
1445
-
3222
+ readonly issuerCertificate?: X509Certificate | undefined;
1446
3223
  /**
1447
- * The public key for this certificate.
3224
+ * The public key `KeyObject` for this certificate.
3225
+ * @since v15.6.0
1448
3226
  */
1449
3227
  readonly publicKey: KeyObject;
1450
-
1451
3228
  /**
1452
3229
  * A `Buffer` containing the DER encoding of this certificate.
3230
+ * @since v15.6.0
1453
3231
  */
1454
3232
  readonly raw: Buffer;
1455
-
1456
3233
  /**
1457
3234
  * The serial number of this certificate.
3235
+ *
3236
+ * Serial numbers are assigned by certificate authorities and do not uniquely
3237
+ * identify certificates. Consider using `x509.fingerprint256` as a unique
3238
+ * identifier instead.
3239
+ * @since v15.6.0
1458
3240
  */
1459
3241
  readonly serialNumber: string;
1460
-
1461
3242
  /**
1462
- * Returns the PEM-encoded certificate.
3243
+ * The date/time from which this certificate is considered valid.
3244
+ * @since v15.6.0
1463
3245
  */
1464
3246
  readonly validFrom: string;
1465
-
1466
3247
  /**
1467
- * The date/time from which this certificate is considered valid.
3248
+ * The date/time until which this certificate is considered valid.
3249
+ * @since v15.6.0
1468
3250
  */
1469
3251
  readonly validTo: string;
1470
-
1471
3252
  constructor(buffer: BinaryLike);
1472
-
1473
3253
  /**
1474
3254
  * Checks whether the certificate matches the given email address.
1475
3255
  *
1476
- * Returns `email` if the certificate matches,`undefined` if it does not.
3256
+ * If the `'subject'` option is undefined or set to `'default'`, the certificate
3257
+ * subject is only considered if the subject alternative name extension either does
3258
+ * not exist or does not contain any email addresses.
3259
+ *
3260
+ * If the `'subject'` option is set to `'always'` and if the subject alternative
3261
+ * name extension either does not exist or does not contain a matching email
3262
+ * address, the certificate subject is considered.
3263
+ *
3264
+ * If the `'subject'` option is set to `'never'`, the certificate subject is never
3265
+ * considered, even if the certificate contains no subject alternative names.
3266
+ * @since v15.6.0
3267
+ * @return Returns `email` if the certificate matches, `undefined` if it does not.
1477
3268
  */
1478
- checkEmail(email: string, options?: X509CheckOptions): string | undefined;
1479
-
3269
+ checkEmail(email: string, options?: Pick<X509CheckOptions, 'subject'>): string | undefined;
1480
3270
  /**
1481
3271
  * Checks whether the certificate matches the given host name.
1482
3272
  *
1483
- * Returns `name` if the certificate matches, `undefined` if it does not.
3273
+ * If the certificate matches the given host name, the matching subject name is
3274
+ * returned. The returned name might be an exact match (e.g., `foo.example.com`)
3275
+ * or it might contain wildcards (e.g., `*.example.com`). Because host name
3276
+ * comparisons are case-insensitive, the returned subject name might also differ
3277
+ * from the given `name` in capitalization.
3278
+ *
3279
+ * If the `'subject'` option is undefined or set to `'default'`, the certificate
3280
+ * subject is only considered if the subject alternative name extension either does
3281
+ * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS").
3282
+ *
3283
+ * If the `'subject'` option is set to `'always'` and if the subject alternative
3284
+ * name extension either does not exist or does not contain a matching DNS name,
3285
+ * the certificate subject is considered.
3286
+ *
3287
+ * If the `'subject'` option is set to `'never'`, the certificate subject is never
3288
+ * considered, even if the certificate contains no subject alternative names.
3289
+ * @since v15.6.0
3290
+ * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`.
1484
3291
  */
1485
3292
  checkHost(name: string, options?: X509CheckOptions): string | undefined;
1486
-
1487
3293
  /**
1488
3294
  * Checks whether the certificate matches the given IP address (IPv4 or IPv6).
1489
3295
  *
1490
- * Returns `ip` if the certificate matches, `undefined` if it does not.
3296
+ * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they
3297
+ * must match the given `ip` address exactly. Other subject alternative names as
3298
+ * well as the subject field of the certificate are ignored.
3299
+ * @since v15.6.0
3300
+ * @return Returns `ip` if the certificate matches, `undefined` if it does not.
1491
3301
  */
1492
- checkIP(ip: string, options?: X509CheckOptions): string | undefined;
1493
-
3302
+ checkIP(ip: string): string | undefined;
1494
3303
  /**
1495
3304
  * Checks whether this certificate was issued by the given `otherCert`.
3305
+ * @since v15.6.0
1496
3306
  */
1497
3307
  checkIssued(otherCert: X509Certificate): boolean;
1498
-
1499
3308
  /**
1500
- * Checks whether this certificate was issued by the given `otherCert`.
3309
+ * Checks whether the public key for this certificate is consistent with
3310
+ * the given private key.
3311
+ * @since v15.6.0
3312
+ * @param privateKey A private key.
1501
3313
  */
1502
3314
  checkPrivateKey(privateKey: KeyObject): boolean;
1503
-
1504
3315
  /**
1505
- * There is no standard JSON encoding for X509 certificates. The
1506
- * `toJSON()` method returns a string containing the PEM encoded
3316
+ * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded
1507
3317
  * certificate.
3318
+ * @since v15.6.0
1508
3319
  */
1509
3320
  toJSON(): string;
1510
-
1511
3321
  /**
1512
- * Returns information about this certificate using the legacy certificate object encoding.
3322
+ * Returns information about this certificate using the legacy `certificate object` encoding.
3323
+ * @since v15.6.0
1513
3324
  */
1514
3325
  toLegacyObject(): PeerCertificate;
1515
-
1516
3326
  /**
1517
3327
  * Returns the PEM-encoded certificate.
3328
+ * @since v15.6.0
1518
3329
  */
1519
3330
  toString(): string;
1520
-
1521
3331
  /**
1522
3332
  * Verifies that this certificate was signed by the given public key.
1523
3333
  * Does not perform any other validation checks on the certificate.
3334
+ * @since v15.6.0
3335
+ * @param publicKey A public key.
1524
3336
  */
1525
3337
  verify(publicKey: KeyObject): boolean;
1526
3338
  }
1527
-
1528
3339
  type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint;
1529
-
1530
3340
  interface GeneratePrimeOptions {
1531
- add?: LargeNumberLike;
1532
- rem?: LargeNumberLike;
3341
+ add?: LargeNumberLike | undefined;
3342
+ rem?: LargeNumberLike | undefined;
1533
3343
  /**
1534
3344
  * @default false
1535
3345
  */
1536
- safe?: boolean;
1537
- bigint?: boolean;
3346
+ safe?: boolean | undefined;
3347
+ bigint?: boolean | undefined;
1538
3348
  }
1539
-
1540
3349
  interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions {
1541
3350
  bigint: true;
1542
3351
  }
1543
-
1544
3352
  interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions {
1545
- bigint?: false;
3353
+ bigint?: false | undefined;
1546
3354
  }
1547
-
3355
+ /**
3356
+ * Generates a pseudorandom prime of `size` bits.
3357
+ *
3358
+ * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime.
3359
+ *
3360
+ * The `options.add` and `options.rem` parameters can be used to enforce additional
3361
+ * requirements, e.g., for Diffie-Hellman:
3362
+ *
3363
+ * * If `options.add` and `options.rem` are both set, the prime will satisfy the
3364
+ * condition that `prime % add = rem`.
3365
+ * * If only `options.add` is set and `options.safe` is not `true`, the prime will
3366
+ * satisfy the condition that `prime % add = 1`.
3367
+ * * If only `options.add` is set and `options.safe` is set to `true`, the prime
3368
+ * will instead satisfy the condition that `prime % add = 3`. This is necessary
3369
+ * because `prime % add = 1` for `options.add > 2` would contradict the condition
3370
+ * enforced by `options.safe`.
3371
+ * * `options.rem` is ignored if `options.add` is not given.
3372
+ *
3373
+ * Both `options.add` and `options.rem` must be encoded as big-endian sequences
3374
+ * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`.
3375
+ *
3376
+ * By default, the prime is encoded as a big-endian sequence of octets
3377
+ * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a
3378
+ * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided.
3379
+ * @since v15.8.0
3380
+ * @param size The size (in bits) of the prime to generate.
3381
+ */
1548
3382
  function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void;
1549
3383
  function generatePrime(size: number, options: GeneratePrimeOptionsBigInt, callback: (err: Error | null, prime: bigint) => void): void;
1550
3384
  function generatePrime(size: number, options: GeneratePrimeOptionsArrayBuffer, callback: (err: Error | null, prime: ArrayBuffer) => void): void;
1551
3385
  function generatePrime(size: number, options: GeneratePrimeOptions, callback: (err: Error | null, prime: ArrayBuffer | bigint) => void): void;
1552
-
3386
+ /**
3387
+ * Generates a pseudorandom prime of `size` bits.
3388
+ *
3389
+ * If `options.safe` is `true`, the prime will be a safe prime -- that is,`(prime - 1) / 2` will also be a prime.
3390
+ *
3391
+ * The `options.add` and `options.rem` parameters can be used to enforce additional
3392
+ * requirements, e.g., for Diffie-Hellman:
3393
+ *
3394
+ * * If `options.add` and `options.rem` are both set, the prime will satisfy the
3395
+ * condition that `prime % add = rem`.
3396
+ * * If only `options.add` is set and `options.safe` is not `true`, the prime will
3397
+ * satisfy the condition that `prime % add = 1`.
3398
+ * * If only `options.add` is set and `options.safe` is set to `true`, the prime
3399
+ * will instead satisfy the condition that `prime % add = 3`. This is necessary
3400
+ * because `prime % add = 1` for `options.add > 2` would contradict the condition
3401
+ * enforced by `options.safe`.
3402
+ * * `options.rem` is ignored if `options.add` is not given.
3403
+ *
3404
+ * Both `options.add` and `options.rem` must be encoded as big-endian sequences
3405
+ * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or`DataView`.
3406
+ *
3407
+ * By default, the prime is encoded as a big-endian sequence of octets
3408
+ * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a
3409
+ * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided.
3410
+ * @since v15.8.0
3411
+ * @param size The size (in bits) of the prime to generate.
3412
+ */
1553
3413
  function generatePrimeSync(size: number): ArrayBuffer;
1554
3414
  function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint;
1555
3415
  function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer;
1556
3416
  function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint;
1557
-
1558
3417
  interface CheckPrimeOptions {
1559
3418
  /**
1560
3419
  * The number of Miller-Rabin probabilistic primality iterations to perform.
1561
- * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most 2-64 for random input.
3420
+ * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input.
1562
3421
  * Care must be used when selecting a number of checks.
1563
3422
  * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details.
1564
3423
  *
1565
3424
  * @default 0
1566
3425
  */
1567
- checks?: number;
3426
+ checks?: number | undefined;
1568
3427
  }
1569
-
1570
3428
  /**
1571
- * Checks the primality of the candidate.
3429
+ * Checks the primality of the `candidate`.
3430
+ * @since v15.8.0
3431
+ * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length.
1572
3432
  */
1573
3433
  function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void;
1574
3434
  function checkPrime(value: LargeNumberLike, options: CheckPrimeOptions, callback: (err: Error | null, result: boolean) => void): void;
1575
-
1576
3435
  /**
1577
- * Checks the primality of the candidate.
3436
+ * Checks the primality of the `candidate`.
3437
+ * @since v15.8.0
3438
+ * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length.
3439
+ * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`.
1578
3440
  */
1579
- function checkPrimeSync(value: LargeNumberLike, options?: CheckPrimeOptions): boolean;
3441
+ function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean;
3442
+ /**
3443
+ * Load and set the `engine` for some or all OpenSSL functions (selected by flags).
3444
+ *
3445
+ * `engine` could be either an id or a path to the engine's shared library.
3446
+ *
3447
+ * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default.
3448
+ * The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`):
3449
+ *
3450
+ * - `crypto.constants.ENGINE_METHOD_RSA`
3451
+ * - `crypto.constants.ENGINE_METHOD_DSA`
3452
+ * - `crypto.constants.ENGINE_METHOD_DH`
3453
+ * - `crypto.constants.ENGINE_METHOD_RAND`
3454
+ * - `crypto.constants.ENGINE_METHOD_EC`
3455
+ * - `crypto.constants.ENGINE_METHOD_CIPHERS`
3456
+ * - `crypto.constants.ENGINE_METHOD_DIGESTS`
3457
+ * - `crypto.constants.ENGINE_METHOD_PKEY_METHS`
3458
+ * - `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS`
3459
+ * - `crypto.constants.ENGINE_METHOD_ALL`
3460
+ * - `crypto.constants.ENGINE_METHOD_NONE`
3461
+ *
3462
+ * The flags below are deprecated in OpenSSL-1.1.0.
3463
+ *
3464
+ * - `crypto.constants.ENGINE_METHOD_ECDH`
3465
+ * - `crypto.constants.ENGINE_METHOD_ECDSA`
3466
+ * - `crypto.constants.ENGINE_METHOD_STORE`
3467
+ * @since v0.11.11
3468
+ * @param [flags=crypto.constants.ENGINE_METHOD_ALL]
3469
+ */
3470
+ function setEngine(engine: string, flags?: number): void;
3471
+ /**
3472
+ * A convenient alias for `crypto.webcrypto.getRandomValues()`.
3473
+ * This implementation is not compliant with the Web Crypto spec,
3474
+ * to write web-compatible code use `crypto.webcrypto.getRandomValues()` instead.
3475
+ * @since v17.4.0
3476
+ * @returns Returns `typedArray`.
3477
+ */
3478
+ function getRandomValues<T extends webcrypto.BufferSource>(typedArray: T): T;
3479
+ /**
3480
+ * A convenient alias for `crypto.webcrypto.subtle`.
3481
+ * @since v17.4.0
3482
+ */
3483
+ const subtle: webcrypto.SubtleCrypto;
3484
+ /**
3485
+ * An implementation of the Web Crypto API standard.
3486
+ *
3487
+ * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details.
3488
+ * @since v15.0.0
3489
+ */
3490
+ const webcrypto: webcrypto.Crypto;
3491
+ namespace webcrypto {
3492
+ type BufferSource = ArrayBufferView | ArrayBuffer;
3493
+ type KeyFormat = 'jwk' | 'pkcs8' | 'raw' | 'spki';
3494
+ type KeyType = 'private' | 'public' | 'secret';
3495
+ type KeyUsage = 'decrypt' | 'deriveBits' | 'deriveKey' | 'encrypt' | 'sign' | 'unwrapKey' | 'verify' | 'wrapKey';
3496
+ type AlgorithmIdentifier = Algorithm | string;
3497
+ type HashAlgorithmIdentifier = AlgorithmIdentifier;
3498
+ type NamedCurve = string;
3499
+ type BigInteger = Uint8Array;
3500
+ interface AesCbcParams extends Algorithm {
3501
+ iv: BufferSource;
3502
+ }
3503
+ interface AesCtrParams extends Algorithm {
3504
+ counter: BufferSource;
3505
+ length: number;
3506
+ }
3507
+ interface AesDerivedKeyParams extends Algorithm {
3508
+ length: number;
3509
+ }
3510
+ interface AesGcmParams extends Algorithm {
3511
+ additionalData?: BufferSource;
3512
+ iv: BufferSource;
3513
+ tagLength?: number;
3514
+ }
3515
+ interface AesKeyAlgorithm extends KeyAlgorithm {
3516
+ length: number;
3517
+ }
3518
+ interface AesKeyGenParams extends Algorithm {
3519
+ length: number;
3520
+ }
3521
+ interface Algorithm {
3522
+ name: string;
3523
+ }
3524
+ interface EcKeyAlgorithm extends KeyAlgorithm {
3525
+ namedCurve: NamedCurve;
3526
+ }
3527
+ interface EcKeyGenParams extends Algorithm {
3528
+ namedCurve: NamedCurve;
3529
+ }
3530
+ interface EcKeyImportParams extends Algorithm {
3531
+ namedCurve: NamedCurve;
3532
+ }
3533
+ interface EcdhKeyDeriveParams extends Algorithm {
3534
+ public: CryptoKey;
3535
+ }
3536
+ interface EcdsaParams extends Algorithm {
3537
+ hash: HashAlgorithmIdentifier;
3538
+ }
3539
+ interface Ed448Params extends Algorithm {
3540
+ context?: BufferSource;
3541
+ }
3542
+ interface HkdfParams extends Algorithm {
3543
+ hash: HashAlgorithmIdentifier;
3544
+ info: BufferSource;
3545
+ salt: BufferSource;
3546
+ }
3547
+ interface HmacImportParams extends Algorithm {
3548
+ hash: HashAlgorithmIdentifier;
3549
+ length?: number;
3550
+ }
3551
+ interface HmacKeyAlgorithm extends KeyAlgorithm {
3552
+ hash: KeyAlgorithm;
3553
+ length: number;
3554
+ }
3555
+ interface HmacKeyGenParams extends Algorithm {
3556
+ hash: HashAlgorithmIdentifier;
3557
+ length?: number;
3558
+ }
3559
+ interface JsonWebKey {
3560
+ alg?: string;
3561
+ crv?: string;
3562
+ d?: string;
3563
+ dp?: string;
3564
+ dq?: string;
3565
+ e?: string;
3566
+ ext?: boolean;
3567
+ k?: string;
3568
+ key_ops?: string[];
3569
+ kty?: string;
3570
+ n?: string;
3571
+ oth?: RsaOtherPrimesInfo[];
3572
+ p?: string;
3573
+ q?: string;
3574
+ qi?: string;
3575
+ use?: string;
3576
+ x?: string;
3577
+ y?: string;
3578
+ }
3579
+ interface KeyAlgorithm {
3580
+ name: string;
3581
+ }
3582
+ interface Pbkdf2Params extends Algorithm {
3583
+ hash: HashAlgorithmIdentifier;
3584
+ iterations: number;
3585
+ salt: BufferSource;
3586
+ }
3587
+ interface RsaHashedImportParams extends Algorithm {
3588
+ hash: HashAlgorithmIdentifier;
3589
+ }
3590
+ interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm {
3591
+ hash: KeyAlgorithm;
3592
+ }
3593
+ interface RsaHashedKeyGenParams extends RsaKeyGenParams {
3594
+ hash: HashAlgorithmIdentifier;
3595
+ }
3596
+ interface RsaKeyAlgorithm extends KeyAlgorithm {
3597
+ modulusLength: number;
3598
+ publicExponent: BigInteger;
3599
+ }
3600
+ interface RsaKeyGenParams extends Algorithm {
3601
+ modulusLength: number;
3602
+ publicExponent: BigInteger;
3603
+ }
3604
+ interface RsaOaepParams extends Algorithm {
3605
+ label?: BufferSource;
3606
+ }
3607
+ interface RsaOtherPrimesInfo {
3608
+ d?: string;
3609
+ r?: string;
3610
+ t?: string;
3611
+ }
3612
+ interface RsaPssParams extends Algorithm {
3613
+ saltLength: number;
3614
+ }
3615
+ /**
3616
+ * Calling `require('node:crypto').webcrypto` returns an instance of the `Crypto` class.
3617
+ * `Crypto` is a singleton that provides access to the remainder of the crypto API.
3618
+ * @since v15.0.0
3619
+ */
3620
+ interface Crypto {
3621
+ /**
3622
+ * Provides access to the `SubtleCrypto` API.
3623
+ * @since v15.0.0
3624
+ */
3625
+ readonly subtle: SubtleCrypto;
3626
+ /**
3627
+ * Generates cryptographically strong random values.
3628
+ * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned.
3629
+ *
3630
+ * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted.
3631
+ *
3632
+ * An error will be thrown if the given `typedArray` is larger than 65,536 bytes.
3633
+ * @since v15.0.0
3634
+ */
3635
+ getRandomValues<T extends Exclude<NodeJS.TypedArray, Float32Array | Float64Array>>(typedArray: T): T;
3636
+ /**
3637
+ * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID.
3638
+ * The UUID is generated using a cryptographic pseudorandom number generator.
3639
+ * @since v16.7.0
3640
+ */
3641
+ randomUUID(): string;
3642
+ CryptoKey: CryptoKeyConstructor;
3643
+ }
3644
+ // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable.
3645
+ interface CryptoKeyConstructor {
3646
+ /** Illegal constructor */
3647
+ (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user.
3648
+ readonly length: 0;
3649
+ readonly name: 'CryptoKey';
3650
+ readonly prototype: CryptoKey;
3651
+ }
3652
+ /**
3653
+ * @since v15.0.0
3654
+ */
3655
+ interface CryptoKey {
3656
+ /**
3657
+ * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters.
3658
+ * @since v15.0.0
3659
+ */
3660
+ readonly algorithm: KeyAlgorithm;
3661
+ /**
3662
+ * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`.
3663
+ * @since v15.0.0
3664
+ */
3665
+ readonly extractable: boolean;
3666
+ /**
3667
+ * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key.
3668
+ * @since v15.0.0
3669
+ */
3670
+ readonly type: KeyType;
3671
+ /**
3672
+ * An array of strings identifying the operations for which the key may be used.
3673
+ *
3674
+ * The possible usages are:
3675
+ * - `'encrypt'` - The key may be used to encrypt data.
3676
+ * - `'decrypt'` - The key may be used to decrypt data.
3677
+ * - `'sign'` - The key may be used to generate digital signatures.
3678
+ * - `'verify'` - The key may be used to verify digital signatures.
3679
+ * - `'deriveKey'` - The key may be used to derive a new key.
3680
+ * - `'deriveBits'` - The key may be used to derive bits.
3681
+ * - `'wrapKey'` - The key may be used to wrap another key.
3682
+ * - `'unwrapKey'` - The key may be used to unwrap another key.
3683
+ *
3684
+ * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`).
3685
+ * @since v15.0.0
3686
+ */
3687
+ readonly usages: KeyUsage[];
3688
+ }
3689
+ /**
3690
+ * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair.
3691
+ * @since v15.0.0
3692
+ */
3693
+ interface CryptoKeyPair {
3694
+ /**
3695
+ * A {@link CryptoKey} whose type will be `'private'`.
3696
+ * @since v15.0.0
3697
+ */
3698
+ privateKey: CryptoKey;
3699
+ /**
3700
+ * A {@link CryptoKey} whose type will be `'public'`.
3701
+ * @since v15.0.0
3702
+ */
3703
+ publicKey: CryptoKey;
3704
+ }
3705
+ /**
3706
+ * @since v15.0.0
3707
+ */
3708
+ interface SubtleCrypto {
3709
+ /**
3710
+ * Using the method and parameters specified in `algorithm` and the keying material provided by `key`,
3711
+ * `subtle.decrypt()` attempts to decipher the provided `data`. If successful,
3712
+ * the returned promise will be resolved with an `<ArrayBuffer>` containing the plaintext result.
3713
+ *
3714
+ * The algorithms currently supported include:
3715
+ *
3716
+ * - `'RSA-OAEP'`
3717
+ * - `'AES-CTR'`
3718
+ * - `'AES-CBC'`
3719
+ * - `'AES-GCM'`
3720
+ * @since v15.0.0
3721
+ */
3722
+ decrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>;
3723
+ /**
3724
+ * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`,
3725
+ * `subtle.deriveBits()` attempts to generate `length` bits.
3726
+ * The Node.js implementation requires that when `length` is a number it must be multiple of `8`.
3727
+ * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed
3728
+ * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms.
3729
+ * If successful, the returned promise will be resolved with an `<ArrayBuffer>` containing the generated data.
3730
+ *
3731
+ * The algorithms currently supported include:
3732
+ *
3733
+ * - `'ECDH'`
3734
+ * - `'X25519'`
3735
+ * - `'X448'`
3736
+ * - `'HKDF'`
3737
+ * - `'PBKDF2'`
3738
+ * @since v15.0.0
3739
+ */
3740
+ deriveBits(algorithm: EcdhKeyDeriveParams, baseKey: CryptoKey, length: number | null): Promise<ArrayBuffer>;
3741
+ deriveBits(algorithm: AlgorithmIdentifier | HkdfParams | Pbkdf2Params, baseKey: CryptoKey, length: number): Promise<ArrayBuffer>;
3742
+ /**
3743
+ * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`,
3744
+ * `subtle.deriveKey()` attempts to generate a new <CryptoKey>` based on the method and parameters in `derivedKeyAlgorithm`.
3745
+ *
3746
+ * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material,
3747
+ * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input.
3748
+ *
3749
+ * The algorithms currently supported include:
3750
+ *
3751
+ * - `'ECDH'`
3752
+ * - `'X25519'`
3753
+ * - `'X448'`
3754
+ * - `'HKDF'`
3755
+ * - `'PBKDF2'`
3756
+ * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}.
3757
+ * @since v15.0.0
3758
+ */
3759
+ deriveKey(
3760
+ algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params,
3761
+ baseKey: CryptoKey,
3762
+ derivedKeyAlgorithm: AlgorithmIdentifier | AesDerivedKeyParams | HmacImportParams | HkdfParams | Pbkdf2Params,
3763
+ extractable: boolean,
3764
+ keyUsages: ReadonlyArray<KeyUsage>
3765
+ ): Promise<CryptoKey>;
3766
+ /**
3767
+ * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`.
3768
+ * If successful, the returned promise is resolved with an `<ArrayBuffer>` containing the computed digest.
3769
+ *
3770
+ * If `algorithm` is provided as a `<string>`, it must be one of:
3771
+ *
3772
+ * - `'SHA-1'`
3773
+ * - `'SHA-256'`
3774
+ * - `'SHA-384'`
3775
+ * - `'SHA-512'`
3776
+ *
3777
+ * If `algorithm` is provided as an `<Object>`, it must have a `name` property whose value is one of the above.
3778
+ * @since v15.0.0
3779
+ */
3780
+ digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise<ArrayBuffer>;
3781
+ /**
3782
+ * Using the method and parameters specified by `algorithm` and the keying material provided by `key`,
3783
+ * `subtle.encrypt()` attempts to encipher `data`. If successful,
3784
+ * the returned promise is resolved with an `<ArrayBuffer>` containing the encrypted result.
3785
+ *
3786
+ * The algorithms currently supported include:
3787
+ *
3788
+ * - `'RSA-OAEP'`
3789
+ * - `'AES-CTR'`
3790
+ * - `'AES-CBC'`
3791
+ * - `'AES-GCM'`
3792
+ * @since v15.0.0
3793
+ */
3794
+ encrypt(algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>;
3795
+ /**
3796
+ * Exports the given key into the specified format, if supported.
3797
+ *
3798
+ * If the `<CryptoKey>` is not extractable, the returned promise will reject.
3799
+ *
3800
+ * When `format` is either `'pkcs8'` or `'spki'` and the export is successful,
3801
+ * the returned promise will be resolved with an `<ArrayBuffer>` containing the exported key data.
3802
+ *
3803
+ * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a
3804
+ * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification.
3805
+ * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
3806
+ * @returns `<Promise>` containing `<ArrayBuffer>`.
3807
+ * @since v15.0.0
3808
+ */
3809
+ exportKey(format: 'jwk', key: CryptoKey): Promise<JsonWebKey>;
3810
+ exportKey(format: Exclude<KeyFormat, 'jwk'>, key: CryptoKey): Promise<ArrayBuffer>;
3811
+ /**
3812
+ * Using the method and parameters provided in `algorithm`,
3813
+ * `subtle.generateKey()` attempts to generate new keying material.
3814
+ * Depending the method used, the method may generate either a single `<CryptoKey>` or a `<CryptoKeyPair>`.
3815
+ *
3816
+ * The `<CryptoKeyPair>` (public and private key) generating algorithms supported include:
3817
+ *
3818
+ * - `'RSASSA-PKCS1-v1_5'`
3819
+ * - `'RSA-PSS'`
3820
+ * - `'RSA-OAEP'`
3821
+ * - `'ECDSA'`
3822
+ * - `'Ed25519'`
3823
+ * - `'Ed448'`
3824
+ * - `'ECDH'`
3825
+ * - `'X25519'`
3826
+ * - `'X448'`
3827
+ * The `<CryptoKey>` (secret key) generating algorithms supported include:
3828
+ *
3829
+ * - `'HMAC'`
3830
+ * - `'AES-CTR'`
3831
+ * - `'AES-CBC'`
3832
+ * - `'AES-GCM'`
3833
+ * - `'AES-KW'`
3834
+ * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}.
3835
+ * @since v15.0.0
3836
+ */
3837
+ generateKey(algorithm: RsaHashedKeyGenParams | EcKeyGenParams, extractable: boolean, keyUsages: ReadonlyArray<KeyUsage>): Promise<CryptoKeyPair>;
3838
+ generateKey(algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, extractable: boolean, keyUsages: ReadonlyArray<KeyUsage>): Promise<CryptoKey>;
3839
+ generateKey(algorithm: AlgorithmIdentifier, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKeyPair | CryptoKey>;
3840
+ /**
3841
+ * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format`
3842
+ * to create a `<CryptoKey>` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments.
3843
+ * If the import is successful, the returned promise will be resolved with the created `<CryptoKey>`.
3844
+ *
3845
+ * If importing a `'PBKDF2'` key, `extractable` must be `false`.
3846
+ * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
3847
+ * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}.
3848
+ * @since v15.0.0
3849
+ */
3850
+ importKey(
3851
+ format: 'jwk',
3852
+ keyData: JsonWebKey,
3853
+ algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm,
3854
+ extractable: boolean,
3855
+ keyUsages: ReadonlyArray<KeyUsage>
3856
+ ): Promise<CryptoKey>;
3857
+ importKey(
3858
+ format: Exclude<KeyFormat, 'jwk'>,
3859
+ keyData: BufferSource,
3860
+ algorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm,
3861
+ extractable: boolean,
3862
+ keyUsages: KeyUsage[]
3863
+ ): Promise<CryptoKey>;
3864
+ /**
3865
+ * Using the method and parameters given by `algorithm` and the keying material provided by `key`,
3866
+ * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful,
3867
+ * the returned promise is resolved with an `<ArrayBuffer>` containing the generated signature.
3868
+ *
3869
+ * The algorithms currently supported include:
3870
+ *
3871
+ * - `'RSASSA-PKCS1-v1_5'`
3872
+ * - `'RSA-PSS'`
3873
+ * - `'ECDSA'`
3874
+ * - `'Ed25519'`
3875
+ * - `'Ed448'`
3876
+ * - `'HMAC'`
3877
+ * @since v15.0.0
3878
+ */
3879
+ sign(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, key: CryptoKey, data: BufferSource): Promise<ArrayBuffer>;
3880
+ /**
3881
+ * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material.
3882
+ * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `<CryptoKey>` instance.
3883
+ * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input)
3884
+ * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs.
3885
+ * If successful, the returned promise is resolved with a `<CryptoKey>` object.
3886
+ *
3887
+ * The wrapping algorithms currently supported include:
3888
+ *
3889
+ * - `'RSA-OAEP'`
3890
+ * - `'AES-CTR'`
3891
+ * - `'AES-CBC'`
3892
+ * - `'AES-GCM'`
3893
+ * - `'AES-KW'`
3894
+ *
3895
+ * The unwrapped key algorithms supported include:
3896
+ *
3897
+ * - `'RSASSA-PKCS1-v1_5'`
3898
+ * - `'RSA-PSS'`
3899
+ * - `'RSA-OAEP'`
3900
+ * - `'ECDSA'`
3901
+ * - `'Ed25519'`
3902
+ * - `'Ed448'`
3903
+ * - `'ECDH'`
3904
+ * - `'X25519'`
3905
+ * - `'X448'`
3906
+ * - `'HMAC'`
3907
+ * - `'AES-CTR'`
3908
+ * - `'AES-CBC'`
3909
+ * - `'AES-GCM'`
3910
+ * - `'AES-KW'`
3911
+ * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
3912
+ * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}.
3913
+ * @since v15.0.0
3914
+ */
3915
+ unwrapKey(
3916
+ format: KeyFormat,
3917
+ wrappedKey: BufferSource,
3918
+ unwrappingKey: CryptoKey,
3919
+ unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams,
3920
+ unwrappedKeyAlgorithm: AlgorithmIdentifier | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | AesKeyAlgorithm,
3921
+ extractable: boolean,
3922
+ keyUsages: KeyUsage[]
3923
+ ): Promise<CryptoKey>;
3924
+ /**
3925
+ * Using the method and parameters given in `algorithm` and the keying material provided by `key`,
3926
+ * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`.
3927
+ * The returned promise is resolved with either `true` or `false`.
3928
+ *
3929
+ * The algorithms currently supported include:
3930
+ *
3931
+ * - `'RSASSA-PKCS1-v1_5'`
3932
+ * - `'RSA-PSS'`
3933
+ * - `'ECDSA'`
3934
+ * - `'Ed25519'`
3935
+ * - `'Ed448'`
3936
+ * - `'HMAC'`
3937
+ * @since v15.0.0
3938
+ */
3939
+ verify(algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, key: CryptoKey, signature: BufferSource, data: BufferSource): Promise<boolean>;
3940
+ /**
3941
+ * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material.
3942
+ * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`,
3943
+ * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`.
3944
+ * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments,
3945
+ * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs.
3946
+ * If successful, the returned promise will be resolved with an `<ArrayBuffer>` containing the encrypted key data.
3947
+ *
3948
+ * The wrapping algorithms currently supported include:
3949
+ *
3950
+ * - `'RSA-OAEP'`
3951
+ * - `'AES-CTR'`
3952
+ * - `'AES-CBC'`
3953
+ * - `'AES-GCM'`
3954
+ * - `'AES-KW'`
3955
+ * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`.
3956
+ * @since v15.0.0
3957
+ */
3958
+ wrapKey(format: KeyFormat, key: CryptoKey, wrappingKey: CryptoKey, wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams): Promise<ArrayBuffer>;
3959
+ }
3960
+ }
3961
+ }
3962
+ declare module 'node:crypto' {
3963
+ export * from 'crypto';
1580
3964
  }