forked from oven-sh/bun-types
-
Notifications
You must be signed in to change notification settings - Fork 0
/
crypto.d.ts
3790 lines (3790 loc) · 137 KB
/
crypto.d.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* The `crypto` module provides cryptographic functionality that includes a set of
* wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.
*
* ```js
* const { createHmac } = await import('crypto');
*
* const secret = 'abcdefg';
* const hash = createHmac('sha256', secret)
* .update('I love cupcakes')
* .digest('hex');
* console.log(hash);
* // Prints:
* // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
* ```
* @see [source](https://github.com/nodejs/node/blob/v18.0.0/lib/crypto.js)
*/
declare module "crypto" {
import * as stream from "node:stream";
/**
* SPKAC is a Certificate Signing Request mechanism originally implemented by
* Netscape and was specified formally as part of [HTML5's `keygen` element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/keygen).
*
* `<keygen>` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects
* should not use this element anymore.
*
* The `crypto` module provides the `Certificate` class for working with SPKAC
* data. The most common usage is handling output generated by the HTML5`<keygen>` element. Node.js uses [OpenSSL's SPKAC
* implementation](https://www.openssl.org/docs/man1.1.0/apps/openssl-spkac.html) internally.
*/
class Certificate {
/**
* ```js
* const { Certificate } = await import('crypto');
* const spkac = getSpkacSomehow();
* const challenge = Certificate.exportChallenge(spkac);
* console.log(challenge.toString('utf8'));
* // Prints: the challenge as a UTF8 string
* ```
* @param encoding The `encoding` of the `spkac` string.
* @return The challenge component of the `spkac` data structure, which includes a public key and a challenge.
*/
static exportChallenge(spkac: BinaryLike): Buffer;
/**
* ```js
* const { Certificate } = await import('crypto');
* const spkac = getSpkacSomehow();
* const publicKey = Certificate.exportPublicKey(spkac);
* console.log(publicKey);
* // Prints: the public key as <Buffer ...>
* ```
* @param encoding The `encoding` of the `spkac` string.
* @return The public key component of the `spkac` data structure, which includes a public key and a challenge.
*/
static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer;
/**
* ```js
* import { Buffer } from 'buffer';
* const { Certificate } = await import('crypto');
*
* const spkac = getSpkacSomehow();
* console.log(Certificate.verifySpkac(Buffer.from(spkac)));
* // Prints: true or false
* ```
* @param encoding The `encoding` of the `spkac` string.
* @return `true` if the given `spkac` data structure is valid, `false` otherwise.
*/
static verifySpkac(spkac: ArrayBufferView): boolean;
/**
* @deprecated
* @param spkac
* @returns The challenge component of the `spkac` data structure,
* which includes a public key and a challenge.
*/
exportChallenge(spkac: BinaryLike): Buffer;
/**
* @deprecated
* @param spkac
* @param encoding The encoding of the spkac string.
* @returns The public key component of the `spkac` data structure,
* which includes a public key and a challenge.
*/
exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer;
/**
* @deprecated
* @param spkac
* @returns `true` if the given `spkac` data structure is valid,
* `false` otherwise.
*/
verifySpkac(spkac: ArrayBufferView): boolean;
}
namespace constants {
// https://nodejs.org/dist/latest-v10.x/docs/api/crypto.html#crypto_crypto_constants
const OPENSSL_VERSION_NUMBER: number;
/** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */
const SSL_OP_ALL: number;
/** 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. */
const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number;
/** 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. */
const SSL_OP_CIPHER_SERVER_PREFERENCE: number;
/** Instructs OpenSSL to use Cisco's "speshul" version of DTLS_BAD_VER. */
const SSL_OP_CISCO_ANYCONNECT: number;
/** Instructs OpenSSL to turn on cookie exchange. */
const SSL_OP_COOKIE_EXCHANGE: number;
/** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */
const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number;
/** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */
const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number;
/** Instructs OpenSSL to always use the tmp_rsa key when performing RSA operations. */
const SSL_OP_EPHEMERAL_RSA: number;
/** Allows initial connection to servers that do not support RI. */
const SSL_OP_LEGACY_SERVER_CONNECT: number;
const SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER: number;
const SSL_OP_MICROSOFT_SESS_ID_BUG: number;
/** Instructs OpenSSL to disable the workaround for a man-in-the-middle protocol-version vulnerability in the SSL 2.0 server implementation. */
const SSL_OP_MSIE_SSLV2_RSA_PADDING: number;
const SSL_OP_NETSCAPE_CA_DN_BUG: number;
const SSL_OP_NETSCAPE_CHALLENGE_BUG: number;
const SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG: number;
const SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG: number;
/** Instructs OpenSSL to disable support for SSL/TLS compression. */
const SSL_OP_NO_COMPRESSION: number;
const SSL_OP_NO_QUERY_MTU: number;
/** Instructs OpenSSL to always start a new session when performing renegotiation. */
const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number;
const SSL_OP_NO_SSLv2: number;
const SSL_OP_NO_SSLv3: number;
const SSL_OP_NO_TICKET: number;
const SSL_OP_NO_TLSv1: number;
const SSL_OP_NO_TLSv1_1: number;
const SSL_OP_NO_TLSv1_2: number;
const SSL_OP_PKCS1_CHECK_1: number;
const SSL_OP_PKCS1_CHECK_2: number;
/** Instructs OpenSSL to always create a new key when using temporary/ephemeral DH parameters. */
const SSL_OP_SINGLE_DH_USE: number;
/** Instructs OpenSSL to always create a new key when using temporary/ephemeral ECDH parameters. */
const SSL_OP_SINGLE_ECDH_USE: number;
const SSL_OP_SSLEAY_080_CLIENT_DH_BUG: number;
const SSL_OP_SSLREF2_REUSE_CERT_TYPE_BUG: number;
const SSL_OP_TLS_BLOCK_PADDING_BUG: number;
const SSL_OP_TLS_D5_BUG: number;
/** Instructs OpenSSL to disable version rollback attack detection. */
const SSL_OP_TLS_ROLLBACK_BUG: number;
const ENGINE_METHOD_RSA: number;
const ENGINE_METHOD_DSA: number;
const ENGINE_METHOD_DH: number;
const ENGINE_METHOD_RAND: number;
const ENGINE_METHOD_EC: number;
const ENGINE_METHOD_CIPHERS: number;
const ENGINE_METHOD_DIGESTS: number;
const ENGINE_METHOD_PKEY_METHS: number;
const ENGINE_METHOD_PKEY_ASN1_METHS: number;
const ENGINE_METHOD_ALL: number;
const ENGINE_METHOD_NONE: number;
const DH_CHECK_P_NOT_SAFE_PRIME: number;
const DH_CHECK_P_NOT_PRIME: number;
const DH_UNABLE_TO_CHECK_GENERATOR: number;
const DH_NOT_SUITABLE_GENERATOR: number;
const ALPN_ENABLED: number;
const RSA_PKCS1_PADDING: number;
const RSA_SSLV23_PADDING: number;
const RSA_NO_PADDING: number;
const RSA_PKCS1_OAEP_PADDING: number;
const RSA_X931_PADDING: number;
const RSA_PKCS1_PSS_PADDING: number;
/** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */
const RSA_PSS_SALTLEN_DIGEST: number;
/** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */
const RSA_PSS_SALTLEN_MAX_SIGN: number;
/** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */
const RSA_PSS_SALTLEN_AUTO: number;
const POINT_CONVERSION_COMPRESSED: number;
const POINT_CONVERSION_UNCOMPRESSED: number;
const POINT_CONVERSION_HYBRID: number;
/** Specifies the built-in default cipher list used by Node.js (colon-separated values). */
const defaultCoreCipherList: string;
/** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */
const defaultCipherList: string;
}
interface HashOptions extends stream.TransformOptions {
/**
* For XOF hash functions such as `shake256`, the
* outputLength option can be used to specify the desired output length in bytes.
*/
outputLength?: number | undefined;
}
/** @deprecated since v10.0.0 */
const fips: boolean;
/**
* Creates and returns a `Hash` object that can be used to generate hash digests
* using the given `algorithm`. Optional `options` argument controls stream
* behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option
* can be used to specify the desired output length in bytes.
*
* The `algorithm` is dependent on the available algorithms supported by the
* version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
* On recent releases of OpenSSL, `openssl list -digest-algorithms` will
* display the available digest algorithms.
*
* Example: generating the sha256 sum of a file
*
* ```js
* import {
* createReadStream
* } from 'fs';
* import { argv } from 'process';
* const {
* createHash
* } = await import('crypto');
*
* const filename = argv[2];
*
* const hash = createHash('sha256');
*
* const input = createReadStream(filename);
* input.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = input.read();
* if (data)
* hash.update(data);
* else {
* console.log(`${hash.digest('hex')} ${filename}`);
* }
* });
* ```
* @param options `stream.transform` options
*/
function createHash(algorithm: string, options?: HashOptions): Hash;
/**
* Creates and returns an `Hmac` object that uses the given `algorithm` and `key`.
* Optional `options` argument controls stream behavior.
*
* The `algorithm` is dependent on the available algorithms supported by the
* version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
* On recent releases of OpenSSL, `openssl list -digest-algorithms` will
* display the available digest algorithms.
*
* The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is
* a `KeyObject`, its type must be `secret`.
*
* Example: generating the sha256 HMAC of a file
*
* ```js
* import {
* createReadStream
* } from 'fs';
* import { argv } from 'process';
* const {
* createHmac
* } = await import('crypto');
*
* const filename = argv[2];
*
* const hmac = createHmac('sha256', 'a secret');
*
* const input = createReadStream(filename);
* input.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = input.read();
* if (data)
* hmac.update(data);
* else {
* console.log(`${hmac.digest('hex')} ${filename}`);
* }
* });
* ```
* @param options `stream.transform` options
*/
function createHmac(
algorithm: string,
key: BinaryLike | KeyObject,
options?: stream.TransformOptions
): Hmac;
// https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings
type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary";
type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "latin1";
type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2";
type Encoding =
| BinaryToTextEncoding
| CharacterEncoding
| LegacyCharacterEncoding;
type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid";
/**
* The `Hash` class is a utility for creating hash digests of data. It can be
* used in one of two ways:
*
* * As a `stream` that is both readable and writable, where data is written
* to produce a computed hash digest on the readable side, or
* * Using the `hash.update()` and `hash.digest()` methods to produce the
* computed hash.
*
* The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword.
*
* Example: Using `Hash` objects as streams:
*
* ```js
* const {
* createHash
* } = await import('crypto');
*
* const hash = createHash('sha256');
*
* hash.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = hash.read();
* if (data) {
* console.log(data.toString('hex'));
* // Prints:
* // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
* }
* });
*
* hash.write('some data to hash');
* hash.end();
* ```
*
* Example: Using `Hash` and piped streams:
*
* ```js
* import { createReadStream } from 'fs';
* import { stdout } from 'process';
* const { createHash } = await import('crypto');
*
* const hash = createHash('sha256');
*
* const input = createReadStream('test.js');
* input.pipe(hash).setEncoding('hex').pipe(stdout);
* ```
*
* Example: Using the `hash.update()` and `hash.digest()` methods:
*
* ```js
* const {
* createHash
* } = await import('crypto');
*
* const hash = createHash('sha256');
*
* hash.update('some data to hash');
* console.log(hash.digest('hex'));
* // Prints:
* // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
* ```
*/
class Hash extends stream.Transform {
private constructor();
/**
* Creates a new `Hash` object that contains a deep copy of the internal state
* of the current `Hash` object.
*
* The optional `options` argument controls stream behavior. For XOF hash
* functions such as `'shake256'`, the `outputLength` option can be used to
* specify the desired output length in bytes.
*
* An error is thrown when an attempt is made to copy the `Hash` object after
* its `hash.digest()` method has been called.
*
* ```js
* // Calculate a rolling hash.
* const {
* createHash
* } = await import('crypto');
*
* const hash = createHash('sha256');
*
* hash.update('one');
* console.log(hash.copy().digest('hex'));
*
* hash.update('two');
* console.log(hash.copy().digest('hex'));
*
* hash.update('three');
* console.log(hash.copy().digest('hex'));
*
* // Etc.
* ```
* @param options `stream.transform` options
*/
copy(options?: stream.TransformOptions): Hash;
/**
* Updates the hash content with the given `data`, the encoding of which
* is given in `inputEncoding`.
* If `encoding` is not provided, and the `data` is a string, an
* encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
*
* This can be called many times with new data as it is streamed.
* @param inputEncoding The `encoding` of the `data` string.
*/
update(data: BinaryLike): Hash;
update(data: string, inputEncoding: Encoding): Hash;
/**
* Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method).
* If `encoding` is provided a string will be returned; otherwise
* a `Buffer` is returned.
*
* The `Hash` object can not be used again after `hash.digest()` method has been
* called. Multiple calls will cause an error to be thrown.
* @param encoding The `encoding` of the return value.
*/
digest(): Buffer;
digest(encoding: BinaryToTextEncoding): string;
}
/**
* The `Hmac` class is a utility for creating cryptographic HMAC digests. It can
* be used in one of two ways:
*
* * As a `stream` that is both readable and writable, where data is written
* to produce a computed HMAC digest on the readable side, or
* * Using the `hmac.update()` and `hmac.digest()` methods to produce the
* computed HMAC digest.
*
* The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword.
*
* Example: Using `Hmac` objects as streams:
*
* ```js
* const {
* createHmac
* } = await import('crypto');
*
* const hmac = createHmac('sha256', 'a secret');
*
* hmac.on('readable', () => {
* // Only one element is going to be produced by the
* // hash stream.
* const data = hmac.read();
* if (data) {
* console.log(data.toString('hex'));
* // Prints:
* // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
* }
* });
*
* hmac.write('some data to hash');
* hmac.end();
* ```
*
* Example: Using `Hmac` and piped streams:
*
* ```js
* import { createReadStream } from 'fs';
* import { stdout } from 'process';
* const {
* createHmac
* } = await import('crypto');
*
* const hmac = createHmac('sha256', 'a secret');
*
* const input = createReadStream('test.js');
* input.pipe(hmac).pipe(stdout);
* ```
*
* Example: Using the `hmac.update()` and `hmac.digest()` methods:
*
* ```js
* const {
* createHmac
* } = await import('crypto');
*
* const hmac = createHmac('sha256', 'a secret');
*
* hmac.update('some data to hash');
* console.log(hmac.digest('hex'));
* // Prints:
* // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
* ```
*/
class Hmac extends stream.Transform {
private constructor();
/**
* Updates the `Hmac` content with the given `data`, the encoding of which
* is given in `inputEncoding`.
* If `encoding` is not provided, and the `data` is a string, an
* encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored.
*
* This can be called many times with new data as it is streamed.
* @param inputEncoding The `encoding` of the `data` string.
*/
update(data: BinaryLike): Hmac;
update(data: string, inputEncoding: Encoding): Hmac;
/**
* Calculates the HMAC digest of all of the data passed using `hmac.update()`.
* If `encoding` is
* provided a string is returned; otherwise a `Buffer` is returned;
*
* The `Hmac` object can not be used again after `hmac.digest()` has been
* called. Multiple calls to `hmac.digest()` will result in an error being thrown.
* @param encoding The `encoding` of the return value.
*/
digest(): Buffer;
digest(encoding: BinaryToTextEncoding): string;
}
type KeyObjectType = "secret" | "public" | "private";
interface KeyExportOptions<T extends KeyFormat> {
type: "pkcs1" | "spki" | "pkcs8" | "sec1";
format: T;
cipher?: string | undefined;
passphrase?: string | Buffer | undefined;
}
interface JwkKeyExportOptions {
format: "jwk";
}
interface JsonWebKey {
crv?: string | undefined;
d?: string | undefined;
dp?: string | undefined;
dq?: string | undefined;
e?: string | undefined;
k?: string | undefined;
kty?: string | undefined;
n?: string | undefined;
p?: string | undefined;
q?: string | undefined;
qi?: string | undefined;
x?: string | undefined;
y?: string | undefined;
[key: string]: unknown;
}
interface AsymmetricKeyDetails {
/**
* Key size in bits (RSA, DSA).
*/
modulusLength?: number | undefined;
/**
* Public exponent (RSA).
*/
publicExponent?: bigint | undefined;
/**
* Name of the message digest (RSA-PSS).
*/
hashAlgorithm?: string | undefined;
/**
* Name of the message digest used by MGF1 (RSA-PSS).
*/
mgf1HashAlgorithm?: string | undefined;
/**
* Minimal salt length in bytes (RSA-PSS).
*/
saltLength?: number | undefined;
/**
* Size of q in bits (DSA).
*/
divisorLength?: number | undefined;
/**
* Name of the curve (EC).
*/
namedCurve?: string | undefined;
}
interface JwkKeyExportOptions {
format: "jwk";
}
/**
* Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key,
* and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject`
* objects are not to be created directly using the `new`keyword.
*
* Most applications should consider using the new `KeyObject` API instead of
* passing keys as strings or `Buffer`s due to improved security features.
*
* `KeyObject` instances can be passed to other threads via `postMessage()`.
* The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to
* be listed in the `transferList` argument.
*/
class KeyObject {
private constructor();
/**
* Example: Converting a `CryptoKey` instance to a `KeyObject`:
*
* ```js
* const { webcrypto, KeyObject } = await import('crypto');
* const { subtle } = webcrypto;
*
* const key = await subtle.generateKey({
* name: 'HMAC',
* hash: 'SHA-256',
* length: 256
* }, true, ['sign', 'verify']);
*
* const keyObject = KeyObject.from(key);
* console.log(keyObject.symmetricKeySize);
* // Prints: 32 (symmetric key size in bytes)
* ```
*/
// static from(key: webcrypto.CryptoKey): KeyObject;
/**
* For asymmetric keys, this property represents the type of the key. Supported key
* types are:
*
* * `'rsa'` (OID 1.2.840.113549.1.1.1)
* * `'rsa-pss'` (OID 1.2.840.113549.1.1.10)
* * `'dsa'` (OID 1.2.840.10040.4.1)
* * `'ec'` (OID 1.2.840.10045.2.1)
* * `'x25519'` (OID 1.3.101.110)
* * `'x448'` (OID 1.3.101.111)
* * `'ed25519'` (OID 1.3.101.112)
* * `'ed448'` (OID 1.3.101.113)
* * `'dh'` (OID 1.2.840.113549.1.3.1)
*
* This property is `undefined` for unrecognized `KeyObject` types and symmetric
* keys.
*/
asymmetricKeyType?: KeyType | undefined;
/**
* For asymmetric keys, this property represents the size of the embedded key in
* bytes. This property is `undefined` for symmetric keys.
*/
asymmetricKeySize?: number | undefined;
/**
* This property exists only on asymmetric keys. Depending on the type of the key,
* this object contains information about the key. None of the information obtained
* through this property can be used to uniquely identify a key or to compromise
* the security of the key.
*
* For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence,
* the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be
* set.
*
* Other key details might be exposed via this API using additional attributes.
*/
asymmetricKeyDetails?: AsymmetricKeyDetails | undefined;
/**
* For symmetric keys, the following encoding options can be used:
*
* For public keys, the following encoding options can be used:
*
* For private keys, the following encoding options can be used:
*
* The result type depends on the selected encoding format, when PEM the
* result is a string, when DER it will be a buffer containing the data
* encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object.
*
* When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are
* ignored.
*
* PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of
* 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
* encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for
* encrypted private keys. Since PKCS#8 defines its own
* encryption mechanism, PEM-level encryption is not supported when encrypting
* 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
* PKCS#1 and SEC1 encryption.
*/
export(options: KeyExportOptions<"pem">): string | Buffer;
export(options?: KeyExportOptions<"der">): Buffer;
export(options?: JwkKeyExportOptions): JsonWebKey;
/**
* For secret keys, this property represents the size of the key in bytes. This
* property is `undefined` for asymmetric keys.
*/
symmetricKeySize?: number | undefined;
/**
* Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys
* or `'private'` for private (asymmetric) keys.
*/
type: KeyObjectType;
}
type CipherCCMTypes =
| "aes-128-ccm"
| "aes-192-ccm"
| "aes-256-ccm"
| "chacha20-poly1305";
type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm";
type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb";
type BinaryLike = string | ArrayBufferView;
type CipherKey = BinaryLike | KeyObject;
interface CipherCCMOptions extends stream.TransformOptions {
authTagLength: number;
}
interface CipherGCMOptions extends stream.TransformOptions {
authTagLength?: number | undefined;
}
interface CipherOCBOptions extends stream.TransformOptions {
authTagLength: number;
}
/**
* Creates and returns a `Cipher` object that uses the given `algorithm` and`password`.
*
* The `options` argument controls stream behavior and is optional except when a
* cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the
* 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
* tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
* For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
*
* The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
* recent OpenSSL releases, `openssl list -cipher-algorithms` will
* display the available cipher algorithms.
*
* The `password` is used to derive the cipher key and initialization vector (IV).
* The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`.
*
* The implementation of `crypto.createCipher()` derives keys using the OpenSSL
* function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one
* iteration, and no salt. The lack of salt allows dictionary attacks as the same
* password always creates the same key. The low iteration count and
* non-cryptographically secure hash algorithm allow passwords to be tested very
* rapidly.
*
* 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
* developers derive a key and IV on
* their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode
* (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when
* they are used in order to avoid the risk of IV reuse that causes
* vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details.
* @deprecated Since v10.0.0 - Use {@link createCipheriv} instead.
* @param options `stream.transform` options
*/
function createCipher(
algorithm: CipherCCMTypes,
password: BinaryLike,
options: CipherCCMOptions
): CipherCCM;
/** @deprecated since v10.0.0 use `createCipheriv()` */
function createCipher(
algorithm: CipherGCMTypes,
password: BinaryLike,
options?: CipherGCMOptions
): CipherGCM;
/** @deprecated since v10.0.0 use `createCipheriv()` */
function createCipher(
algorithm: string,
password: BinaryLike,
options?: stream.TransformOptions
): Cipher;
/**
* Creates and returns a `Cipher` object, with the given `algorithm`, `key` and
* initialization vector (`iv`).
*
* The `options` argument controls stream behavior and is optional except when a
* cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the
* 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
* tag that will be returned by `getAuthTag()` and defaults to 16 bytes.
* For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
*
* The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
* recent OpenSSL releases, `openssl list -cipher-algorithms` will
* display the available cipher algorithms.
*
* 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
* strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be
* a `KeyObject` of type `secret`. If the cipher does not need
* an initialization vector, `iv` may be `null`.
*
* When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`.
*
* Initialization vectors should be unpredictable and unique; ideally, they will be
* cryptographically random. They do not have to be secret: IVs are typically just
* added to ciphertext messages unencrypted. It may sound contradictory that
* something has to be unpredictable and unique, but does not have to be secret;
* remember that an attacker must not be able to predict ahead of time what a
* given IV will be.
* @param options `stream.transform` options
*/
function createCipheriv(
algorithm: CipherCCMTypes,
key: CipherKey,
iv: BinaryLike,
options: CipherCCMOptions
): CipherCCM;
function createCipheriv(
algorithm: CipherOCBTypes,
key: CipherKey,
iv: BinaryLike,
options: CipherOCBOptions
): CipherOCB;
function createCipheriv(
algorithm: CipherGCMTypes,
key: CipherKey,
iv: BinaryLike,
options?: CipherGCMOptions
): CipherGCM;
function createCipheriv(
algorithm: string,
key: CipherKey,
iv: BinaryLike | null,
options?: stream.TransformOptions
): Cipher;
/**
* Instances of the `Cipher` class are used to encrypt data. The class can be
* used in one of two ways:
*
* * As a `stream` that is both readable and writable, where plain unencrypted
* data is written to produce encrypted data on the readable side, or
* * Using the `cipher.update()` and `cipher.final()` methods to produce
* the encrypted data.
*
* The {@link createCipher} or {@link createCipheriv} methods are
* used to create `Cipher` instances. `Cipher` objects are not to be created
* directly using the `new` keyword.
*
* Example: Using `Cipher` objects as streams:
*
* ```js
* const {
* scrypt,
* randomFill,
* createCipheriv
* } = await import('crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
*
* // First, we'll generate the key. The key length is dependent on the algorithm.
* // In this case for aes192, it is 24 bytes (192 bits).
* scrypt(password, 'salt', 24, (err, key) => {
* if (err) throw err;
* // Then, we'll generate a random initialization vector
* randomFill(new Uint8Array(16), (err, iv) => {
* if (err) throw err;
*
* // Once we have the key and iv, we can create and use the cipher...
* const cipher = createCipheriv(algorithm, key, iv);
*
* let encrypted = '';
* cipher.setEncoding('hex');
*
* cipher.on('data', (chunk) => encrypted += chunk);
* cipher.on('end', () => console.log(encrypted));
*
* cipher.write('some clear text data');
* cipher.end();
* });
* });
* ```
*
* Example: Using `Cipher` and piped streams:
*
* ```js
* import {
* createReadStream,
* createWriteStream,
* } from 'fs';
*
* import {
* pipeline
* } from 'stream';
*
* const {
* scrypt,
* randomFill,
* createCipheriv
* } = await import('crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
*
* // First, we'll generate the key. The key length is dependent on the algorithm.
* // In this case for aes192, it is 24 bytes (192 bits).
* scrypt(password, 'salt', 24, (err, key) => {
* if (err) throw err;
* // Then, we'll generate a random initialization vector
* randomFill(new Uint8Array(16), (err, iv) => {
* if (err) throw err;
*
* const cipher = createCipheriv(algorithm, key, iv);
*
* const input = createReadStream('test.js');
* const output = createWriteStream('test.enc');
*
* pipeline(input, cipher, output, (err) => {
* if (err) throw err;
* });
* });
* });
* ```
*
* Example: Using the `cipher.update()` and `cipher.final()` methods:
*
* ```js
* const {
* scrypt,
* randomFill,
* createCipheriv
* } = await import('crypto');
*
* const algorithm = 'aes-192-cbc';
* const password = 'Password used to generate key';
*
* // First, we'll generate the key. The key length is dependent on the algorithm.
* // In this case for aes192, it is 24 bytes (192 bits).
* scrypt(password, 'salt', 24, (err, key) => {
* if (err) throw err;
* // Then, we'll generate a random initialization vector
* randomFill(new Uint8Array(16), (err, iv) => {
* if (err) throw err;
*
* const cipher = createCipheriv(algorithm, key, iv);
*
* let encrypted = cipher.update('some clear text data', 'utf8', 'hex');
* encrypted += cipher.final('hex');
* console.log(encrypted);
* });
* });
* ```
*/
class Cipher extends stream.Transform {
private constructor();
/**
* Updates the cipher with `data`. If the `inputEncoding` argument is given,
* 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`,
* `TypedArray`, or `DataView`, then`inputEncoding` is ignored.
*
* The `outputEncoding` specifies the output format of the enciphered
* data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned.
*
* 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
* thrown.
* @param inputEncoding The `encoding` of the data.
* @param outputEncoding The `encoding` of the return value.
*/
update(data: BinaryLike): Buffer;
update(data: string, inputEncoding: Encoding): Buffer;
update(
data: ArrayBufferView,
inputEncoding: undefined,
outputEncoding: Encoding
): string;
update(
data: string,
inputEncoding: Encoding | undefined,
outputEncoding: Encoding
): string;
/**
* Once the `cipher.final()` method has been called, the `Cipher` object can no
* longer be used to encrypt data. Attempts to call `cipher.final()` more than
* once will result in an error being thrown.
* @param outputEncoding The `encoding` of the return value.
* @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned.
*/
final(): Buffer;
final(outputEncoding: BufferEncoding): string;
/**
* When using block encryption algorithms, the `Cipher` class will automatically
* add padding to the input data to the appropriate block size. To disable the
* default padding call `cipher.setAutoPadding(false)`.
*
* When `autoPadding` is `false`, the length of the entire input data must be a
* multiple of the cipher's block size or `cipher.final()` will throw an error.
* Disabling automatic padding is useful for non-standard padding, for instance
* using `0x0` instead of PKCS padding.
*
* The `cipher.setAutoPadding()` method must be called before `cipher.final()`.
* @param [autoPadding=true]
* @return for method chaining.
*/
setAutoPadding(autoPadding?: boolean): this;
}
interface CipherCCM extends Cipher {
setAAD(
buffer: ArrayBufferView,
options: {
plaintextLength: number;
}
): this;
getAuthTag(): Buffer;
}
interface CipherGCM extends Cipher {
setAAD(
buffer: ArrayBufferView,
options?: {
plaintextLength: number;
}
): this;
getAuthTag(): Buffer;
}
interface CipherOCB extends Cipher {
setAAD(
buffer: ArrayBufferView,
options?: {
plaintextLength: number;
}
): this;
getAuthTag(): Buffer;
}
/**
* Creates and returns a `Decipher` object that uses the given `algorithm` and`password` (key).
*
* The `options` argument controls stream behavior and is optional except when a
* cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the
* authentication tag in bytes, see `CCM mode`.
* For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes.
*
* The implementation of `crypto.createDecipher()` derives keys using the OpenSSL
* function [`EVP_BytesToKey`](https://www.openssl.org/docs/man1.1.0/crypto/EVP_BytesToKey.html) with the digest algorithm set to MD5, one
* iteration, and no salt. The lack of salt allows dictionary attacks as the same
* password always creates the same key. The low iteration count and
* non-cryptographically secure hash algorithm allow passwords to be tested very
* rapidly.
*
* 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
* developers derive a key and IV on
* their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object.
* @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead.
* @param options `stream.transform` options
*/
function createDecipher(
algorithm: CipherCCMTypes,
password: BinaryLike,