Merge remote-tracking branch 'ry/v0.8'
[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); // ['AES128-SHA', 'AES256-SHA', ...]
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 Returned by `crypto.createHash`.
93
94 ### hash.update(data, [input_encoding])
95
96 Updates the hash content with the given `data`, the encoding of which
97 is given in `input_encoding` and can be `'utf8'`, `'ascii'` or
98 `'binary'`.  If no encoding is provided, then a buffer is expected.
99
100 This can be called many times with new data as it is streamed.
101
102 ### hash.digest([encoding])
103
104 Calculates the digest of all of the passed data to be hashed.  The
105 `encoding` can be `'hex'`, `'binary'` or `'base64'`.  If no encoding
106 is provided, then a buffer is returned.
107
108 Note: `hash` object can not be used after `digest()` method been
109 called.
110
111
112 ## crypto.createHmac(algorithm, key)
113
114 Creates and returns a hmac object, a cryptographic hmac with the given
115 algorithm and key.
116
117 `algorithm` is dependent on the available algorithms supported by
118 OpenSSL - see createHash above.  `key` is the hmac key to be used.
119
120 ## Class: Hmac
121
122 Class for creating cryptographic hmac content.
123
124 Returned by `crypto.createHmac`.
125
126 ### hmac.update(data)
127
128 Update the hmac content with the given `data`.  This can be called
129 many times with new data as it is streamed.
130
131 ### hmac.digest([encoding])
132
133 Calculates the digest of all of the passed data to the hmac.  The
134 `encoding` can be `'hex'`, `'binary'` or `'base64'`.  If no encoding
135 is provided, then a buffer is returned.
136
137 Note: `hmac` object can not be used after `digest()` method been
138 called.
139
140
141 ## crypto.createCipher(algorithm, password)
142
143 Creates and returns a cipher object, with the given algorithm and
144 password.
145
146 `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc.  On
147 recent releases, `openssl list-cipher-algorithms` will display the
148 available cipher algorithms.  `password` is used to derive key and IV,
149 which must be a `'binary'` encoded string or a [buffer](buffer.html).
150
151 ## crypto.createCipheriv(algorithm, key, iv)
152
153 Creates and returns a cipher object, with the given algorithm, key and
154 iv.
155
156 `algorithm` is the same as the argument to `createCipher()`.  `key` is
157 the raw key used by the algorithm.  `iv` is an [initialization
158 vector](http://en.wikipedia.org/wiki/Initialization_vector).
159
160 `key` and `iv` must be `'binary'` encoded strings or
161 [buffers](buffer.html).
162
163 ## Class: Cipher
164
165 Class for encrypting data.
166
167 Returned by `crypto.createCipher` and `crypto.createCipheriv`.
168
169 ### cipher.update(data, [input_encoding], [output_encoding])
170
171 Updates the cipher with `data`, the encoding of which is given in
172 `input_encoding` and can be `'utf8'`, `'ascii'` or `'binary'`.  If no
173 encoding is provided, then a buffer is expected.
174
175 The `output_encoding` specifies the output format of the enciphered
176 data, and can be `'binary'`, `'base64'` or `'hex'`.  If no encoding is
177 provided, then a buffer iis returned.
178
179 Returns the enciphered contents, and can be called many times with new
180 data as it is streamed.
181
182 ### cipher.final([output_encoding])
183
184 Returns any remaining enciphered contents, with `output_encoding`
185 being one of: `'binary'`, `'base64'` or `'hex'`.  If no encoding is
186 provided, then a buffer is returned.
187
188 Note: `cipher` object can not be used after `final()` method been
189 called.
190
191 ### cipher.setAutoPadding(auto_padding=true)
192
193 You can disable automatic padding of the input data to block size. If
194 `auto_padding` is false, the length of the entire input data must be a
195 multiple of the cipher's block size or `final` will fail.  Useful for
196 non-standard padding, e.g. using `0x0` instead of PKCS padding. You
197 must call this before `cipher.final`.
198
199
200 ## crypto.createDecipher(algorithm, password)
201
202 Creates and returns a decipher object, with the given algorithm and
203 key.  This is the mirror of the [createCipher()][] above.
204
205 ## crypto.createDecipheriv(algorithm, key, iv)
206
207 Creates and returns a decipher object, with the given algorithm, key
208 and iv.  This is the mirror of the [createCipheriv()][] above.
209
210 ## Class: Decipher
211
212 Class for decrypting data.
213
214 Returned by `crypto.createDecipher` and `crypto.createDecipheriv`.
215
216 ### decipher.update(data, [input_encoding], [output_encoding])
217
218 Updates the decipher with `data`, which is encoded in `'binary'`,
219 `'base64'` or `'hex'`.  If no encoding is provided, then a buffer is
220 expected.
221
222 The `output_decoding` specifies in what format to return the
223 deciphered plaintext: `'binary'`, `'ascii'` or `'utf8'`.  If no
224 encoding is provided, then a buffer is returned.
225
226 ### decipher.final([output_encoding])
227
228 Returns any remaining plaintext which is deciphered, with
229 `output_encoding` being one of: `'binary'`, `'ascii'` or `'utf8'`.  If
230 no encoding is provided, then a buffer is returned.
231
232 Note: `decipher` object can not be used after `final()` method been
233 called.
234
235 ### decipher.setAutoPadding(auto_padding=true)
236
237 You can disable auto padding if the data has been encrypted without
238 standard block padding to prevent `decipher.final` from checking and
239 removing it. Can only work if the input data's length is a multiple of
240 the ciphers block size. You must call this before streaming data to
241 `decipher.update`.
242
243 ## crypto.createSign(algorithm)
244
245 Creates and returns a signing object, with the given algorithm.  On
246 recent OpenSSL releases, `openssl list-public-key-algorithms` will
247 display the available signing algorithms. Examples are `'RSA-SHA256'`.
248
249 ## Class: Signer
250
251 Class for generating signatures.
252
253 Returned by `crypto.createSign`.
254
255 ### signer.update(data)
256
257 Updates the signer object with data.  This can be called many times
258 with new data as it is streamed.
259
260 ### signer.sign(private_key, [output_format])
261
262 Calculates the signature on all the updated data passed through the
263 signer.  `private_key` is a string containing the PEM encoded private
264 key for signing.
265
266 Returns the signature in `output_format` which can be `'binary'`,
267 `'hex'` or `'base64'`. If no encoding is provided, then a buffer is
268 returned.
269
270 Note: `signer` object can not be used after `sign()` method been
271 called.
272
273 ## crypto.createVerify(algorithm)
274
275 Creates and returns a verification object, with the given algorithm.
276 This is the mirror of the signing object above.
277
278 ## Class: Verify
279
280 Class for verifying signatures.
281
282 Returned by `crypto.createVerify`.
283
284 ### verifier.update(data)
285
286 Updates the verifier object with data.  This can be called many times
287 with new data as it is streamed.
288
289 ### verifier.verify(object, signature, [signature_format])
290
291 Verifies the signed data by using the `object` and `signature`.
292 `object` is  a string containing a PEM encoded object, which can be
293 one of RSA public key, DSA public key, or X.509 certificate.
294 `signature` is the previously calculated signature for the data, in
295 the `signature_format` which can be `'binary'`, `'hex'` or `'base64'`.
296 If no encoding is specified, then a buffer is expected.
297
298 Returns true or false depending on the validity of the signature for
299 the data and public key.
300
301 Note: `verifier` object can not be used after `verify()` method been
302 called.
303
304 ## crypto.createDiffieHellman(prime_length)
305
306 Creates a Diffie-Hellman key exchange object and generates a prime of
307 the given bit length. The generator used is `2`.
308
309 ## crypto.createDiffieHellman(prime, [encoding])
310
311 Creates a Diffie-Hellman key exchange object using the supplied prime.
312 The generator used is `2`. Encoding can be `'binary'`, `'hex'`, or
313 `'base64'`.  If no encoding is specified, then a buffer is expected.
314
315 ## Class: DiffieHellman
316
317 The class for creating Diffie-Hellman key exchanges.
318
319 Returned by `crypto.createDiffieHellman`.
320
321 ### diffieHellman.generateKeys([encoding])
322
323 Generates private and public Diffie-Hellman key values, and returns
324 the public key in the specified encoding. This key should be
325 transferred to the other party. Encoding can be `'binary'`, `'hex'`,
326 or `'base64'`.  If no encoding is provided, then a buffer is returned.
327
328 ### diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])
329
330 Computes the shared secret using `other_public_key` as the other
331 party's public key and returns the computed shared secret. Supplied
332 key is interpreted using specified `input_encoding`, and secret is
333 encoded using specified `output_encoding`. Encodings can be
334 `'binary'`, `'hex'`, or `'base64'`. If the input encoding is not
335 provided, then a buffer is expected.
336
337 If no output encoding is given, then a buffer is returned.
338
339 ### diffieHellman.getPrime([encoding])
340
341 Returns the Diffie-Hellman prime in the specified encoding, which can
342 be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided,
343 then a buffer is returned.
344
345 ### diffieHellman.getGenerator([encoding])
346
347 Returns the Diffie-Hellman prime in the specified encoding, which can
348 be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided,
349 then a buffer is returned.
350
351 ### diffieHellman.getPublicKey([encoding])
352
353 Returns the Diffie-Hellman public key in the specified encoding, which
354 can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided,
355 then a buffer is returned.
356
357 ### diffieHellman.getPrivateKey([encoding])
358
359 Returns the Diffie-Hellman private key in the specified encoding,
360 which can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is
361 provided, then a buffer is returned.
362
363 ### diffieHellman.setPublicKey(public_key, [encoding])
364
365 Sets the Diffie-Hellman public key. Key encoding can be `'binary'`,
366 `'hex'` or `'base64'`. If no encoding is provided, then a buffer is
367 expected.
368
369 ### diffieHellman.setPrivateKey(public_key, [encoding])
370
371 Sets the Diffie-Hellman private key. Key encoding can be `'binary'`,
372 `'hex'` or `'base64'`. If no encoding is provided, then a buffer is
373 expected.
374
375 ## crypto.getDiffieHellman(group_name)
376
377 Creates a predefined Diffie-Hellman key exchange object.  The
378 supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC
379 2412][]) and `'modp14'`, `'modp15'`, `'modp16'`, `'modp17'`,
380 `'modp18'` (defined in [RFC 3526][]).  The returned object mimics the
381 interface of objects created by [crypto.createDiffieHellman()][]
382 above, but will not allow to change the keys (with
383 [diffieHellman.setPublicKey()][] for example).  The advantage of using
384 this routine is that the parties don't have to generate nor exchange
385 group modulus beforehand, saving both processor and communication
386 time.
387
388 Example (obtaining a shared secret):
389
390     var crypto = require('crypto');
391     var alice = crypto.getDiffieHellman('modp5');
392     var bob = crypto.getDiffieHellman('modp5');
393
394     alice.generateKeys();
395     bob.generateKeys();
396
397     var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
398     var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
399
400     /* alice_secret and bob_secret should be the same */
401     console.log(alice_secret == bob_secret);
402
403 ## crypto.pbkdf2(password, salt, iterations, keylen, callback)
404
405 Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive
406 a key of given length from the given password, salt and iterations.
407 The callback gets two arguments `(err, derivedKey)`.
408
409 ## crypto.pbkdf2Sync(password, salt, iterations, keylen)
410
411 Synchronous PBKDF2 function.  Returns derivedKey or throws error.
412
413 ## crypto.randomBytes(size, [callback])
414
415 Generates cryptographically strong pseudo-random data. Usage:
416
417     // async
418     crypto.randomBytes(256, function(ex, buf) {
419       if (ex) throw ex;
420       console.log('Have %d bytes of random data: %s', buf.length, buf);
421     });
422
423     // sync
424     try {
425       var buf = crypto.randomBytes(256);
426       console.log('Have %d bytes of random data: %s', buf.length, buf);
427     } catch (ex) {
428       // handle error
429     }
430
431 ## crypto.DEFAULT_ENCODING
432
433 The default encoding to use for functions that can take either strings
434 or buffers.  The default value is `'buffer'`, which makes it default
435 to using Buffer objects.  This is here to make the crypto module more
436 easily compatible with legacy programs that expected `'binary'` to be
437 the default encoding.
438
439 Note that new programs will probably expect buffers, so only use this
440 as a temporary measure.
441
442 ## Recent API Changes
443
444 The Crypto module was added to Node before there was the concept of a
445 unified Stream API, and before there were Buffer objects for handling
446 binary data.
447
448 As such, the streaming classes don't have the typical methods found on
449 other Node classes, and many methods accepted and returned
450 Binary-encoded strings by default rather than Buffers.  This was
451 changed to use Buffers by default instead.
452
453 This is a breaking change for some use cases, but not all.
454
455 For example, if you currently use the default arguments to the Sign
456 class, and then pass the results to the Verify class, without ever
457 inspecting the data, then it will continue to work as before.  Where
458 you once got a binary string and then presented the binary string to
459 the Verify object, you'll now get a Buffer, and present the Buffer to
460 the Verify object.
461
462 However, if you were doing things with the string data that will not
463 work properly on Buffers (such as, concatenating them, storing in
464 databases, etc.), or you are passing binary strings to the crypto
465 functions without an encoding argument, then you will need to start
466 providing encoding arguments to specify which encoding you'd like to
467 use.  To switch to the previous style of using binary strings by
468 default, set the `crypto.DEFAULT_ENCODING` field to 'binary'.  Note
469 that new programs will probably expect buffers, so only use this as a
470 temporary measure.
471
472 Also, a Streaming API will be provided, but this will be done in such
473 a way as to preserve the legacy API surface.
474
475
476 [createCipher()]: #crypto_crypto_createcipher_algorithm_password
477 [createCipheriv()]: #crypto_crypto_createcipheriv_algorithm_key_iv
478 [crypto.createDiffieHellman()]: #crypto_crypto_creatediffiehellman_prime_encoding
479 [diffieHellman.setPublicKey()]: #crypto_diffiehellman_setpublickey_public_key_encoding
480 [RFC 2412]: http://www.rfc-editor.org/rfc/rfc2412.txt
481 [RFC 3526]: http://www.rfc-editor.org/rfc/rfc3526.txt