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