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