@types/node 18.19.22 → 18.19.23

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