048bc077785c92f75d26fb8dd944cbc22021c30d
[platform/upstream/nodejs.git] / doc / api / crypto.markdown
1 # Crypto
2
3     Stability: 2 - Stable
4
5 Use `require('crypto')` to access this module.
6
7 The crypto module offers a way of encapsulating secure credentials to be
8 used as part of a secure HTTPS net or http connection.
9
10 It also offers a set of wrappers for OpenSSL's hash, hmac, cipher,
11 decipher, sign and verify methods.
12
13 ## Class: Certificate
14
15 The class used for working with signed public key & challenges. The most
16 common usage for this series of functions is when dealing with the `<keygen>`
17 element. http://www.openssl.org/docs/apps/spkac.html
18
19 Returned by `crypto.Certificate`.
20
21 ### Certificate.exportChallenge(spkac)
22
23 Exports the encoded challenge associated with the SPKAC.
24
25 ### Certificate.exportPublicKey(spkac)
26
27 Exports the encoded public key from the supplied SPKAC.
28
29 ### Certificate.verifySpkac(spkac)
30
31 Returns true of false based on the validity of the SPKAC.
32
33 ## Class: Cipher
34
35 Class for encrypting data.
36
37 Returned by `crypto.createCipher` and `crypto.createCipheriv`.
38
39 Cipher objects are [streams][] that are both readable and writable.
40 The written plain text data is used to produce the encrypted data on
41 the readable side. The legacy `update` and `final` methods are also
42 supported.
43
44 ### cipher.final([output_encoding])
45
46 Returns any remaining enciphered contents, with `output_encoding`
47 being one of: `'binary'`, `'base64'` or `'hex'`.  If no encoding is
48 provided, then a buffer is returned.
49
50 Note: `cipher` object can not be used after `final()` method has been
51 called.
52
53 ### cipher.getAuthTag()
54
55 For authenticated encryption modes (currently supported: GCM), this
56 method returns a `Buffer` that represents the _authentication tag_ that
57 has been computed from the given data. Should be called after
58 encryption has been completed using the `final` method!
59
60 ### cipher.setAAD(buffer)
61
62 For authenticated encryption modes (currently supported: GCM), this
63 method sets the value used for the additional authenticated data (AAD) input
64 parameter.
65
66 ### cipher.setAutoPadding(auto_padding=true)
67
68 You can disable automatic padding of the input data to block size. If
69 `auto_padding` is false, the length of the entire input data must be a
70 multiple of the cipher's block size or `final` will fail.  Useful for
71 non-standard padding, e.g. using `0x0` instead of PKCS padding. You
72 must call this before `cipher.final`.
73
74 ### cipher.update(data[, input_encoding][, output_encoding])
75
76 Updates the cipher with `data`, the encoding of which is given in
77 `input_encoding` and can be `'utf8'`, `'ascii'` or `'binary'`.  If no
78 encoding is provided, then a buffer is expected.
79 If `data` is a `Buffer` then `input_encoding` is ignored.
80
81 The `output_encoding` specifies the output format of the enciphered
82 data, and can be `'binary'`, `'base64'` or `'hex'`.  If no encoding is
83 provided, then a buffer is returned.
84
85 Returns the enciphered contents, and can be called many times with new
86 data as it is streamed.
87
88 ## Class: Decipher
89
90 Class for decrypting data.
91
92 Returned by `crypto.createDecipher` and `crypto.createDecipheriv`.
93
94 Decipher objects are [streams][] that are both readable and writable.
95 The written enciphered data is used to produce the plain-text data on
96 the the readable side. The legacy `update` and `final` methods are also
97 supported.
98
99 ### decipher.final([output_encoding])
100
101 Returns any remaining plaintext which is deciphered, with
102 `output_encoding` being one of: `'binary'`, `'ascii'` or `'utf8'`.  If
103 no encoding is provided, then a buffer is returned.
104
105 Note: `decipher` object can not be used after `final()` method has been
106 called.
107
108 ### decipher.setAAD(buffer)
109
110 For authenticated encryption modes (currently supported: GCM), this
111 method sets the value used for the additional authenticated data (AAD) input
112 parameter.
113
114 ### decipher.setAuthTag(buffer)
115
116 For authenticated encryption modes (currently supported: GCM), this
117 method must be used to pass in the received _authentication tag_.
118 If no tag is provided or if the ciphertext has been tampered with,
119 `final` will throw, thus indicating that the ciphertext should
120 be discarded due to failed authentication.
121
122 ### decipher.setAutoPadding(auto_padding=true)
123
124 You can disable auto padding if the data has been encrypted without
125 standard block padding to prevent `decipher.final` from checking and
126 removing it. This will only work if the input data's length is a multiple of
127 the ciphers block size. You must call this before streaming data to
128 `decipher.update`.
129
130 ### decipher.update(data[, input_encoding][, output_encoding])
131
132 Updates the decipher with `data`, which is encoded in `'binary'`,
133 `'base64'` or `'hex'`.  If no encoding is provided, then a buffer is
134 expected.
135 If `data` is a `Buffer` then `input_encoding` is ignored.
136
137 The `output_decoding` specifies in what format to return the
138 deciphered plaintext: `'binary'`, `'ascii'` or `'utf8'`.  If no
139 encoding is provided, then a buffer is returned.
140
141 ## Class: DiffieHellman
142
143 The class for creating Diffie-Hellman key exchanges.
144
145 Returned by `crypto.createDiffieHellman`.
146
147 ### diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding])
148
149 Computes the shared secret using `other_public_key` as the other
150 party's public key and returns the computed shared secret. Supplied
151 key is interpreted using specified `input_encoding`, and secret is
152 encoded using specified `output_encoding`. Encodings can be
153 `'binary'`, `'hex'`, or `'base64'`. If the input encoding is not
154 provided, then a buffer is expected.
155
156 If no output encoding is given, then a buffer is returned.
157
158 ### diffieHellman.generateKeys([encoding])
159
160 Generates private and public Diffie-Hellman key values, and returns
161 the public key in the specified encoding. This key should be
162 transferred to the other party. Encoding can be `'binary'`, `'hex'`,
163 or `'base64'`.  If no encoding is provided, then a buffer is returned.
164
165 ### diffieHellman.getGenerator([encoding])
166
167 Returns the Diffie-Hellman generator in the specified encoding, which can
168 be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided,
169 then a buffer is returned.
170
171 ### diffieHellman.getPrime([encoding])
172
173 Returns the Diffie-Hellman prime in the specified encoding, which can
174 be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided,
175 then a buffer is returned.
176
177 ### diffieHellman.getPrivateKey([encoding])
178
179 Returns the Diffie-Hellman private key in the specified encoding,
180 which can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is
181 provided, then a buffer is returned.
182
183 ### diffieHellman.getPublicKey([encoding])
184
185 Returns the Diffie-Hellman public key in the specified encoding, which
186 can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided,
187 then a buffer is returned.
188
189 ### diffieHellman.setPrivateKey(private_key[, encoding])
190
191 Sets the Diffie-Hellman private key. Key encoding can be `'binary'`,
192 `'hex'` or `'base64'`. If no encoding is provided, then a buffer is
193 expected.
194
195 ### diffieHellman.setPublicKey(public_key[, encoding])
196
197 Sets the Diffie-Hellman public key. Key encoding can be `'binary'`,
198 `'hex'` or `'base64'`. If no encoding is provided, then a buffer is
199 expected.
200
201 ### diffieHellman.verifyError
202
203 A bit field containing any warnings and/or errors as a result of a check performed
204 during initialization. The following values are valid for this property
205 (defined in `constants` module):
206
207 * `DH_CHECK_P_NOT_SAFE_PRIME`
208 * `DH_CHECK_P_NOT_PRIME`
209 * `DH_UNABLE_TO_CHECK_GENERATOR`
210 * `DH_NOT_SUITABLE_GENERATOR`
211
212 ## Class: ECDH
213
214 The class for creating EC Diffie-Hellman key exchanges.
215
216 Returned by `crypto.createECDH`.
217
218 ### ECDH.computeSecret(other_public_key[, input_encoding][, output_encoding])
219
220 Computes the shared secret using `other_public_key` as the other
221 party's public key and returns the computed shared secret. Supplied
222 key is interpreted using specified `input_encoding`, and secret is
223 encoded using specified `output_encoding`. Encodings can be
224 `'binary'`, `'hex'`, or `'base64'`. If the input encoding is not
225 provided, then a buffer is expected.
226
227 If no output encoding is given, then a buffer is returned.
228
229 ### ECDH.generateKeys([encoding[, format]])
230
231 Generates private and public EC Diffie-Hellman key values, and returns
232 the public key in the specified format and encoding. This key should be
233 transferred to the other party.
234
235 Format specifies point encoding and can be `'compressed'`, `'uncompressed'`, or
236 `'hybrid'`. If no format is provided - the point will be returned in
237 `'uncompressed'` format.
238
239 Encoding can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided,
240 then a buffer is returned.
241
242 ### ECDH.getPrivateKey([encoding])
243
244 Returns the EC Diffie-Hellman private key in the specified encoding,
245 which can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is
246 provided, then a buffer is returned.
247
248 ### ECDH.getPublicKey([encoding[, format]])
249
250 Returns the EC Diffie-Hellman public key in the specified encoding and format.
251
252 Format specifies point encoding and can be `'compressed'`, `'uncompressed'`, or
253 `'hybrid'`. If no format is provided - the point will be returned in
254 `'uncompressed'` format.
255
256 Encoding can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided,
257 then a buffer is returned.
258
259 ### ECDH.setPrivateKey(private_key[, encoding])
260
261 Sets the EC Diffie-Hellman private key. Key encoding can be `'binary'`,
262 `'hex'` or `'base64'`. If no encoding is provided, then a buffer is
263 expected.
264
265 Example (obtaining a shared secret):
266
267     var crypto = require('crypto');
268     var alice = crypto.createECDH('secp256k1');
269     var bob = crypto.createECDH('secp256k1');
270
271     alice.generateKeys();
272     bob.generateKeys();
273
274     var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
275     var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
276
277     /* alice_secret and bob_secret should be the same */
278     console.log(alice_secret == bob_secret);
279
280 ### ECDH.setPublicKey(public_key[, encoding])
281
282 Sets the EC Diffie-Hellman public key. Key encoding can be `'binary'`,
283 `'hex'` or `'base64'`. If no encoding is provided, then a buffer is
284 expected.
285
286 ## Class: Hash
287
288 The class for creating hash digests of data.
289
290 It is a [stream][] that is both readable and writable.  The written data
291 is used to compute the hash.  Once the writable side of the stream is ended,
292 use the `read()` method to get the computed hash digest.  The legacy `update`
293 and `digest` methods are also supported.
294
295 Returned by `crypto.createHash`.
296
297 ### hash.digest([encoding])
298
299 Calculates the digest of all of the passed data to be hashed.  The
300 `encoding` can be `'hex'`, `'binary'` or `'base64'`.  If no encoding
301 is provided, then a buffer is returned.
302
303 Note: `hash` object can not be used after `digest()` method has been
304 called.
305
306 ### hash.update(data[, input_encoding])
307
308 Updates the hash content with the given `data`, the encoding of which
309 is given in `input_encoding` and can be `'utf8'`, `'ascii'` or
310 `'binary'`.  If no encoding is provided, and the input is a string, an
311 encoding of `'binary'` is enforced. If `data` is a `Buffer` then
312 `input_encoding` is ignored.
313
314 This can be called many times with new data as it is streamed.
315
316 ## Class: Hmac
317
318 Class for creating cryptographic hmac content.
319
320 Returned by `crypto.createHmac`.
321
322 ### hmac.digest([encoding])
323
324 Calculates the digest of all of the passed data to the hmac.  The
325 `encoding` can be `'hex'`, `'binary'` or `'base64'`.  If no encoding
326 is provided, then a buffer is returned.
327
328 Note: `hmac` object can not be used after `digest()` method has been
329 called.
330
331 ### hmac.update(data)
332
333 Update the hmac content with the given `data`.  This can be called
334 many times with new data as it is streamed.
335
336 ## Class: Sign
337
338 Class for generating signatures.
339
340 Returned by `crypto.createSign`.
341
342 Sign objects are writable [streams][].  The written data is used to
343 generate the signature.  Once all of the data has been written, the
344 `sign` method will return the signature.  The legacy `update` method
345 is also supported.
346
347 ### sign.sign(private_key[, output_format])
348
349 Calculates the signature on all the updated data passed through the
350 sign.
351
352 `private_key` can be an object or a string. If `private_key` is a string, it is
353 treated as the key with no passphrase.
354
355 `private_key`:
356
357 * `key` : A string holding the PEM encoded private key
358 * `passphrase` : A string of passphrase for the private key
359
360 Returns the signature in `output_format` which can be `'binary'`,
361 `'hex'` or `'base64'`. If no encoding is provided, then a buffer is
362 returned.
363
364 Note: `sign` object can not be used after `sign()` method has been
365 called.
366
367 ### sign.update(data)
368
369 Updates the sign object with data.  This can be called many times
370 with new data as it is streamed.
371
372 ## Class: Verify
373
374 Class for verifying signatures.
375
376 Returned by `crypto.createVerify`.
377
378 Verify objects are writable [streams][].  The written data is used to
379 validate against the supplied signature.  Once all of the data has been
380 written, the `verify` method will return true if the supplied signature
381 is valid.  The legacy `update` method is also supported.
382
383 ### verifier.update(data)
384
385 Updates the verifier object with data.  This can be called many times
386 with new data as it is streamed.
387
388 ### verifier.verify(object, signature[, signature_format])
389
390 Verifies the signed data by using the `object` and `signature`.
391 `object` is  a string containing a PEM encoded object, which can be
392 one of RSA public key, DSA public key, or X.509 certificate.
393 `signature` is the previously calculated signature for the data, in
394 the `signature_format` which can be `'binary'`, `'hex'` or `'base64'`.
395 If no encoding is specified, then a buffer is expected.
396
397 Returns true or false depending on the validity of the signature for
398 the data and public key.
399
400 Note: `verifier` object can not be used after `verify()` method has been
401 called.
402
403 ## crypto.DEFAULT_ENCODING
404
405 The default encoding to use for functions that can take either strings
406 or buffers.  The default value is `'buffer'`, which makes it default
407 to using Buffer objects.  This is here to make the crypto module more
408 easily compatible with legacy programs that expected `'binary'` to be
409 the default encoding.
410
411 Note that new programs will probably expect buffers, so only use this
412 as a temporary measure.
413
414 ## crypto.createCipher(algorithm, password)
415
416 Creates and returns a cipher object, with the given algorithm and
417 password.
418
419 `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc.  On
420 recent releases, `openssl list-cipher-algorithms` will display the
421 available cipher algorithms.  `password` is used to derive key and IV,
422 which must be a `'binary'` encoded string or a [buffer][].
423
424 It is a [stream][] that is both readable and writable.  The written data
425 is used to compute the hash.  Once the writable side of the stream is ended,
426 use the `read()` method to get the enciphered contents.  The legacy `update`
427 and `final` methods are also supported.
428
429 Note: `createCipher` derives keys with the OpenSSL function [EVP_BytesToKey][]
430 with the digest algorithm set to MD5, one iteration, and no salt. The lack of
431 salt allows dictionary attacks as the same password always creates the same key.
432 The low iteration count and non-cryptographically secure hash algorithm allow
433 passwords to be tested very rapidly.
434
435 In line with OpenSSL's recommendation to use pbkdf2 instead of EVP_BytesToKey it
436 is recommended you derive a key and iv yourself with [crypto.pbkdf2][] and to
437 then use [createCipheriv()][] to create the cipher stream.
438
439 ## crypto.createCipheriv(algorithm, key, iv)
440
441 Creates and returns a cipher object, with the given algorithm, key and
442 iv.
443
444 `algorithm` is the same as the argument to `createCipher()`.  `key` is
445 the raw key used by the algorithm.  `iv` is an [initialization vector][].
446
447 `key` and `iv` must be `'binary'` encoded strings or [buffers][].
448
449 ## crypto.createCredentials(details)
450
451     Stability: 0 - Deprecated: Use [tls.createSecureContext][] instead.
452
453 Creates a credentials object, with the optional details being a
454 dictionary with keys:
455
456 * `pfx` : A string or buffer holding the PFX or PKCS12 encoded private
457   key, certificate and CA certificates
458 * `key` : A string holding the PEM encoded private key
459 * `passphrase` : A string of passphrase for the private key or pfx
460 * `cert` : A string holding the PEM encoded certificate
461 * `ca` : Either a string or list of strings of PEM encoded CA
462   certificates to trust.
463 * `crl` : Either a string or list of strings of PEM encoded CRLs
464   (Certificate Revocation List)
465 * `ciphers`: A string describing the ciphers to use or exclude.
466   Consult
467   <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>
468   for details on the format.
469
470 If no 'ca' details are given, then Node.js will use the default
471 publicly trusted list of CAs as given in
472 <http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt>.
473
474 ## crypto.createDecipher(algorithm, password)
475
476 Creates and returns a decipher object, with the given algorithm and
477 key.  This is the mirror of the [createCipher()][] above.
478
479 ## crypto.createDecipheriv(algorithm, key, iv)
480
481 Creates and returns a decipher object, with the given algorithm, key
482 and iv.  This is the mirror of the [createCipheriv()][] above.
483
484 ## crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding])
485
486 Creates a Diffie-Hellman key exchange object using the supplied `prime` and an
487 optional specific `generator`.
488 `generator` can be a number, string, or Buffer.
489 If no `generator` is specified, then `2` is used.
490 `prime_encoding` and `generator_encoding` can be `'binary'`, `'hex'`, or `'base64'`.
491 If no `prime_encoding` is specified, then a Buffer is expected for `prime`.
492 If no `generator_encoding` is specified, then a Buffer is expected for `generator`.
493
494 ## crypto.createDiffieHellman(prime_length[, generator])
495
496 Creates a Diffie-Hellman key exchange object and generates a prime of
497 `prime_length` bits and using an optional specific numeric `generator`.
498 If no `generator` is specified, then `2` is used.
499
500 ## crypto.createECDH(curve_name)
501
502 Creates an Elliptic Curve (EC) Diffie-Hellman key exchange object using a
503 predefined curve specified by the `curve_name` string. Use [getCurves()][] to
504 obtain a list of available curve names. On recent releases,
505 `openssl ecparam -list_curves` will also display the name and description of
506 each available elliptic curve.
507
508 ## crypto.createHash(algorithm)
509
510 Creates and returns a hash object, a cryptographic hash with the given
511 algorithm which can be used to generate hash digests.
512
513 `algorithm` is dependent on the available algorithms supported by the
514 version of OpenSSL on the platform. Examples are `'sha256'`,
515 `'sha512'`, etc.  On recent releases, `openssl
516 list-message-digest-algorithms` will display the available digest
517 algorithms.
518
519 Example: this program that takes the sha256 sum of a file
520
521     var filename = process.argv[2];
522     var crypto = require('crypto');
523     var fs = require('fs');
524
525     var shasum = crypto.createHash('sha256');
526
527     var s = fs.ReadStream(filename);
528     s.on('data', function(d) {
529       shasum.update(d);
530     });
531
532     s.on('end', function() {
533       var d = shasum.digest('hex');
534       console.log(d + '  ' + filename);
535     });
536
537 ## crypto.createHmac(algorithm, key)
538
539 Creates and returns a hmac object, a cryptographic hmac with the given
540 algorithm and key.
541
542 It is a [stream][] that is both readable and writable.  The written
543 data is used to compute the hmac.  Once the writable side of the
544 stream is ended, use the `read()` method to get the computed digest.
545 The legacy `update` and `digest` methods are also supported.
546
547 `algorithm` is dependent on the available algorithms supported by
548 OpenSSL - see createHash above.  `key` is the hmac key to be used.
549
550 ## crypto.createSign(algorithm)
551
552 Creates and returns a signing object, with the given algorithm.  On
553 recent OpenSSL releases, `openssl list-public-key-algorithms` will
554 display the available signing algorithms. Examples are `'RSA-SHA256'`.
555
556 ## crypto.createVerify(algorithm)
557
558 Creates and returns a verification object, with the given algorithm.
559 This is the mirror of the signing object above.
560
561 ## crypto.getCiphers()
562
563 Returns an array with the names of the supported ciphers.
564
565 Example:
566
567     var ciphers = crypto.getCiphers();
568     console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]
569
570 ## crypto.getCurves()
571
572 Returns an array with the names of the supported elliptic curves.
573
574 Example:
575
576     var curves = crypto.getCurves();
577     console.log(curves); // ['secp256k1', 'secp384r1', ...]
578
579 ## crypto.getDiffieHellman(group_name)
580
581 Creates a predefined Diffie-Hellman key exchange object.  The
582 supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in
583 [RFC 2412][], but see [Caveats][]) and `'modp14'`, `'modp15'`,
584 `'modp16'`, `'modp17'`, `'modp18'` (defined in [RFC 3526][]).  The
585 returned object mimics the interface of objects created by
586 [crypto.createDiffieHellman()][] above, but will not allow changing
587 the keys (with [diffieHellman.setPublicKey()][] for example). The
588 advantage of using this routine is that the parties do not have to
589 generate nor exchange group modulus beforehand, saving both processor
590 and communication time.
591
592 Example (obtaining a shared secret):
593
594     var crypto = require('crypto');
595     var alice = crypto.getDiffieHellman('modp14');
596     var bob = crypto.getDiffieHellman('modp14');
597
598     alice.generateKeys();
599     bob.generateKeys();
600
601     var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
602     var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
603
604     /* alice_secret and bob_secret should be the same */
605     console.log(alice_secret == bob_secret);
606
607 ## crypto.getHashes()
608
609 Returns an array with the names of the supported hash algorithms.
610
611 Example:
612
613     var hashes = crypto.getHashes();
614     console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]
615
616 ## crypto.pbkdf2(password, salt, iterations, keylen[, digest], callback)
617
618 Asynchronous PBKDF2 function.  Applies the selected HMAC digest function
619 (default: SHA1) to derive a key of the requested byte length from the password,
620 salt and number of iterations.  The callback gets two arguments:
621 `(err, derivedKey)`.
622
623 Example:
624
625     crypto.pbkdf2('secret', 'salt', 4096, 64, 'sha256', function(err, key) {
626       if (err)
627         throw err;
628       console.log(key.toString('hex'));  // 'c5e478d...1469e50'
629     });
630
631 You can get a list of supported digest functions with [crypto.getHashes()][].
632
633 ## crypto.pbkdf2Sync(password, salt, iterations, keylen[, digest])
634
635 Synchronous PBKDF2 function.  Returns derivedKey or throws error.
636
637 ## crypto.privateDecrypt(private_key, buffer)
638
639 Decrypts `buffer` with `private_key`.
640
641 `private_key` can be an object or a string. If `private_key` is a string, it is
642 treated as the key with no passphrase and will use `RSA_PKCS1_OAEP_PADDING`.
643
644 `private_key`:
645
646 * `key` : A string holding the PEM encoded private key
647 * `passphrase` : An optional string of passphrase for the private key
648 * `padding` : An optional padding value, one of the following:
649   * `constants.RSA_NO_PADDING`
650   * `constants.RSA_PKCS1_PADDING`
651   * `constants.RSA_PKCS1_OAEP_PADDING`
652
653 NOTE: All paddings are defined in `constants` module.
654
655 ## crypto.privateEncrypt(private_key, buffer)
656
657 See above for details. Has the same API as `crypto.privateDecrypt`.
658 Default padding is `RSA_PKCS1_PADDING`.
659
660 ## crypto.publicDecrypt(public_key, buffer)
661
662 See above for details. Has the same API as `crypto.publicEncrypt`. Default
663 padding is `RSA_PKCS1_PADDING`.
664
665 ## crypto.publicEncrypt(public_key, buffer)
666
667 Encrypts `buffer` with `public_key`. Only RSA is currently supported.
668
669 `public_key` can be an object or a string. If `public_key` is a string, it is
670 treated as the key with no passphrase and will use `RSA_PKCS1_OAEP_PADDING`.
671 Since RSA public keys may be derived from private keys you may pass a private
672 key to this method.
673
674 `public_key`:
675
676 * `key` : A string holding the PEM encoded private key
677 * `passphrase` : An optional string of passphrase for the private key
678 * `padding` : An optional padding value, one of the following:
679   * `constants.RSA_NO_PADDING`
680   * `constants.RSA_PKCS1_PADDING`
681   * `constants.RSA_PKCS1_OAEP_PADDING`
682
683 NOTE: All paddings are defined in `constants` module.
684
685 ## crypto.randomBytes(size[, callback])
686
687 Generates cryptographically strong pseudo-random data. Usage:
688
689     // async
690     crypto.randomBytes(256, function(ex, buf) {
691       if (ex) throw ex;
692       console.log('Have %d bytes of random data: %s', buf.length, buf);
693     });
694
695     // sync
696     const buf = crypto.randomBytes(256);
697     console.log('Have %d bytes of random data: %s', buf.length, buf);
698
699 NOTE: This will block if there is insufficient entropy, although it should
700 normally never take longer than a few milliseconds. The only time when this
701 may conceivably block is right after boot, when the whole system is still
702 low on entropy.
703
704 ## crypto.setEngine(engine[, flags])
705
706 Load and set engine for some/all OpenSSL functions (selected by flags).
707
708 `engine` could be either an id or a path to the engine's shared library.
709
710 `flags` is optional and has `ENGINE_METHOD_ALL` value by default. It could take
711 one of or mix of following flags (defined in `constants` module):
712
713 * `ENGINE_METHOD_RSA`
714 * `ENGINE_METHOD_DSA`
715 * `ENGINE_METHOD_DH`
716 * `ENGINE_METHOD_RAND`
717 * `ENGINE_METHOD_ECDH`
718 * `ENGINE_METHOD_ECDSA`
719 * `ENGINE_METHOD_CIPHERS`
720 * `ENGINE_METHOD_DIGESTS`
721 * `ENGINE_METHOD_STORE`
722 * `ENGINE_METHOD_PKEY_METH`
723 * `ENGINE_METHOD_PKEY_ASN1_METH`
724 * `ENGINE_METHOD_ALL`
725 * `ENGINE_METHOD_NONE`
726
727 ## Recent API Changes
728
729 The Crypto module was added to Node.js before there was the concept of a
730 unified Stream API, and before there were Buffer objects for handling
731 binary data.
732
733 As such, the streaming classes don't have the typical methods found on
734 other Node.js classes, and many methods accepted and returned
735 Binary-encoded strings by default rather than Buffers.  This was
736 changed to use Buffers by default instead.
737
738 This is a breaking change for some use cases, but not all.
739
740 For example, if you currently use the default arguments to the Sign
741 class, and then pass the results to the Verify class, without ever
742 inspecting the data, then it will continue to work as before.  Where
743 you once got a binary string and then presented the binary string to
744 the Verify object, you'll now get a Buffer, and present the Buffer to
745 the Verify object.
746
747 However, if you were doing things with the string data that will not
748 work properly on Buffers (such as, concatenating them, storing in
749 databases, etc.), or you are passing binary strings to the crypto
750 functions without an encoding argument, then you will need to start
751 providing encoding arguments to specify which encoding you'd like to
752 use.  To switch to the previous style of using binary strings by
753 default, set the `crypto.DEFAULT_ENCODING` field to 'binary'.  Note
754 that new programs will probably expect buffers, so only use this as a
755 temporary measure.
756
757 ## Caveats
758
759 The crypto module still supports some algorithms which are already
760 compromised. And the API also allows the use of ciphers and hashes
761 with a small key size that are considered to be too weak for safe use.
762
763 Users should take full responsibility for selecting the crypto
764 algorithm and key size according to their security requirements.
765
766 Based on the recommendations of [NIST SP 800-131A]:
767
768 - MD5 and SHA-1 are no longer acceptable where collision resistance is
769   required such as digital signatures.
770 - The key used with RSA, DSA and DH algorithms is recommended to have
771   at least 2048 bits and that of the curve of ECDSA and ECDH at least
772   224 bits, to be safe to use for several years.
773 - The DH groups of `modp1`, `modp2` and `modp5` have a key size
774   smaller than 2048 bits and are not recommended.
775
776 See the reference for other recommendations and details.
777
778 [stream]: stream.html
779 [streams]: stream.html
780 [buffer]: buffer.html
781 [buffers]: buffer.html
782 [createCipher()]: #crypto_crypto_createcipher_algorithm_password
783 [createCipheriv()]: #crypto_crypto_createcipheriv_algorithm_key_iv
784 [getCurves()]: #crypto_crypto_getcurves
785 [crypto.createDiffieHellman()]: #crypto_crypto_creatediffiehellman_prime_prime_encoding_generator_generator_encoding
786 [tls.createSecureContext]: tls.html#tls_tls_createsecurecontext_details
787 [diffieHellman.setPublicKey()]: #crypto_diffiehellman_setpublickey_public_key_encoding
788 [RFC 2412]: http://www.rfc-editor.org/rfc/rfc2412.txt
789 [RFC 3526]: http://www.rfc-editor.org/rfc/rfc3526.txt
790 [crypto.pbkdf2]: #crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback
791 [EVP_BytesToKey]: https://www.openssl.org/docs/crypto/EVP_BytesToKey.html
792 [NIST SP 800-131A]: http://csrc.nist.gov/publications/nistpubs/800-131A/sp800-131A.pdf
793 [initialization vector]: http://en.wikipedia.org/wiki/Initialization_vector
794 [Caveats]: #crypto_caveats
795 [crypto.getHashes()]: #crypto_crypto_gethashes