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