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