crypto: Move encoding logic to JS, default=buffer
[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 requires OpenSSL to be available on the underlying platform.
9 It offers a way of encapsulating secure credentials to be used as part
10 of a secure HTTPS net or http connection.
11
12 It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, 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 dictionary with keys:
38
39 * `pfx` : A string or buffer holding the PFX or PKCS12 encoded private key, certificate and CA certificates
40 * `key` : A string holding the PEM encoded private key
41 * `passphrase` : A string of passphrase for the private key or pfx
42 * `cert` : A string holding the PEM encoded certificate
43 * `ca` : Either a string or list of strings of PEM encoded CA certificates to trust.
44 * `crl` : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)
45 * `ciphers`: A string describing the ciphers to use or exclude. Consult
46   <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT> for details
47   on the format.
48
49 If no 'ca' details are given, then node.js will use the default publicly trusted list of CAs as given in
50 <http://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt>.
51
52
53 ## crypto.createHash(algorithm)
54
55 Creates and returns a hash object, a cryptographic hash with the given algorithm
56 which can be used to generate hash digests.
57
58 `algorithm` is dependent on the available algorithms supported by the version
59 of OpenSSL on the platform. Examples are `'sha1'`, `'md5'`, `'sha256'`, `'sha512'`, etc.
60 On recent releases, `openssl list-message-digest-algorithms` will display the available digest algorithms.
61
62 Example: this program that takes the sha1 sum of a file
63
64     var filename = process.argv[2];
65     var crypto = require('crypto');
66     var fs = require('fs');
67
68     var shasum = crypto.createHash('sha1');
69
70     var s = fs.ReadStream(filename);
71     s.on('data', function(d) {
72       shasum.update(d);
73     });
74
75     s.on('end', function() {
76       var d = shasum.digest('hex');
77       console.log(d + '  ' + filename);
78     });
79
80 ## Class: Hash
81
82 The class for creating hash digests of data.
83
84 Returned by `crypto.createHash`.
85
86 ### hash.update(data, [input_encoding])
87
88 Updates the hash content with the given `data`, the encoding of which is given
89 in `input_encoding` and can be `'buffer'`, `'utf8'`, `'ascii'` or `'binary'`.
90 Defaults to `'buffer'`.
91
92 This can be called many times with new data as it is streamed.
93
94 ### hash.digest([encoding])
95
96 Calculates the digest of all of the passed data to be hashed.
97 The `encoding` can be `'buffer'`, `'hex'`, `'binary'` or `'base64'`.
98 Defaults to `'buffer'`.
99
100 Note: `hash` object can not be used after `digest()` method been called.
101
102
103 ## crypto.createHmac(algorithm, key)
104
105 Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.
106
107 `algorithm` is dependent on the available algorithms supported by OpenSSL - see createHash above.
108 `key` is the hmac key to be used.
109
110 ## Class: Hmac
111
112 Class for creating cryptographic hmac content.
113
114 Returned by `crypto.createHmac`.
115
116 ### hmac.update(data)
117
118 Update the hmac content with the given `data`.
119 This can be called many times with new data as it is streamed.
120
121 ### hmac.digest([encoding])
122
123 Calculates the digest of all of the passed data to the hmac.
124 The `encoding` can be `'buffer'`, `'hex'`, `'binary'` or `'base64'`.
125 Defaults to `'buffer'`.
126
127 Note: `hmac` object can not be used after `digest()` method been called.
128
129
130 ## crypto.createCipher(algorithm, password)
131
132 Creates and returns a cipher object, with the given algorithm and password.
133
134 `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc.
135 On recent releases, `openssl list-cipher-algorithms` will display the
136 available cipher algorithms.
137 `password` is used to derive key and IV, which must be a `'binary'` encoded
138 string or a [buffer](buffer.html).
139
140 ## crypto.createCipheriv(algorithm, key, iv)
141
142 Creates and returns a cipher object, with the given algorithm, key and iv.
143
144 `algorithm` is the same as the argument to `createCipher()`.
145 `key` is the raw key used by the algorithm.
146 `iv` is an [initialization
147 vector](http://en.wikipedia.org/wiki/Initialization_vector).
148
149 `key` and `iv` must be `'binary'` encoded strings or [buffers](buffer.html).
150
151 ## Class: Cipher
152
153 Class for encrypting data.
154
155 Returned by `crypto.createCipher` and `crypto.createCipheriv`.
156
157 ### cipher.update(data, [input_encoding], [output_encoding])
158
159 Updates the cipher with `data`, the encoding of which is given in
160 `input_encoding` and can be `'buffer'`, `'utf8'`, `'ascii'` or `'binary'`.
161 Defaults to `'buffer'`.
162
163 The `output_encoding` specifies the output format of the enciphered data,
164 and can be `'buffer'`, `'binary'`, `'base64'` or `'hex'`. Defaults to
165 `'buffer'`.
166
167 Returns the enciphered contents, and can be called many times with new data as it is streamed.
168
169 ### cipher.final([output_encoding])
170
171 Returns any remaining enciphered contents, with `output_encoding` being one of:
172 `'buffer'`, `'binary'`, `'base64'` or `'hex'`. Defaults to `'buffer'`.
173
174 Note: `cipher` object can not be used after `final()` method been called.
175
176 ### cipher.setAutoPadding(auto_padding=true)
177
178 You can disable automatic padding of the input data to block size. If `auto_padding` is false,
179 the length of the entire input data must be a multiple of the cipher's block size or `final` will fail.
180 Useful for non-standard padding, e.g. using `0x0` instead of PKCS padding. You must call this before `cipher.final`.
181
182
183 ## crypto.createDecipher(algorithm, password)
184
185 Creates and returns a decipher object, with the given algorithm and key.
186 This is the mirror of the [createCipher()][] above.
187
188 ## crypto.createDecipheriv(algorithm, key, iv)
189
190 Creates and returns a decipher object, with the given algorithm, key and iv.
191 This is the mirror of the [createCipheriv()][] above.
192
193 ## Class: Decipher
194
195 Class for decrypting data.
196
197 Returned by `crypto.createDecipher` and `crypto.createDecipheriv`.
198
199 ### decipher.update(data, [input_encoding], [output_encoding])
200
201 Updates the decipher with `data`, which is encoded in `'buffer'`, `'binary'`,
202 `'base64'` or `'hex'`. Defaults to `'buffer'`.
203
204 The `output_decoding` specifies in what format to return the deciphered
205 plaintext: `'buffer'`, `'binary'`, `'ascii'` or `'utf8'`.
206 Defaults to `'buffer'`.
207
208 ### decipher.final([output_encoding])
209
210 Returns any remaining plaintext which is deciphered,
211 with `output_encoding` being one of: `'buffer'`, `'binary'`, `'ascii'` or
212 `'utf8'`.
213 Defaults to `'buffer'`.
214
215 Note: `decipher` object can not be used after `final()` method been called.
216
217 ### decipher.setAutoPadding(auto_padding=true)
218
219 You can disable auto padding if the data has been encrypted without standard block padding to prevent
220 `decipher.final` from checking and removing it. Can only work if the input data's length is a multiple of the
221 ciphers block size. You must call this before streaming data to `decipher.update`.
222
223 ## crypto.createSign(algorithm)
224
225 Creates and returns a signing object, with the given algorithm.
226 On recent OpenSSL releases, `openssl list-public-key-algorithms` will display
227 the available signing algorithms. Examples are `'RSA-SHA256'`.
228
229 ## Class: Signer
230
231 Class for generating signatures.
232
233 Returned by `crypto.createSign`.
234
235 ### signer.update(data)
236
237 Updates the signer object with data.
238 This can be called many times with new data as it is streamed.
239
240 ### signer.sign(private_key, [output_format])
241
242 Calculates the signature on all the updated data passed through the signer.
243 `private_key` is a string containing the PEM encoded private key for signing.
244
245 Returns the signature in `output_format` which can be `'buffer'`, `'binary'`,
246 `'hex'` or `'base64'`. Defaults to `'buffer'`.
247
248 Note: `signer` object can not be used after `sign()` method been called.
249
250 ## crypto.createVerify(algorithm)
251
252 Creates and returns a verification object, with the given algorithm.
253 This is the mirror of the signing object above.
254
255 ## Class: Verify
256
257 Class for verifying signatures.
258
259 Returned by `crypto.createVerify`.
260
261 ### verifier.update(data)
262
263 Updates the verifier object with data.
264 This can be called many times with new data as it is streamed.
265
266 ### verifier.verify(object, signature, [signature_format])
267
268 Verifies the signed data by using the `object` and `signature`. `object` is  a
269 string containing a PEM encoded object, which can be one of RSA public key,
270 DSA public key, or X.509 certificate. `signature` is the previously calculated
271 signature for the data, in the `signature_format` which can be `'buffer'`,
272 `'binary'`, `'hex'` or `'base64'`. Defaults to `'buffer'`.
273
274 Returns true or false depending on the validity of the signature for the data and public key.
275
276 Note: `verifier` object can not be used after `verify()` method been called.
277
278 ## crypto.createDiffieHellman(prime_length)
279
280 Creates a Diffie-Hellman key exchange object and generates a prime of the
281 given bit length. The generator used is `2`.
282
283 ## crypto.createDiffieHellman(prime, [encoding])
284
285 Creates a Diffie-Hellman key exchange object using the supplied prime. The
286 generator used is `2`. Encoding can be `'buffer'`, `'binary'`, `'hex'`, or
287 `'base64'`.
288 Defaults to `'buffer'`.
289
290 ## Class: DiffieHellman
291
292 The class for creating Diffie-Hellman key exchanges.
293
294 Returned by `crypto.createDiffieHellman`.
295
296 ### diffieHellman.generateKeys([encoding])
297
298 Generates private and public Diffie-Hellman key values, and returns the
299 public key in the specified encoding. This key should be transferred to the
300 other party. Encoding can be `'binary'`, `'hex'`, or `'base64'`.
301 Defaults to `'buffer'`.
302
303 ### diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])
304
305 Computes the shared secret using `other_public_key` as the other party's
306 public key and returns the computed shared secret. Supplied key is
307 interpreted using specified `input_encoding`, and secret is encoded using
308 specified `output_encoding`. Encodings can be `'buffer'`, `'binary'`, `'hex'`,
309 or `'base64'`. The input encoding defaults to `'buffer'`.
310 If no output encoding is given, the input encoding is used as output encoding.
311
312 ### diffieHellman.getPrime([encoding])
313
314 Returns the Diffie-Hellman prime in the specified encoding, which can be
315 `'buffer'`, `'binary'`, `'hex'`, or `'base64'`. Defaults to `'buffer'`.
316
317 ### diffieHellman.getGenerator([encoding])
318
319 Returns the Diffie-Hellman prime in the specified encoding, which can be
320 `'buffer'`, `'binary'`, `'hex'`, or `'base64'`. Defaults to `'buffer'`.
321
322 ### diffieHellman.getPublicKey([encoding])
323
324 Returns the Diffie-Hellman public key in the specified encoding, which can
325 be `'binary'`, `'hex'`, or `'base64'`. Defaults to `'buffer'`.
326
327 ### diffieHellman.getPrivateKey([encoding])
328
329 Returns the Diffie-Hellman private key in the specified encoding, which can
330 be `'buffer'`, `'binary'`, `'hex'`, or `'base64'`. Defaults to
331 `'buffer'`.
332
333 ### diffieHellman.setPublicKey(public_key, [encoding])
334
335 Sets the Diffie-Hellman public key. Key encoding can be `'buffer', ``'binary'`,
336 `'hex'` or `'base64'`. Defaults to `'buffer'`.
337
338 ### diffieHellman.setPrivateKey(public_key, [encoding])
339
340 Sets the Diffie-Hellman private key. Key encoding can be `'buffer'`, `'binary'`,
341 `'hex'` or `'base64'`. Defaults to `'buffer'`.
342
343 ## crypto.getDiffieHellman(group_name)
344
345 Creates a predefined Diffie-Hellman key exchange object.
346 The supported groups are: `'modp1'`, `'modp2'`, `'modp5'`
347 (defined in [RFC 2412][])
348 and `'modp14'`, `'modp15'`, `'modp16'`, `'modp17'`, `'modp18'`
349 (defined in [RFC 3526][]).
350 The returned object mimics the interface of objects created by
351 [crypto.createDiffieHellman()][] above, but
352 will not allow to change the keys (with
353 [diffieHellman.setPublicKey()][] for example).
354 The advantage of using this routine is that the parties don't have to
355 generate nor exchange group modulus beforehand, saving both processor and
356 communication time.
357
358 Example (obtaining a shared secret):
359
360     var crypto = require('crypto');
361     var alice = crypto.getDiffieHellman('modp5');
362     var bob = crypto.getDiffieHellman('modp5');
363
364     alice.generateKeys();
365     bob.generateKeys();
366
367     var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
368     var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
369
370     /* alice_secret and bob_secret should be the same */
371     console.log(alice_secret == bob_secret);
372
373 ## crypto.pbkdf2(password, salt, iterations, keylen, callback)
374
375 Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive
376 a key of given length from the given password, salt and iterations.
377 The callback gets two arguments `(err, derivedKey)`.
378
379 ## crypto.randomBytes(size, [callback])
380
381 Generates cryptographically strong pseudo-random data. Usage:
382
383     // async
384     crypto.randomBytes(256, function(ex, buf) {
385       if (ex) throw ex;
386       console.log('Have %d bytes of random data: %s', buf.length, buf);
387     });
388
389     // sync
390     try {
391       var buf = crypto.randomBytes(256);
392       console.log('Have %d bytes of random data: %s', buf.length, buf);
393     } catch (ex) {
394       // handle error
395     }
396
397 ## Proposed API Changes in Future Versions of Node
398
399 The Crypto module was added to Node before there was the concept of a
400 unified Stream API, and before there were Buffer objects for handling
401 binary data.
402
403 As such, the streaming classes don't have the typical methods found on
404 other Node classes, and many methods accept and return Binary-encoded
405 strings by default rather than Buffers.
406
407 A future version of node will make Buffers the default data type.
408 This will be a breaking change for some use cases, but not all.
409
410 For example, if you currently use the default arguments to the Sign
411 class, and then pass the results to the Verify class, without ever
412 inspecting the data, then it will continue to work as before.  Where
413 you now get a binary string and then present the binary string to the
414 Verify object, you'll get a Buffer, and present the Buffer to the
415 Verify object.
416
417 However, if you are doing things with the string data that will not
418 work properly on Buffers (such as, concatenating them, storing in
419 databases, etc.), or you are passing binary strings to the crypto
420 functions without an encoding argument, then you will need to start
421 providing encoding arguments to specify which encoding you'd like to
422 use.
423
424 Also, a Streaming API will be provided, but this will be done in such
425 a way as to preserve the legacy API surface.
426
427
428 [createCipher()]: #crypto_crypto_createcipher_algorithm_password
429 [createCipheriv()]: #crypto_crypto_createcipheriv_algorithm_key_iv
430 [crypto.createDiffieHellman()]: #crypto_crypto_creatediffiehellman_prime_encoding
431 [diffieHellman.setPublicKey()]: #crypto_diffiehellman_setpublickey_public_key_encoding
432 [RFC 2412]: http://www.rfc-editor.org/rfc/rfc2412.txt
433 [RFC 3526]: http://www.rfc-editor.org/rfc/rfc3526.txt