-
Notifications
You must be signed in to change notification settings - Fork 30.4k
/
Copy pathcrypto.md
6173 lines (4951 loc) Β· 192 KB
/
crypto.md
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
# Crypto
<!--introduced_in=v0.3.6-->
> Stability: 2 - Stable
<!-- source_link=lib/crypto.js -->
The `node:crypto` module provides cryptographic functionality that includes a
set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify
functions.
```mjs
const { createHmac } = await import('node:crypto');
const secret = 'abcdefg';
const hash = createHmac('sha256', secret)
.update('I love cupcakes')
.digest('hex');
console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
```
```cjs
const crypto = require('node:crypto');
const secret = 'abcdefg';
const hash = crypto.createHmac('sha256', secret)
.update('I love cupcakes')
.digest('hex');
console.log(hash);
// Prints:
// c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
```
## Determining if crypto support is unavailable
It is possible for Node.js to be built without including support for the
`node:crypto` module. In such cases, attempting to `import` from `crypto` or
calling `require('node:crypto')` will result in an error being thrown.
When using CommonJS, the error thrown can be caught using try/catch:
<!-- eslint-skip -->
```cjs
let crypto;
try {
crypto = require('node:crypto');
} catch (err) {
console.log('crypto support is disabled!');
}
```
When using the lexical ESM `import` keyword, the error can only be
caught if a handler for `process.on('uncaughtException')` is registered
_before_ any attempt to load the module is made (using, for instance,
a preload module).
When using ESM, if there is a chance that the code may be run on a build
of Node.js where crypto support is not enabled, consider using the
[`import()`][] function instead of the lexical `import` keyword:
```mjs
let crypto;
try {
crypto = await import('node:crypto');
} catch (err) {
console.log('crypto support is disabled!');
}
```
## Class: `Certificate`
<!-- YAML
added: v0.11.8
-->
SPKAC is a Certificate Signing Request mechanism originally implemented by
Netscape and was specified formally as part of [HTML5's `keygen` element][].
`<keygen>` is deprecated since [HTML 5.2][] and new projects
should not use this element anymore.
The `node: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][] internally.
### Static method: `Certificate.exportChallenge(spkac[, encoding])`
<!-- YAML
added: v9.0.0
changes:
- version: v15.0.0
pr-url: https://github.com/nodejs/node/pull/35093
description: The spkac argument can be an ArrayBuffer. Limited the size of
the spkac argument to a maximum of 2**31 - 1 bytes.
-->
* `spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}
* `encoding` {string} The [encoding][] of the `spkac` string.
* Returns: {Buffer} The challenge component of the `spkac` data structure, which
includes a public key and a challenge.
```mjs
const { Certificate } = await import('node:crypto');
const spkac = getSpkacSomehow();
const challenge = Certificate.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 string
```
```cjs
const { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
const challenge = Certificate.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 string
```
### Static method: `Certificate.exportPublicKey(spkac[, encoding])`
<!-- YAML
added: v9.0.0
changes:
- version: v15.0.0
pr-url: https://github.com/nodejs/node/pull/35093
description: The spkac argument can be an ArrayBuffer. Limited the size of
the spkac argument to a maximum of 2**31 - 1 bytes.
-->
* `spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}
* `encoding` {string} The [encoding][] of the `spkac` string.
* Returns: {Buffer} The public key component of the `spkac` data structure,
which includes a public key and a challenge.
```mjs
const { Certificate } = await import('node:crypto');
const spkac = getSpkacSomehow();
const publicKey = Certificate.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as <Buffer ...>
```
```cjs
const { Certificate } = require('node:crypto');
const spkac = getSpkacSomehow();
const publicKey = Certificate.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as <Buffer ...>
```
### Static method: `Certificate.verifySpkac(spkac[, encoding])`
<!-- YAML
added: v9.0.0
changes:
- version: v15.0.0
pr-url: https://github.com/nodejs/node/pull/35093
description: The spkac argument can be an ArrayBuffer. Added encoding.
Limited the size of the spkac argument to a maximum of
2**31 - 1 bytes.
-->
* `spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}
* `encoding` {string} The [encoding][] of the `spkac` string.
* Returns: {boolean} `true` if the given `spkac` data structure is valid,
`false` otherwise.
```mjs
import { Buffer } from 'node:buffer';
const { Certificate } = await import('node:crypto');
const spkac = getSpkacSomehow();
console.log(Certificate.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
```
```cjs
const { Certificate } = require('node:crypto');
const { Buffer } = require('node:buffer');
const spkac = getSpkacSomehow();
console.log(Certificate.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
```
### Legacy API
> Stability: 0 - Deprecated
As a legacy interface, it is possible to create new instances of
the `crypto.Certificate` class as illustrated in the examples below.
#### `new crypto.Certificate()`
Instances of the `Certificate` class can be created using the `new` keyword
or by calling `crypto.Certificate()` as a function:
```mjs
const { Certificate } = await import('node:crypto');
const cert1 = new Certificate();
const cert2 = Certificate();
```
```cjs
const { Certificate } = require('node:crypto');
const cert1 = new Certificate();
const cert2 = Certificate();
```
#### `certificate.exportChallenge(spkac[, encoding])`
<!-- YAML
added: v0.11.8
-->
* `spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}
* `encoding` {string} The [encoding][] of the `spkac` string.
* Returns: {Buffer} The challenge component of the `spkac` data structure, which
includes a public key and a challenge.
```mjs
const { Certificate } = await import('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
const challenge = cert.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 string
```
```cjs
const { Certificate } = require('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
const challenge = cert.exportChallenge(spkac);
console.log(challenge.toString('utf8'));
// Prints: the challenge as a UTF8 string
```
#### `certificate.exportPublicKey(spkac[, encoding])`
<!-- YAML
added: v0.11.8
-->
* `spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}
* `encoding` {string} The [encoding][] of the `spkac` string.
* Returns: {Buffer} The public key component of the `spkac` data structure,
which includes a public key and a challenge.
```mjs
const { Certificate } = await import('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
const publicKey = cert.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as <Buffer ...>
```
```cjs
const { Certificate } = require('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
const publicKey = cert.exportPublicKey(spkac);
console.log(publicKey);
// Prints: the public key as <Buffer ...>
```
#### `certificate.verifySpkac(spkac[, encoding])`
<!-- YAML
added: v0.11.8
-->
* `spkac` {string|ArrayBuffer|Buffer|TypedArray|DataView}
* `encoding` {string} The [encoding][] of the `spkac` string.
* Returns: {boolean} `true` if the given `spkac` data structure is valid,
`false` otherwise.
```mjs
import { Buffer } from 'node:buffer';
const { Certificate } = await import('node:crypto');
const cert = Certificate();
const spkac = getSpkacSomehow();
console.log(cert.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
```
```cjs
const { Certificate } = require('node:crypto');
const { Buffer } = require('node:buffer');
const cert = Certificate();
const spkac = getSpkacSomehow();
console.log(cert.verifySpkac(Buffer.from(spkac)));
// Prints: true or false
```
## Class: `Cipher`
<!-- YAML
added: v0.1.94
-->
* Extends: {stream.Transform}
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 [`crypto.createCipher()`][] or [`crypto.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:
```mjs
const {
scrypt,
randomFill,
createCipheriv
} = await import('node: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();
});
});
```
```cjs
const {
scrypt,
randomFill,
createCipheriv
} = require('node: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:
```mjs
import {
createReadStream,
createWriteStream,
} from 'fs';
import {
pipeline
} from 'stream';
const {
scrypt,
randomFill,
createCipheriv
} = await import('node: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;
});
});
});
```
```cjs
const {
createReadStream,
createWriteStream,
} = require('node:fs');
const {
pipeline
} = require('node:stream');
const {
scrypt,
randomFill,
createCipheriv,
} = require('node: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:
```mjs
const {
scrypt,
randomFill,
createCipheriv
} = await import('node: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);
});
});
```
```cjs
const {
scrypt,
randomFill,
createCipheriv,
} = require('node: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);
});
});
```
### `cipher.final([outputEncoding])`
<!-- YAML
added: v0.1.94
-->
* `outputEncoding` {string} The [encoding][] of the return value.
* Returns: {Buffer | string} Any remaining enciphered contents.
If `outputEncoding` is specified, a string is
returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned.
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.
### `cipher.getAuthTag()`
<!-- YAML
added: v1.0.0
-->
* Returns: {Buffer} When using an authenticated encryption mode (`GCM`, `CCM`,
`OCB`, and `chacha20-poly1305` are currently supported), the
`cipher.getAuthTag()` method returns a
[`Buffer`][] containing the _authentication tag_ that has been computed from
the given data.
The `cipher.getAuthTag()` method should only be called after encryption has
been completed using the [`cipher.final()`][] method.
If the `authTagLength` option was set during the `cipher` instance's creation,
this function will return exactly `authTagLength` bytes.
### `cipher.setAAD(buffer[, options])`
<!-- YAML
added: v1.0.0
-->
* `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}
* `options` {Object} [`stream.transform` options][]
* `plaintextLength` {number}
* `encoding` {string} The string encoding to use when `buffer` is a string.
* Returns: {Cipher} for method chaining.
When using an authenticated encryption mode (`GCM`, `CCM`, `OCB`, and
`chacha20-poly1305` are
currently supported), the `cipher.setAAD()` method sets the value used for the
_additional authenticated data_ (AAD) input parameter.
The `plaintextLength` option is optional for `GCM` and `OCB`. When using `CCM`,
the `plaintextLength` option must be specified and its value must match the
length of the plaintext in bytes. See [CCM mode][].
The `cipher.setAAD()` method must be called before [`cipher.update()`][].
### `cipher.setAutoPadding([autoPadding])`
<!-- YAML
added: v0.7.1
-->
* `autoPadding` {boolean} **Default:** `true`
* Returns: {Cipher} for method chaining.
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()`][].
### `cipher.update(data[, inputEncoding][, outputEncoding])`
<!-- YAML
added: v0.1.94
changes:
- version: v6.0.0
pr-url: https://github.com/nodejs/node/pull/5522
description: The default `inputEncoding` changed from `binary` to `utf8`.
-->
* `data` {string|Buffer|TypedArray|DataView}
* `inputEncoding` {string} The [encoding][] of the data.
* `outputEncoding` {string} The [encoding][] of the return value.
* Returns: {Buffer | string}
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.
## Class: `Decipher`
<!-- YAML
added: v0.1.94
-->
* Extends: {stream.Transform}
Instances of the `Decipher` class are used to decrypt data. The class can be
used in one of two ways:
* As a [stream][] that is both readable and writable, where plain encrypted
data is written to produce unencrypted data on the readable side, or
* Using the [`decipher.update()`][] and [`decipher.final()`][] methods to
produce the unencrypted data.
The [`crypto.createDecipher()`][] or [`crypto.createDecipheriv()`][] methods are
used to create `Decipher` instances. `Decipher` objects are not to be created
directly using the `new` keyword.
Example: Using `Decipher` objects as streams:
```mjs
import { Buffer } from 'node:buffer';
const {
scryptSync,
createDecipheriv
} = await import('node:crypto');
const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Key length is dependent on the algorithm. In this case for aes192, it is
// 24 bytes (192 bits).
// Use the async `crypto.scrypt()` instead.
const key = scryptSync(password, 'salt', 24);
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.
const decipher = createDecipheriv(algorithm, key, iv);
let decrypted = '';
decipher.on('readable', () => {
while (null !== (chunk = decipher.read())) {
decrypted += chunk.toString('utf8');
}
});
decipher.on('end', () => {
console.log(decrypted);
// Prints: some clear text data
});
// Encrypted with same algorithm, key and iv.
const encrypted =
'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
decipher.write(encrypted, 'hex');
decipher.end();
```
```cjs
const {
scryptSync,
createDecipheriv,
} = require('node:crypto');
const { Buffer } = require('node:buffer');
const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Key length is dependent on the algorithm. In this case for aes192, it is
// 24 bytes (192 bits).
// Use the async `crypto.scrypt()` instead.
const key = scryptSync(password, 'salt', 24);
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.
const decipher = createDecipheriv(algorithm, key, iv);
let decrypted = '';
decipher.on('readable', () => {
while (null !== (chunk = decipher.read())) {
decrypted += chunk.toString('utf8');
}
});
decipher.on('end', () => {
console.log(decrypted);
// Prints: some clear text data
});
// Encrypted with same algorithm, key and iv.
const encrypted =
'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
decipher.write(encrypted, 'hex');
decipher.end();
```
Example: Using `Decipher` and piped streams:
```mjs
import {
createReadStream,
createWriteStream,
} from 'fs';
import { Buffer } from 'node:buffer';
const {
scryptSync,
createDecipheriv
} = await import('node:crypto');
const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Use the async `crypto.scrypt()` instead.
const key = scryptSync(password, 'salt', 24);
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.
const decipher = createDecipheriv(algorithm, key, iv);
const input = createReadStream('test.enc');
const output = createWriteStream('test.js');
input.pipe(decipher).pipe(output);
```
```cjs
const {
createReadStream,
createWriteStream,
} = require('node:fs');
const {
scryptSync,
createDecipheriv,
} = require('node:crypto');
const { Buffer } = require('node:buffer');
const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Use the async `crypto.scrypt()` instead.
const key = scryptSync(password, 'salt', 24);
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.
const decipher = createDecipheriv(algorithm, key, iv);
const input = createReadStream('test.enc');
const output = createWriteStream('test.js');
input.pipe(decipher).pipe(output);
```
Example: Using the [`decipher.update()`][] and [`decipher.final()`][] methods:
```mjs
import { Buffer } from 'node:buffer';
const {
scryptSync,
createDecipheriv
} = await import('node:crypto');
const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Use the async `crypto.scrypt()` instead.
const key = scryptSync(password, 'salt', 24);
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.
const decipher = createDecipheriv(algorithm, key, iv);
// Encrypted using same algorithm, key and iv.
const encrypted =
'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
// Prints: some clear text data
```
```cjs
const {
scryptSync,
createDecipheriv,
} = require('node:crypto');
const { Buffer } = require('node:buffer');
const algorithm = 'aes-192-cbc';
const password = 'Password used to generate key';
// Use the async `crypto.scrypt()` instead.
const key = scryptSync(password, 'salt', 24);
// The IV is usually passed along with the ciphertext.
const iv = Buffer.alloc(16, 0); // Initialization vector.
const decipher = createDecipheriv(algorithm, key, iv);
// Encrypted using same algorithm, key and iv.
const encrypted =
'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa';
let decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
// Prints: some clear text data
```
### `decipher.final([outputEncoding])`
<!-- YAML
added: v0.1.94
-->
* `outputEncoding` {string} The [encoding][] of the return value.
* Returns: {Buffer | string} Any remaining deciphered contents.
If `outputEncoding` is specified, a string is
returned. If an `outputEncoding` is not provided, a [`Buffer`][] is returned.
Once the `decipher.final()` method has been called, the `Decipher` object can
no longer be used to decrypt data. Attempts to call `decipher.final()` more
than once will result in an error being thrown.
### `decipher.setAAD(buffer[, options])`
<!-- YAML
added: v1.0.0
changes:
- version: v15.0.0
pr-url: https://github.com/nodejs/node/pull/35093
description: The buffer argument can be a string or ArrayBuffer and is
limited to no more than 2 ** 31 - 1 bytes.
- version: v7.2.0
pr-url: https://github.com/nodejs/node/pull/9398
description: This method now returns a reference to `decipher`.
-->
* `buffer` {string|ArrayBuffer|Buffer|TypedArray|DataView}
* `options` {Object} [`stream.transform` options][]
* `plaintextLength` {number}
* `encoding` {string} String encoding to use when `buffer` is a string.
* Returns: {Decipher} for method chaining.
When using an authenticated encryption mode (`GCM`, `CCM`, `OCB`, and
`chacha20-poly1305` are
currently supported), the `decipher.setAAD()` method sets the value used for the
_additional authenticated data_ (AAD) input parameter.
The `options` argument is optional for `GCM`. When using `CCM`, the
`plaintextLength` option must be specified and its value must match the length
of the ciphertext in bytes. See [CCM mode][].
The `decipher.setAAD()` method must be called before [`decipher.update()`][].
When passing a string as the `buffer`, please consider
[caveats when using strings as inputs to cryptographic APIs][].
### `decipher.setAuthTag(buffer[, encoding])`
<!-- YAML
added: v1.0.0
changes:
- version: v15.0.0
pr-url: https://github.com/nodejs/node/pull/35093
description: The buffer argument can be a string or ArrayBuffer and is
limited to no more than 2 ** 31 - 1 bytes.
- version: v11.0.0
pr-url: https://github.com/nodejs/node/pull/17825
description: This method now throws if the GCM tag length is invalid.
- version: v7.2.0
pr-url: https://github.com/nodejs/node/pull/9398
description: This method now returns a reference to `decipher`.
-->
* `buffer` {string|Buffer|ArrayBuffer|TypedArray|DataView}
* `encoding` {string} String encoding to use when `buffer` is a string.
* Returns: {Decipher} for method chaining.
When using an authenticated encryption mode (`GCM`, `CCM`, `OCB`, and
`chacha20-poly1305` are
currently supported), the `decipher.setAuthTag()` method is used to pass in the
received _authentication tag_. If no tag is provided, or if the cipher text
has been tampered with, [`decipher.final()`][] will throw, indicating that the
cipher text should be discarded due to failed authentication. If the tag length
is invalid according to [NIST SP 800-38D][] or does not match the value of the
`authTagLength` option, `decipher.setAuthTag()` will throw an error.
The `decipher.setAuthTag()` method must be called before [`decipher.update()`][]
for `CCM` mode or before [`decipher.final()`][] for `GCM` and `OCB` modes and
`chacha20-poly1305`.
`decipher.setAuthTag()` can only be called once.
When passing a string as the authentication tag, please consider
[caveats when using strings as inputs to cryptographic APIs][].
### `decipher.setAutoPadding([autoPadding])`
<!-- YAML
added: v0.7.1
-->
* `autoPadding` {boolean} **Default:** `true`
* Returns: {Decipher} for method chaining.
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 removing padding.
Turning auto padding off will only work if the input data's length is a
multiple of the ciphers block size.
The `decipher.setAutoPadding()` method must be called before
[`decipher.final()`][].
### `decipher.update(data[, inputEncoding][, outputEncoding])`
<!-- YAML
added: v0.1.94
changes:
- version: v6.0.0
pr-url: https://github.com/nodejs/node/pull/5522
description: The default `inputEncoding` changed from `binary` to `utf8`.
-->
* `data` {string|Buffer|TypedArray|DataView}
* `inputEncoding` {string} The [encoding][] of the `data` string.
* `outputEncoding` {string} The [encoding][] of the return value.
* Returns: {Buffer | string}
Updates the decipher 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`][]. If `data` is a
[`Buffer`][] 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 `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 being thrown.
## Class: `DiffieHellman`
<!-- YAML
added: v0.5.0
-->
The `DiffieHellman` class is a utility for creating Diffie-Hellman key
exchanges.
Instances of the `DiffieHellman` class can be created using the
[`crypto.createDiffieHellman()`][] function.
```mjs
import assert from 'node:assert';
const {
createDiffieHellman
} = await import('node:crypto');
// Generate Alice's keys...
const alice = createDiffieHellman(2048);
const aliceKey = alice.generateKeys();
// Generate Bob's keys...
const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator());
const bobKey = bob.generateKeys();
// Exchange and generate the secret...
const aliceSecret = alice.computeSecret(bobKey);