UNPKG

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