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