@anthropic-ai/claude-code 0.2.9 → 0.2.18

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