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