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