doc: fix reference to API `hash.final`
[platform/upstream/nodejs.git] / doc / api / crypto.markdown
1 # Crypto
2
3     Stability: 2 - Stable
4
5 The `crypto` module provides cryptographic functionality that includes a set of
6 wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign and verify functions.
7
8 Use `require('crypto')` to access this module.
9
10 ```js
11 const crypto = require('crypto');
12
13 const secret = 'abcdefg';
14 const hash = crypto.createHmac('sha256', secret)
15                    .update('I love cupcakes')
16                    .digest('hex');
17 console.log(hash);
18   // Prints:
19   //   c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
20 ```
21
22 ## Class: Certificate
23
24 SPKAC is a Certificate Signing Request mechanism originally implemented by
25 Netscape and now specified formally as part of [HTML5's `keygen` element][].
26
27 The `crypto` module provides the `Certificate` class for working with SPKAC
28 data. The most common usage is handling output generated by the HTML5
29 `<keygen>` element. Node.js uses [OpenSSL's SPKAC implementation][] internally.
30
31 ### new crypto.Certificate()
32
33 Instances of the `Certificate` class can be created using the `new` keyword
34 or by calling `crypto.Certificate()` as a function:
35
36 ```js
37 const crypto = require('crypto');
38
39 const cert1 = new crypto.Certificate();
40 const cert2 = crypto.Certificate();
41 ```
42
43 ### certificate.exportChallenge(spkac)
44
45 The `spkac` data structure includes a public key and a challenge. The
46 `certificate.exportChallenge()` returns the challenge component in the
47 form of a Node.js [`Buffer`][]. The `spkac` argument can be either a string
48 or a [`Buffer`][].
49
50 ```js
51 const cert = require('crypto').Certificate();
52 const spkac = getSpkacSomehow();
53 const challenge = cert.exportChallenge(spkac);
54 console.log(challenge.toString('utf8'));
55   // Prints the challenge as a UTF8 string
56 ```
57
58 ### Certificate.exportPublicKey(spkac)
59
60 The `spkac` data structure includes a public key and a challenge. The
61 `certificate.exportPublicKey()` returns the public key component in the
62 form of a Node.js [`Buffer`][]. The `spkac` argument can be either a string
63 or a [`Buffer`][].
64
65 ```js
66 const cert = require('crypto').Certificate();
67 const spkac = getSpkacSomehow();
68 const publicKey = cert.exportPublicKey(spkac);
69 console.log(publicKey);
70   // Prints the public key as <Buffer ...>
71 ```
72
73 ### Certificate.verifySpkac(spkac)
74
75 Returns `true` if the given `spkac` data structure is valid, `false` otherwise.
76 The `spkac` argument must be a Node.js [`Buffer`][].
77
78 ```js
79 const cert = require('crypto').Certificate();
80 const spkac = getSpkacSomehow();
81 console.log(cert.verifySpkac(new Buffer(spkac)));
82   // Prints true or false
83 ```
84
85 ## Class: Cipher
86
87 Instances of the `Cipher` class are used to encrypt data. The class can be
88 used in one of two ways:
89
90 - As a [stream][] that is both readable and writable, where plain unencrypted
91   data is written to produce encrypted data on the readable side, or
92 - Using the `cipher.update()` and `cipher.final()` methods to produce the
93   encrypted data.
94
95 The `crypto.createCipher()` or `crypto.createCipheriv()` methods are used to
96 create `Cipher` instances. `Cipher` objects are not to be created directly
97 using the `new` keyword.
98
99 Example: Using `Cipher` objects as streams:
100
101 ```js
102 const crypto = require('crypto');
103 const cipher = crypto.createCipher('aes192', 'a password');
104
105 var encrypted = '';
106 cipher.on('readable', () => {
107   var data = cipher.read();
108   if (data)
109     encrypted += data.toString('hex');
110 });
111 cipher.on('end', () => {
112   console.log(encrypted);
113   // Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504
114 });
115
116 cipher.write('some clear text data');
117 cipher.end();
118 ```
119
120 Example: Using `Cipher` and piped streams:
121
122 ```js
123 const crypto = require('crypto');
124 const fs = require('fs');
125 const cipher = crypto.createCipher('aes192', 'a password');
126
127 const input = fs.createReadStream('test.js');
128 const output = fs.createWriteStream('test.enc');
129
130 input.pipe(cipher).pipe(output);
131 ```
132
133 Example: Using the `cipher.update()` and `cipher.final()` methods:
134
135 ```js
136 const crypto = require('crypto');
137 const cipher = crypto.createCipher('aes192', 'a password');
138
139 var encrypted = cipher.update('some clear text data', 'utf8', 'hex');
140 encrypted += cipher.final('hex');
141 console.log(encrypted);
142   // Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504
143 ```
144
145 ### cipher.final([output_encoding])
146
147 Returns any remaining enciphered contents. If `output_encoding`
148 parameter is one of `'binary'`, `'base64'` or `'hex'`, a string is returned.
149 If an `output_encoding` is not provided, a [`Buffer`][] is returned.
150
151 Once the `cipher.final()` method has been called, the `Cipher` object can no
152 longer be used to encrypt data. Attempts to call `cipher.final()` more than
153 once will result in an error being thrown.
154
155 ### cipher.setAAD(buffer)
156
157 When using an authenticated encryption mode (only `GCM` is currently
158 supported), the `cipher.getAAD()` method sets the value used for the
159 _additional authenticated data_ (AAD) input parameter.
160
161 ### cipher.getAuthTag()
162
163 When using an authenticated encryption mode (only `GCM` is currently
164 supported), the `cipher.getAuthTag()` method returns a [`Buffer`][] containing
165 the _authentication tag_ that has been computed from the given data.
166
167 The `cipher.getAuthTag()` method should only be called after encryption has
168 been completed using the `cipher.final()` method.
169
170 ### cipher.setAutoPadding(auto_padding=true)
171
172 When using block encryption algorithms, the `Cipher` class will automatically
173 add padding to the input data to the appropriate block size. To disable the
174 default padding call `cipher.setAutoPadding(false)`.
175
176 When `auto_padding` is `false`, the length of the entire input data must be a
177 multiple of the cipher's block size or `cipher.final()` will throw an Error.
178 Disabling automatic padding is useful for non-standard padding, for instance
179 using `0x0` instead of PKCS padding.
180
181 The `cipher.setAutoPadding()` method must be called before `cipher.final()`.
182
183 ### cipher.update(data[, input_encoding][, output_encoding])
184
185 Updates the cipher with `data`. If the `input_encoding` argument is given,
186 it's value must be one of `'utf8'`, `'ascii'`, or `'binary'` and the `data`
187 argument is a string using the specified encoding. If the `input_encoding`
188 argument is not given, `data` must be a [`Buffer`][]. If `data` is a
189 [`Buffer`][] then `input_encoding` is ignored.
190
191 The `output_encoding` specifies the output format of the enciphered
192 data, and can be `'binary'`, `'base64'` or `'hex'`. If the `output_encoding`
193 is specified, a string using the specified encoding is returned. If no
194 `output_encoding` is provided, a [`Buffer`][] is returned.
195
196 The `cipher.update()` method can be called multiple times with new data until
197 `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()`
198 will result in an error being thrown.
199
200 ## Class: Decipher
201
202 Instances of the `Decipher` class are used to decrypt data. The class can be
203 used in one of two ways:
204
205 - As a [stream][] that is both readable and writable, where plain encrypted
206   data is written to produce unencrypted data on the readable side, or
207 - Using the `decipher.update()` and `decipher.final()` methods to produce the
208   unencrypted data.
209
210 The `crypto.createDecipher()` or `crypto.createDecipheriv()` methods are used
211 to create `Decipher` instances. `Decipher` objects are not to be created
212 directly using the `new` keyword.
213
214 Example: Using `Decipher` objects as streams:
215
216 ```js
217 const crypto = require('crypto');
218 const decipher = crypto.createDecipher('aes192', 'a password');
219
220 var decrypted = '';
221 decipher.on('readable', () => {
222   var data = decipher.read();
223   if (data)
224   decrypted += data.toString('utf8');
225 });
226 decipher.on('end', () => {
227   console.log(decrypted);
228   // Prints: some clear text data
229 });
230
231 var encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
232 decipher.write(encrypted, 'hex');
233 decipher.end();
234 ```
235
236 Example: Using `Decipher` and piped streams:
237
238 ```js
239 const crypto = require('crypto');
240 const fs = require('fs');
241 const decipher = crypto.createDecipher('aes192', 'a password');
242
243 const input = fs.createReadStream('test.enc');
244 const output = fs.createWriteStream('test.js');
245
246 input.pipe(decipher).pipe(output);
247 ```
248
249 Example: Using the `decipher.update()` and `decipher.final()` methods:
250
251 ```js
252 const crypto = require('crypto');
253 const decipher = crypto.createDecipher('aes192', 'a password');
254
255 var encrypted = 'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
256 var decrypted = decipher.update(encrypted, 'hex', 'utf8');
257 decrypted += decipher.final('utf8');
258 console.log(decrypted);
259   // Prints: some clear text data
260 ```
261
262 ### decipher.final([output_encoding])
263
264 Returns any remaining deciphered contents. If `output_encoding`
265 parameter is one of `'binary'`, `'base64'` or `'hex'`, a string is returned.
266 If an `output_encoding` is not provided, a [`Buffer`][] is returned.
267
268 Once the `decipher.final()` method has been called, the `Decipher` object can
269 no longer be used to decrypt data. Attempts to call `decipher.final()` more
270 than once will result in an error being thrown.
271
272 ### decipher.setAAD(buffer)
273
274 When using an authenticated encryption mode (only `GCM` is currently
275 supported), the `cipher.getAAD()` method sets the value used for the
276 _additional authenticated data_ (AAD) input parameter.
277
278 ### decipher.setAuthTag(buffer)
279
280 When using an authenticated encryption mode (only `GCM` is currently
281 supported), the `decipher.setAuthTag()` method is used to pass in the
282 received _authentication tag_. If no tag is provided, or if the ciphertext
283 has been tampered with, `decipher.final()` with throw, indicating that the
284 ciphertext should be discarded due to failed authentication.
285
286 ### decipher.setAutoPadding(auto_padding=true)
287
288 When data has been encrypted without standard block padding, calling
289 `decipher.setAuthPadding(false)` will disable automatic padding to prevent
290 `decipher.final()` from checking for and removing padding.
291
292 Turning auto padding off will only work if the input data's length is a
293 multiple of the ciphers block size.
294
295 The `decipher.setAutoPadding()` method must be called before
296 `decipher.update()`.
297
298 ### decipher.update(data[, input_encoding][, output_encoding])
299
300 Updates the decipher with `data`. If the `input_encoding` argument is given,
301 it's value must be one of `'binary'`, `'base64'`, or `'hex'` and the `data`
302 argument is a string using the specified encoding. If the `input_encoding`
303 argument is not given, `data` must be a [`Buffer`][]. If `data` is a
304 [`Buffer`][] then `input_encoding` is ignored.
305
306 The `output_encoding` specifies the output format of the enciphered
307 data, and can be `'binary'`, `'ascii'` or `'utf8'`. If the `output_encoding`
308 is specified, a string using the specified encoding is returned. If no
309 `output_encoding` is provided, a [`Buffer`][] is returned.
310
311 The `decipher.update()` method can be called multiple times with new data until
312 `decipher.final()` is called. Calling `decipher.update()` after
313 `decipher.final()` will result in an error being thrown.
314
315 ## Class: DiffieHellman
316
317 The `DiffieHellman` class is a utility for creating Diffie-Hellman key
318 exchanges.
319
320 Instances of the `DiffieHellman` class can be created using the
321 `crypto.createDiffieHellman()` function.
322
323 ```js
324 const crypto = require('crypto');
325 const assert = require('assert');
326
327 // Generate Alice's keys...
328 const alice = crypto.createDiffieHellman(11);
329 const alice_key = alice.generateKeys();
330
331 // Generate Bob's keys...
332 const bob = crypto.createDiffieHellman(11);
333 const bob_key = bob.generateKeys();
334
335 // Exchange and generate the secret...
336 const alice_secret = alice.computeSecret(bob_key);
337 const bob_secret = bob.computeSecret(alice_key);
338
339 assert(alice_secret, bob_secret);
340   // OK
341 ```
342
343 ### diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding])
344
345 Computes the shared secret using `other_public_key` as the other
346 party's public key and returns the computed shared secret. The supplied
347 key is interpreted using the specified `input_encoding`, and secret is
348 encoded using specified `output_encoding`. Encodings can be
349 `'binary'`, `'hex'`, or `'base64'`. If the `input_encoding` is not
350 provided, `other_public_key` is expected to be a [`Buffer`][].
351
352 If `output_encoding` is given a string is returned; otherwise, a
353 [`Buffer`][] is returned.
354
355 ### diffieHellman.generateKeys([encoding])
356
357 Generates private and public Diffie-Hellman key values, and returns
358 the public key in the specified `encoding`. This key should be
359 transferred to the other party. Encoding can be `'binary'`, `'hex'`,
360 or `'base64'`.  If `encoding` is provided a string is returned; otherwise a
361 [`Buffer`][] is returned.
362
363 ### diffieHellman.getGenerator([encoding])
364
365 Returns the Diffie-Hellman generator in the specified `encoding`, which can
366 be `'binary'`, `'hex'`, or `'base64'`. If  `encoding` is provided a string is
367 returned; otherwise a [`Buffer`][] is returned.
368
369 ### diffieHellman.getPrime([encoding])
370
371 Returns the Diffie-Hellman prime in the specified `encoding`, which can
372 be `'binary'`, `'hex'`, or `'base64'`. If `encoding` is provided a string is
373 returned; otherwise a [`Buffer`][] is returned.
374
375 ### diffieHellman.getPrivateKey([encoding])
376
377 Returns the Diffie-Hellman private key in the specified `encoding`,
378 which can be `'binary'`, `'hex'`, or `'base64'`. If `encoding` is provided a
379 string is returned; otherwise a [`Buffer`][] is returned.
380
381 ### diffieHellman.getPublicKey([encoding])
382
383 Returns the Diffie-Hellman public key in the specified `encoding`, which
384 can be `'binary'`, `'hex'`, or `'base64'`. If `encoding` is provided a
385 string is returned; otherwise a [`Buffer`][] is returned.
386
387 ### diffieHellman.setPrivateKey(private_key[, encoding])
388
389 Sets the Diffie-Hellman private key. If the `encoding` argument is provided
390 and is either `'binary'`, `'hex'`, or `'base64'`, `private_key` is expected
391 to be a string. If no `encoding` is provided, `private_key` is expected
392 to be a [`Buffer`][].
393
394 ### diffieHellman.setPublicKey(public_key[, encoding])
395
396 Sets the Diffie-Hellman public key. If the `encoding` argument is provided
397 and is either `'binary'`, `'hex'` or `'base64'`, `public_key` is expected
398 to be a string. If no `encoding` is provided, `public_key` is expected
399 to be a [`Buffer`][].
400
401 ### diffieHellman.verifyError
402
403 A bit field containing any warnings and/or errors resulting from a check
404 performed during initialization of the `DiffieHellman` object.
405
406 The following values are valid for this property (as defined in `constants`
407 module):
408
409 * `DH_CHECK_P_NOT_SAFE_PRIME`
410 * `DH_CHECK_P_NOT_PRIME`
411 * `DH_UNABLE_TO_CHECK_GENERATOR`
412 * `DH_NOT_SUITABLE_GENERATOR`
413
414 ## Class: ECDH
415
416 The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)
417 key exchanges.
418
419 Instances of the `ECDH` class can be created using the
420 `crypto.createECDH()` function.
421
422 ```js
423 const crypto = require('crypto');
424 const assert = require('assert');
425
426 // Generate Alice's keys...
427 const alice = crypto.createECDH('secp521r1');
428 const alice_key = alice.generateKeys();
429
430 // Generate Bob's keys...
431 const bob = crypto.createECDH('secp521r1');
432 const bob_key = bob.generateKeys();
433
434 // Exchange and generate the secret...
435 const alice_secret = alice.computeSecret(bob_key);
436 const bob_secret = bob.computeSecret(alice_key);
437
438 assert(alice_secret, bob_secret);
439   // OK
440 ```
441
442 ### ECDH.computeSecret(other_public_key[, input_encoding][, output_encoding])
443
444 Computes the shared secret using `other_public_key` as the other
445 party's public key and returns the computed shared secret. The supplied
446 key is interpreted using specified `input_encoding`, and the returned secret
447 is encoded using the specified `output_encoding`. Encodings can be
448 `'binary'`, `'hex'`, or `'base64'`. If the `input_encoding` is not
449 provided, `other_public_key` is expected to be a [`Buffer`][].
450
451 If `output_encoding` is given a string will be returned; otherwise a
452 [`Buffer`][] is returned.
453
454 ### ECDH.generateKeys([encoding[, format]])
455
456 Generates private and public EC Diffie-Hellman key values, and returns
457 the public key in the specified `format` and `encoding`. This key should be
458 transferred to the other party.
459
460 The `format` arguments specifies point encoding and can be `'compressed'`,
461 `'uncompressed'`, or `'hybrid'`. If `format` is not specified, the point will
462 be returned in `'uncompressed'` format.
463
464 The `encoding` argument can be `'binary'`, `'hex'`, or `'base64'`. If
465 `encoding` is provided a string is returned; otherwise a [`Buffer`][]
466 is returned.
467
468 ### ECDH.getPrivateKey([encoding])
469
470 Returns the EC Diffie-Hellman private key in the specified `encoding`,
471 which can be `'binary'`, `'hex'`, or `'base64'`. If `encoding` is provided
472 a string is returned; otherwise a [`Buffer`][] is returned.
473
474 ### ECDH.getPublicKey([encoding[, format]])
475
476 Returns the EC Diffie-Hellman public key in the specified `encoding` and
477 `format`.
478
479 The `format` argument specifies point encoding and can be `'compressed'`,
480 `'uncompressed'`, or `'hybrid'`. If `format` is not specified the point will be
481 returned in `'uncompressed'` format.
482
483 The `encoding` argument can be `'binary'`, `'hex'`, or `'base64'`. If
484 `encoding` is specified, a string is returned; otherwise a [`Buffer`][] is
485 returned.
486
487 ### ECDH.setPrivateKey(private_key[, encoding])
488
489 Sets the EC Diffie-Hellman private key. The `encoding` can be `'binary'`,
490 `'hex'` or `'base64'`. If `encoding` is provided, `private_key` is expected
491 to be a string; otherwise `private_key` is expected to be a [`Buffer`][]. If
492 `private_key` is not valid for the curve specified when the `ECDH` object was
493 created, an error is thrown. Upon setting the private key, the associated
494 public point (key) is also generated and set in the ECDH object.
495
496 ### ECDH.setPublicKey(public_key[, encoding])
497
498     Stability: 0 - Deprecated
499
500 Sets the EC Diffie-Hellman public key. Key encoding can be `'binary'`,
501 `'hex'` or `'base64'`. If `encoding` is provided `public_key` is expected to
502 be a string; otherwise a [`Buffer`][] is expected.
503
504 Note that there is not normally a reason to call this method because `ECDH`
505 only requires a private key and the other party's public key to compute the
506 shared secret. Typically either `ecdh.generateKeys()` or `ecdh.setPrivateKey()`
507 will be called. The `ecdh.setPrivateKey()` method attempts to generate the
508 public point/key associated with the private key being set.
509
510 Example (obtaining a shared secret):
511
512 ```js
513 const crypto = require('crypto');
514 const alice = crypto.createECDH('secp256k1');
515 const bob = crypto.createECDH('secp256k1');
516
517 // Note: This is a shortcut way to specify one of Alice's previous private
518 // keys. It would be unwise to use such a predictable private key in a real
519 // application.
520 alice.setPrivateKey(
521   crypto.createHash('sha256').update('alice', 'utf8').digest()
522 );
523
524 // Bob uses a newly generated cryptographically strong
525 // pseudorandom key pair bob.generateKeys();
526
527 const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
528 const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
529
530 // alice_secret and bob_secret should be the same shared secret value
531 console.log(alice_secret === bob_secret);
532 ```
533
534 ## Class: Hash
535
536 The `Hash` class is a utility for creating hash digests of data. It can be
537 used in one of two ways:
538
539 - As a [stream][] that is both readable and writable, where data is written
540   to produce a computed hash digest on the readable side, or
541 - Using the `hash.update()` and `hash.digest()` methods to produce the
542   computed hash.
543
544 The `crypto.createHash()` method is used to create `Hash` instances. `Hash`
545 objects are not to be created directly using the `new` keyword.
546
547 Example: Using `Hash` objects as streams:
548
549 ```js
550 const crypto = require('crypto');
551 const hash = crypto.createHash('sha256');
552
553 hash.on('readable', () => {
554   var data = hash.read();
555   if (data)
556     console.log(data.toString('hex'));
557     // Prints:
558     //   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
559 });
560
561 hash.write('some data to hash');
562 hash.end();
563 ```
564
565 Example: Using `Hash` and piped streams:
566
567 ```js
568 const crypto = require('crypto');
569 const fs = require('fs');
570 const hash = crypto.createHash('sha256');
571
572 const input = fs.createReadStream('test.js');
573 input.pipe(hash).pipe(process.stdout);
574 ```
575
576 Example: Using the `hash.update()` and `hash.digest()` methods:
577
578 ```js
579 const crypto = require('crypto');
580 const hash = crypto.createHash('sha256');
581
582 hash.update('some data to hash');
583 console.log(hash.digest('hex'));
584   // Prints:
585   //   6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
586 ```
587
588 ### hash.digest([encoding])
589
590 Calculates the digest of all of the data passed to be hashed (using the
591 `hash.update()` method). The `encoding` can be `'hex'`, `'binary'` or
592 `'base64'`.  If `encoding` is provided a string will be returned; otherwise
593 a [`Buffer`][] is returned.
594
595 The `Hash` object can not be used again after `hash.digest()` method has been
596 called. Multiple calls will cause an error to be thrown.
597
598 ### hash.update(data[, input_encoding])
599
600 Updates the hash content with the given `data`, the encoding of which
601 is given in `input_encoding` and can be `'utf8'`, `'ascii'` or
602 `'binary'`.  If `encoding` is not provided, and the `data` is a string, an
603 encoding of `'binary'` is enforced. If `data` is a [`Buffer`][] then
604 `input_encoding` is ignored.
605
606 This can be called many times with new data as it is streamed.
607
608 ## Class: Hmac
609
610 The `Hmac` Class is a utility for creating cryptographic HMAC digests. It can
611 be used in one of two ways:
612
613 - As a [stream][] that is both readable and writable, where data is written
614   to produce a computed HMAC digest on the readable side, or
615 - Using the `hmac.update()` and `hmac.final()` methods to produce the
616   computed HMAC digest.
617
618 The `crypto.createHmac()` method is used to create `Hmac` instances. `Hmac`
619 objects are not to be created directly using the `new` keyword.
620
621 Example: Using `Hmac` objects as streams:
622
623 ```js
624 const crypto = require('crypto');
625 const hmac = crypto.createHmac('sha256', 'a secret');
626
627 hmac.on('readable', () => {
628   var data = hmac.read();
629   if (data)
630     console.log(data.toString('hex'));
631     // Prints:
632     //   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
633 });
634
635 hmac.write('some data to hash');
636 hmac.end();
637 ```
638
639 Example: Using `Hmac` and piped streams:
640
641 ```js
642 const crypto = require('crypto');
643 const fs = require('fs');
644 const hmac = crypto.createHmac('sha256', 'a secret');
645
646 const input = fs.createReadStream('test.js');
647 input.pipe(hmac).pipe(process.stdout);
648 ```
649
650 Example: Using the `hmac.update()` and `hmac.digest()` methods:
651
652 ```js
653 const crypto = require('crypto');
654 const hmac = crypto.createHmac('sha256', 'a secret');
655
656 hmac.update('some data to hash');
657 console.log(hmac.digest('hex'));
658   // Prints:
659   //   7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
660 ```
661
662 ### hmac.digest([encoding])
663
664 Calculates the HMAC digest of all of the data passed using `hmac.update()`. The
665 `encoding` can be `'hex'`, `'binary'` or `'base64'`.  If `encoding` is provided
666 a string is returned; otherwise a [`Buffer`][] is returned;
667
668 The `Hmac` object can not be used again after `hmac.digest()` has been
669 called. Multiple calls to `hmac.digest()` will result in an error being thrown.
670
671 ### hmac.update(data)
672
673 Update the `Hmac` content with the given `data`.  This can be called
674 many times with new data as it is streamed.
675
676 ## Class: Sign
677
678 The `Sign` Class is a utility for generating signatures. It can be used in one
679 of two ways:
680
681 - As a writable [stream][], where data to be signed is written and the
682   `sign.sign()` method is used to generate and return the signature, or
683 - Using the `sign.update()` and `sign.sign()` methods to produce the
684   signature.
685
686 The `crypto.createSign()` method is used to create `Sign` instances. `Sign`
687 objects are not to be created directly using the `new` keyword.
688
689 Example: Using `Sign` objects as streams:
690
691 ```js
692 const crypto = require('crypto');
693 const sign = crypto.createSign('RSA-SHA256');
694
695 sign.write('some data to sign');
696 sign.end();
697
698 const private_key = getPrivateKeySomehow();
699 console.log(sign.sign(private_key, 'hex'));
700   // Prints the calculated signature
701 ```
702
703 Example: Using the `sign.update()` and `sign.sign()` methods:
704
705 ```js
706 const crypto = require('crypto');
707 const sign = crypto.createSign('RSA-SHA256');
708
709 sign.update('some data to sign');
710
711 const private_key = getPrivateKeySomehow();
712 console.log(sign.sign(private_key, 'hex'));
713   // Prints the calculated signature
714 ```
715
716 ### sign.sign(private_key[, output_format])
717
718 Calculates the signature on all the data passed through using either
719 `sign.update()` or `sign.write()`.
720
721 The `private_key` argument can be an object or a string. If `private_key` is a
722 string, it is treated as a raw key with no passphrase. If `private_key` is an
723 object, it is interpreted as a hash containing two properties:
724
725 * `key` : {String} - PEM encoded private key
726 * `passphrase` : {String} - passphrase for the private key
727
728 The `output_format` can specify one of `'binary'`, `'hex'` or `'base64'`. If
729 `output_format` is provided a string is returned; otherwise a [`Buffer`][] is
730 returned.
731
732 The `Sign` object can not be again used after `sign.sign()` method has been
733 called. Multiple calls to `sign.sign()` will result in an error being thrown.
734
735 ### sign.update(data)
736
737 Updates the sign object with the given `data`.  This can be called many times
738 with new data as it is streamed.
739
740 ## Class: Verify
741
742 The `Verify` class is a utility for verifying signatures. It can be used in one
743 of two ways:
744
745 - As a writable [stream][] where written data is used to validate against the
746   supplied signature, or
747 - Using the `verify.update()` and `verify.verify()` methods to verify the
748   signature.
749
750   The `crypto.createSign()` method is used to create `Sign` instances. `Sign`
751   objects are not to be created directly using the `new` keyword.
752
753 Example: Using `Verify` objects as streams:
754
755 ```js
756 const crypto = require('crypto');
757 const verify = crypto.createVerify('RSA-SHA256');
758
759 verify.write('some data to sign');
760 verify.end();
761
762 const public_key = getPublicKeySomehow();
763 const signature = getSignatureToVerify();
764 console.log(sign.verify(public_key, signature));
765   // Prints true or false
766 ```
767
768 Example: Using the `verify.update()` and `verify.verify()` methods:
769
770 ```js
771 const crypto = require('crypto');
772 const verify = crypto.createVerify('RSA-SHA256');
773
774 verify.update('some data to sign');
775
776 const public_key = getPublicKeySomehow();
777 const signature = getSignatureToVerify();
778 console.log(verify.verify(public_key, signature));
779   // Prints true or false
780 ```
781
782 ### verifier.update(data)
783
784 Updates the verifier object with the given `data`.  This can be called many
785 times with new data as it is streamed.
786
787 ### verifier.verify(object, signature[, signature_format])
788
789 Verifies the provided data using the given `object` and `signature`.
790 The `object` argument is a string containing a PEM encoded object, which can be
791 one an RSA public key, a DSA public key, or an X.509 certificate.
792 The `signature` argument is the previously calculated signature for the data, in
793 the `signature_format` which can be `'binary'`, `'hex'` or `'base64'`.
794 If a `signature_format` is specified, the `signature` is expected to be a
795 string; otherwise `signature` is expected to be a [`Buffer`][].
796
797 Returns `true` or `false` depending on the validity of the signature for
798 the data and public key.
799
800 The `verifier` object can not be used again after `verify.verify()` has been
801 called. Multiple calls to `verify.verify()` will result in an error being
802 thrown.
803
804 ## `crypto` module methods and properties
805
806 ### crypto.DEFAULT_ENCODING
807
808 The default encoding to use for functions that can take either strings
809 or [buffers][].  The default value is `'buffer'`, which makes methods default
810 to [`Buffer`][] objects.
811
812 The `crypto.DEFAULT_ENCODING` mechanism is provided for backwards compatibility
813 with legacy programs that expect `'binary'` to be the default encoding.
814
815 New applications should expect the default to be `'buffer'`. This property may
816 become deprecated in a future Node.js release.
817
818 ### crypto.createCipher(algorithm, password)
819
820 Creates and returns a `Cipher` object that uses the given `algorithm` and
821 `password`.
822
823 The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc.  On
824 recent OpenSSL releases, `openssl list-cipher-algorithms` will display the
825 available cipher algorithms.
826
827 The `password` is used to derive the cipher key and initialization vector (IV).
828 The value must be either a `'binary'` encoded string or a [`Buffer`[].
829
830 The implementation of `crypto.createCipher()` derives keys using the OpenSSL
831 function [`EVP_BytesToKey`][] with the digest algorithm set to MD5, one
832 iteration, and no salt. The lack of salt allows dictionary attacks as the same
833 password always creates the same key. The low iteration count and
834 non-cryptographically secure hash algorithm allow passwords to be tested very
835 rapidly.
836
837 In line with OpenSSL's recommendation to use pbkdf2 instead of
838 [`EVP_BytesToKey`][] it is recommended that developers derive a key and IV on
839 their own using [`crypto.pbkdf2`][] and to use [`crypto.createCipheriv()`][]
840 to create the `Cipher` object.
841
842 ### crypto.createCipheriv(algorithm, key, iv)
843
844 Creates and returns a `Cipher` object, with the given `algorithm`, `key` and
845 initialization vector (`iv`).
846
847 The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc.  On
848 recent OpenSSL releases, `openssl list-cipher-algorithms` will display the
849 available cipher algorithms.
850
851 The `key` is the raw key used by the `algorithm` and `iv` is an
852 [initialization vector][]. Both arguments must be `'binary'` encoded strings or
853 [buffers][].
854
855 ### crypto.createCredentials(details)
856
857     Stability: 0 - Deprecated: Use [`tls.createSecureContext()`][] instead.
858
859 The `crypto.createCredentials()` method is a deprecated alias for creating
860 and returning a `tls.SecureContext` object. The `crypto.createCredentials()`
861 method should not be used.
862
863 The optional `details` argument is a hash object with keys:
864
865 * `pfx` : {String|Buffer} - PFX or PKCS12 encoded private
866   key, certificate and CA certificates
867 * `key` : {String} - PEM encoded private key
868 * `passphrase` : {String} - passphrase for the private key or PFX
869 * `cert` : {String} - PEM encoded certificate
870 * `ca` : {String|Array} - Either a string or array of strings of PEM encoded CA
871   certificates to trust.
872 * `crl` : {String|Array} - Either a string or array of strings of PEM encoded CRLs
873   (Certificate Revocation List)
874 * `ciphers`: {String} using the [OpenSSL cipher list format][] describing the
875   cipher algorithms to use or exclude.
876
877 If no 'ca' details are given, Node.js will use Mozilla's default
878 [publicly trusted list of CAs][].
879
880 ### crypto.createDecipher(algorithm, password)
881
882 Creates and returns a `Decipher` object that uses the given `algorithm` and
883 `password` (key).
884
885 The implementation of `crypto.createDecipher()` derives keys using the OpenSSL
886 function [`EVP_BytesToKey`][] with the digest algorithm set to MD5, one
887 iteration, and no salt. The lack of salt allows dictionary attacks as the same
888 password always creates the same key. The low iteration count and
889 non-cryptographically secure hash algorithm allow passwords to be tested very
890 rapidly.
891
892 In line with OpenSSL's recommendation to use pbkdf2 instead of
893 [`EVP_BytesToKey`][] it is recommended that developers derive a key and IV on
894 their own using [`crypto.pbkdf2`][] and to use [`crypto.createDecipheriv()`][]
895 to create the `Decipher` object.
896
897 ### crypto.createDecipheriv(algorithm, key, iv)
898
899 Creates and returns a `Decipher` object that uses the given `algorithm`, `key`
900 and initialization vector (`iv`).
901
902 The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc.  On
903 recent OpenSSL releases, `openssl list-cipher-algorithms` will display the
904 available cipher algorithms.
905
906 The `key` is the raw key used by the `algorithm` and `iv` is an
907 [initialization vector][]. Both arguments must be `'binary'` encoded strings or
908 [buffers][].
909
910 ## crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding])
911
912 Creates a `DiffieHellman` key exchange object using the supplied `prime` and an
913 optional specific `generator`.
914
915 The `generator` argument can be a number, string, or [`Buffer`][]. If
916 `generator` is not specified, the value `2` is used.
917
918 The `prime_encoding` and `generator_encoding` arguments can be `'binary'`,
919 `'hex'`, or `'base64'`.
920
921 If `prime_encoding` is specified, `prime` is expected to be a string; otherwise
922 a [`Buffer`][] is expected.
923
924 If `generator_encoding` is specified, `generator` is expected to be a string;
925 otherwise either a number or [`Buffer`][] is expected.
926
927 ### crypto.createDiffieHellman(prime_length[, generator])
928
929 Creates a `DiffieHellman` key exchange object and generates a prime of
930 `prime_length` bits using an optional specific numeric `generator`.
931 If `generator` is not specified, the value `2` is used.
932
933 ### crypto.createECDH(curve_name)
934
935 Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a
936 predefined curve specified by the `curve_name` string. Use
937 [`crypto.getCurves()`][] to obtain a list of available curve names. On recent
938 OpenSSL releases, `openssl ecparam -list_curves` will also display the name
939 and description of each available elliptic curve.
940
941 ### crypto.createHash(algorithm)
942
943 Creates and returns a `Hash` object that can be used to generate hash digests
944 using the given `algorithm`.
945
946 The `algorithm` is dependent on the available algorithms supported by the
947 version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
948 On recent releases of OpenSSL, `openssl list-message-digest-algorithms` will
949 display the available digest algorithms.
950
951 Example: generating the sha256 sum of a file
952
953 ```js
954 const filename = process.argv[2];
955 const crypto = require('crypto');
956 const fs = require('fs');
957
958 const hash = crypto.createHash('sha256');
959
960 const input = fs.createReadStream(filename);
961 input.on('readable', () => {
962   var data = input.read();
963   if (data)
964     hash.update(data);
965   else {
966     console.log(`${hash.digest('hex')} ${filename}`);
967   }
968 });
969 ```
970
971 ### crypto.createHmac(algorithm, key)
972
973 Creates and returns an `Hmac` object that uses the given `algorithm` and `key`.
974
975 The `algorithm` is dependent on the available algorithms supported by the
976 version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
977 On recent releases of OpenSSL, `openssl list-message-digest-algorithms` will
978 display the available digest algorithms.
979
980 The `key` is the HMAC key used to generate the cryptographic HMAC hash.
981
982 Example: generating the sha256 HMAC of a file
983
984 ```js
985 const filename = process.argv[2];
986 const crypto = require('crypto');
987 const fs = require('fs');
988
989 const hmac = crypto.createHmac('sha256', 'a secret');
990
991 const input = fs.createReadStream(filename);
992 input.on('readable', () => {
993   var data = input.read();
994   if (data)
995     hmac.update(data);
996   else {
997     console.log(`${hmac.digest('hex')} ${filename}`);
998   }
999 });
1000 ```
1001
1002 ### crypto.createSign(algorithm)
1003
1004 Creates and returns a `Sign` object that uses the given `algorithm`. On
1005 recent OpenSSL releases, `openssl list-public-key-algorithms` will
1006 display the available signing algorithms. One example is `'RSA-SHA256'`.
1007
1008 ### crypto.createVerify(algorithm)
1009
1010 Creates and returns a `Verify` object that uses the given algorithm. On
1011 recent OpenSSL releases, `openssl list-public-key-algorithms` will
1012 display the available signing algorithms. One example is `'RSA-SHA256'`.
1013
1014 ### crypto.getCiphers()
1015
1016 Returns an array with the names of the supported cipher algorithms.
1017
1018 Example:
1019
1020 ```js
1021 const ciphers = crypto.getCiphers();
1022 console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]
1023 ```
1024
1025 ### crypto.getCurves()
1026
1027 Returns an array with the names of the supported elliptic curves.
1028
1029 Example:
1030
1031 ```js
1032 const curves = crypto.getCurves();
1033 console.log(curves); // ['secp256k1', 'secp384r1', ...]
1034 ```
1035
1036 ### crypto.getDiffieHellman(group_name)
1037
1038 Creates a predefined `DiffieHellman` key exchange object.  The
1039 supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in
1040 [RFC 2412][], but see [Caveats][]) and `'modp14'`, `'modp15'`,
1041 `'modp16'`, `'modp17'`, `'modp18'` (defined in [RFC 3526][]). The
1042 returned object mimics the interface of objects created by
1043 [`crypto.createDiffieHellman()`][], but will not allow changing
1044 the keys (with [`diffieHellman.setPublicKey()`][] for example). The
1045 advantage of using this method is that the parties do not have to
1046 generate nor exchange a group modulus beforehand, saving both processor
1047 and communication time.
1048
1049 Example (obtaining a shared secret):
1050
1051 ```js
1052 const crypto = require('crypto');
1053 const alice = crypto.getDiffieHellman('modp14');
1054 const bob = crypto.getDiffieHellman('modp14');
1055
1056 alice.generateKeys();
1057 bob.generateKeys();
1058
1059 const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
1060 const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
1061
1062 /* alice_secret and bob_secret should be the same */
1063 console.log(alice_secret == bob_secret);
1064 ```
1065
1066 ### crypto.getHashes()
1067
1068 Returns an array with the names of the supported hash algorithms.
1069
1070 Example:
1071
1072 ```js
1073 const hashes = crypto.getHashes();
1074 console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]
1075 ```
1076
1077 ### crypto.pbkdf2(password, salt, iterations, keylen[, digest], callback)
1078
1079 Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)
1080 implementation.  A selected HMAC digest algorithm specified by `digest` is
1081 applied to derive a key of the requested byte length (`keylen`) from the
1082 `password`, `salt` and `iterations`. If the `digest` algorithm is not specified,
1083 a default of `'sha1'` is used.
1084
1085 The supplied `callback` function is called with two arguments: `err` and
1086 `derivedKey`. If an error occurs, `err` will be set; otherwise `err` will be
1087 null. The successfully generated `derivedKey` will be passed as a [`Buffer`][].
1088
1089 The `iterations` argument must be a number set as high as possible. The
1090 higher the number of iterations, the more secure the derived key will be,
1091 but will take a longer amount of time to complete.
1092
1093 The `salt` should also be as unique as possible. It is recommended that the
1094 salts are random and their lengths are greater than 16 bytes. See
1095 [NIST SP 800-132][] for details.
1096
1097 Example:
1098
1099 ```js
1100 const crypto = require('crypto');
1101 crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, key) => {
1102   if (err) throw err;
1103   console.log(key.toString('hex'));  // 'c5e478d...1469e50'
1104 });
1105 ```
1106
1107 An array of supported digest functions can be retrieved using
1108 [`crypto.getHashes()`][].
1109
1110 ### crypto.pbkdf2Sync(password, salt, iterations, keylen[, digest])
1111
1112 Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)
1113 implementation.  A selected HMAC digest algorithm specified by `digest` is
1114 applied to derive a key of the requested byte length (`keylen`) from the
1115 `password`, `salt` and `iterations`. If the `digest` algorithm is not specified,
1116 a default of `'sha1'` is used.
1117
1118 If an error occurs an Error will be thrown, otherwise the derived key will be
1119 returned as a [`Buffer`][].
1120
1121 The `iterations` argument must be a number set as high as possible. The
1122 higher the number of iterations, the more secure the derived key will be,
1123 but will take a longer amount of time to complete.
1124
1125 The `salt` should also be as unique as possible. It is recommended that the
1126 salts are random and their lengths are greater than 16 bytes. See
1127 [NIST SP 800-132][] for details.
1128
1129 Example:
1130
1131 ```js
1132 const crypto = require('crypto');
1133 const key = crypto.pbkdf2sync('secret', 'salt', 100000, 512, 'sha512');
1134 console.log(key.toString('hex'));  // 'c5e478d...1469e50'
1135 ```
1136
1137 An array of supported digest functions can be retrieved using
1138 [`crypto.getHashes()`][].
1139
1140 ### crypto.privateDecrypt(private_key, buffer)
1141
1142 Decrypts `buffer` with `private_key`.
1143
1144 `private_key` can be an object or a string. If `private_key` is a string, it is
1145 treated as the key with no passphrase and will use `RSA_PKCS1_OAEP_PADDING`.
1146 If `private_key` is an object, it is interpreted as a hash object with the
1147 keys:
1148
1149 * `key` : {String} - PEM encoded private key
1150 * `passphrase` : {String} - Optional passphrase for the private key
1151 * `padding` : An optional padding value, one of the following:
1152   * `constants.RSA_NO_PADDING`
1153   * `constants.RSA_PKCS1_PADDING`
1154   * `constants.RSA_PKCS1_OAEP_PADDING`
1155
1156 All paddings are defined in the `constants` module.
1157
1158 ### crypto.privateEncrypt(private_key, buffer)
1159
1160 Encrypts `buffer` with `private_key`.
1161
1162 `private_key` can be an object or a string. If `private_key` is a string, it is
1163 treated as the key with no passphrase and will use `RSA_PKCS1_PADDING`.
1164 If `private_key` is an object, it is interpreted as a hash object with the
1165 keys:
1166
1167 * `key` : {String} - PEM encoded private key
1168 * `passphrase` : {String} - Optional passphrase for the private key
1169 * `padding` : An optional padding value, one of the following:
1170   * `constants.RSA_NO_PADDING`
1171   * `constants.RSA_PKCS1_PADDING`
1172   * `constants.RSA_PKCS1_OAEP_PADDING`
1173
1174 All paddings are defined in the `constants` module.
1175
1176 ### crypto.publicDecrypt(public_key, buffer)
1177
1178 Decrypts `buffer` with `public_key`.
1179
1180 `public_key` can be an object or a string. If `public_key` is a string, it is
1181 treated as the key with no passphrase and will use `RSA_PKCS1_PADDING`.
1182 If `public_key` is an object, it is interpreted as a hash object with the
1183 keys:
1184
1185 * `key` : {String} - PEM encoded public key
1186 * `passphrase` : {String} - Optional passphrase for the private key
1187 * `padding` : An optional padding value, one of the following:
1188   * `constants.RSA_NO_PADDING`
1189   * `constants.RSA_PKCS1_PADDING`
1190   * `constants.RSA_PKCS1_OAEP_PADDING`
1191
1192 Because RSA public keys can be derived from private keys, a private key may
1193 be passed instead of a public key.
1194
1195 All paddings are defined in the `constants` module.
1196
1197 ### crypto.publicEncrypt(public_key, buffer)
1198
1199 Encrypts `buffer` with `public_key`.
1200
1201 `public_key` can be an object or a string. If `public_key` is a string, it is
1202 treated as the key with no passphrase and will use `RSA_PKCS1_OAEP_PADDING`.
1203 If `public_key` is an object, it is interpreted as a hash object with the
1204 keys:
1205
1206 * `key` : {String} - PEM encoded public key
1207 * `passphrase` : {String} - Optional passphrase for the private key
1208 * `padding` : An optional padding value, one of the following:
1209   * `constants.RSA_NO_PADDING`
1210   * `constants.RSA_PKCS1_PADDING`
1211   * `constants.RSA_PKCS1_OAEP_PADDING`
1212
1213 Because RSA public keys can be derived from private keys, a private key may
1214 be passed instead of a public key.
1215
1216 All paddings are defined in the `constants` module.
1217
1218 ### crypto.randomBytes(size[, callback])
1219
1220 Generates cryptographically strong pseudo-random data. The `size` argument
1221 is a number indicating the number of bytes to generate.
1222
1223 If a `callback` function is provided, the bytes are generated asynchronously
1224 and the `callback` function is invoked with two arguments: `err` and `buf`.
1225 If an error occurs, `err` will be an Error object; otherwise it is null. The
1226 `buf` argument is a [`Buffer`][] containing the generated bytes.
1227
1228 ```js
1229 // Asynchronous
1230 const crypto = require('crypto');
1231 crypto.randomBytes(256, (err, buf) => {
1232   if (err) throw err;
1233   console.log(
1234     `${buf.length}` bytes of random data: ${buf.toString('hex')});
1235 });
1236 ```
1237
1238 If the `callback` function is not provided, the random bytes are generated
1239 synchronously and returned as a [`Buffer`][]. An error will be thrown if
1240 there is a problem generating the bytes.
1241
1242 ```js
1243 // Synchronous
1244 const buf = crypto.randomBytes(256);
1245 console.log(
1246   `${buf.length}` bytes of random data: ${buf.toString('hex')});
1247 ```
1248
1249 The `crypto.randomBytes()` method will block until there is sufficient entropy.
1250 This should normally never take longer than a few milliseconds. The only time
1251 when generating the random bytes may conceivably block for a longer period of
1252 time is right after boot, when the whole system is still low on entropy.
1253
1254 ### crypto.setEngine(engine[, flags])
1255
1256 Load and set the `engine` for some or all OpenSSL functions (selected by flags).
1257
1258 `engine` could be either an id or a path to the engine's shared library.
1259
1260 The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags`
1261 is a bit field taking one of or a mix of the following flags (defined in the
1262 `constants` module):
1263
1264 * `ENGINE_METHOD_RSA`
1265 * `ENGINE_METHOD_DSA`
1266 * `ENGINE_METHOD_DH`
1267 * `ENGINE_METHOD_RAND`
1268 * `ENGINE_METHOD_ECDH`
1269 * `ENGINE_METHOD_ECDSA`
1270 * `ENGINE_METHOD_CIPHERS`
1271 * `ENGINE_METHOD_DIGESTS`
1272 * `ENGINE_METHOD_STORE`
1273 * `ENGINE_METHOD_PKEY_METH`
1274 * `ENGINE_METHOD_PKEY_ASN1_METH`
1275 * `ENGINE_METHOD_ALL`
1276 * `ENGINE_METHOD_NONE`
1277
1278 ## Notes
1279
1280 ### Legacy Streams API (pre Node.js v0.10)
1281
1282 The Crypto module was added to Node.js before there was the concept of a
1283 unified Stream API, and before there were [`Buffer`][] objects for handling
1284 binary data. As such, the many of the `crypto` defined classes have methods not
1285 typically found on other Node.js classes that implement the [streams][]
1286 API (e.g. `update()`, `final()`, or `digest()`).  Also, many methods accepted
1287 and returned `'binary'` encoded strings by default rather than Buffers.  This
1288 default was changed after Node.js v0.8 to use [`Buffer`][] objects by default
1289 instead.
1290
1291 ### Recent ECDH Changes
1292
1293 Usage of `ECDH` with non-dynamically generated key pairs has been simplified.
1294 Now, `ecdh.setPrivateKey()` can be called with a preselected private key and the
1295 associated public point (key) will be computed and stored in the object.
1296 This allows code to only store and provide the private part of the EC key pair.
1297 `ecdh.setPrivateKey()` now also validates that the private key is valid for the
1298 selected curve.
1299
1300 The `ecdh.setPublicKey()` method is now deprecated as its inclusion in the API
1301 is not useful. Either a previously stored private key should be set, which
1302 automatically generates the associated public key, or `ecdh.generateKeys()`
1303 should be called. The main drawback of using `ecdh.setPublicKey()` is that it
1304 can be used to put the ECDH key pair into an inconsistent state.
1305
1306 ### Support for weak or compromised algorithms
1307
1308 The `crypto` module still supports some algorithms which are already
1309 compromised and are not currently recommended for use. The API also allows
1310 the use of ciphers and hashes with a small key size that are considered to be
1311 too weak for safe use.
1312
1313 Users should take full responsibility for selecting the crypto
1314 algorithm and key size according to their security requirements.
1315
1316 Based on the recommendations of [NIST SP 800-131A][]:
1317
1318 - MD5 and SHA-1 are no longer acceptable where collision resistance is
1319   required such as digital signatures.
1320 - The key used with RSA, DSA and DH algorithms is recommended to have
1321   at least 2048 bits and that of the curve of ECDSA and ECDH at least
1322   224 bits, to be safe to use for several years.
1323 - The DH groups of `modp1`, `modp2` and `modp5` have a key size
1324   smaller than 2048 bits and are not recommended.
1325
1326 See the reference for other recommendations and details.
1327
1328 [HTML5's `keygen` element]: http://www.w3.org/TR/html5/forms.html#the-keygen-element
1329 [OpenSSL's SPKAC implementation]: https://www.openssl.org/docs/apps/spkac.html
1330 [`createCipher()`]: #crypto_crypto_createcipher_algorithm_password
1331 [`createCipheriv()`]: #crypto_crypto_createcipheriv_algorithm_key_iv
1332 [`createHash()`]: #crypto_crypto_createhash_algorithm
1333 [`crypto.createDecipher`]: #crypto_crypto_createdecipher_algorithm_password
1334 [`crypto.createDecipheriv`]: #crypto_crypto_createdecipheriv_algorithm_key_iv
1335 [`crypto.createDiffieHellman()`]: #crypto_crypto_creatediffiehellman_prime_prime_encoding_generator_generator_encoding
1336 [`crypto.getHashes()`]: #crypto_crypto_gethashes
1337 [`crypto.pbkdf2`]: #crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback
1338 [`decipher.update`]: #crypto_decipher_update_data_input_encoding_output_encoding
1339 [`diffieHellman.setPublicKey()`]: #crypto_diffiehellman_setpublickey_public_key_encoding
1340 [`EVP_BytesToKey`]: https://www.openssl.org/docs/crypto/EVP_BytesToKey.html
1341 [`getCurves()`]: #crypto_crypto_getcurves
1342 [`tls.createSecureContext()`]: tls.html#tls_tls_createsecurecontext_details
1343 [`Buffer`]: buffer.html
1344 [buffers]: buffer.html
1345 [Caveats]: #crypto_support_for_weak_or_compromised_algorithms
1346 [initialization vector]: https://en.wikipedia.org/wiki/Initialization_vector
1347 [NIST SP 800-131A]: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf
1348 [NIST SP 800-132]: http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
1349 [RFC 2412]: https://www.rfc-editor.org/rfc/rfc2412.txt
1350 [RFC 3526]: https://www.rfc-editor.org/rfc/rfc3526.txt
1351 [stream]: stream.html
1352 [streams]: stream.html
1353 [OpenSSL cipher list format]: https://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT
1354 [publicly trusted list of CAs]: https://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt