3 Stability: 2 - Unstable; API changes are being discussed for
4 future versions. Breaking changes will be minimized. See below.
6 Use `require('crypto')` to access this module.
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.
12 It also offers a set of wrappers for OpenSSL's hash, hmac, cipher, decipher, sign and verify methods.
14 ## crypto.createCredentials(details)
16 Creates a credentials object, with the optional details being a dictionary with keys:
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
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>.
32 ## crypto.createHash(algorithm)
34 Creates and returns a hash object, a cryptographic hash with the given algorithm
35 which can be used to generate hash digests.
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.
41 Example: this program that takes the sha1 sum of a file
43 var filename = process.argv[2];
44 var crypto = require('crypto');
45 var fs = require('fs');
47 var shasum = crypto.createHash('sha1');
49 var s = fs.ReadStream(filename);
50 s.on('data', function(d) {
54 s.on('end', function() {
55 var d = shasum.digest('hex');
56 console.log(d + ' ' + filename);
61 The class for creating hash digests of data.
63 Returned by `crypto.createHash`.
65 ### hash.update(data, [input_encoding])
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.
72 ### hash.digest([encoding])
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'`.
78 Note: `hash` object can not be used after `digest()` method has been called.
81 ## crypto.createHmac(algorithm, key)
83 Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.
85 `algorithm` is dependent on the available algorithms supported by OpenSSL - see createHash above.
86 `key` is the hmac key to be used.
90 Class for creating cryptographic hmac content.
92 Returned by `crypto.createHmac`.
96 Update the hmac content with the given `data`.
97 This can be called many times with new data as it is streamed.
99 ### hmac.digest([encoding])
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'`.
105 Note: `hmac` object can not be used after `digest()` method been called.
108 ## crypto.createCipher(algorithm, password)
110 Creates and returns a cipher object, with the given algorithm and password.
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).
118 ## crypto.createCipheriv(algorithm, key, iv)
120 Creates and returns a cipher object, with the given algorithm, key and iv.
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).
127 `key` and `iv` must be `'binary'` encoded strings or [buffers](buffer.html).
131 Class for encrypting data.
133 Returned by `crypto.createCipher` and `crypto.createCipheriv`.
135 ### cipher.update(data, [input_encoding], [output_encoding])
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'`.
141 The `output_encoding` specifies the output format of the enciphered data,
142 and can be `'binary'`, `'base64'` or `'hex'`. Defaults to `'binary'`.
144 Returns the enciphered contents, and can be called many times with new data as it is streamed.
146 ### cipher.final([output_encoding])
148 Returns any remaining enciphered contents, with `output_encoding` being one of:
149 `'binary'`, `'base64'` or `'hex'`. Defaults to `'binary'`.
151 Note: `cipher` object can not be used after `final()` method been called.
153 ### cipher.setAutoPadding(auto_padding=true)
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`.
160 ## crypto.createDecipher(algorithm, password)
162 Creates and returns a decipher object, with the given algorithm and key.
163 This is the mirror of the [createCipher()][] above.
165 ## crypto.createDecipheriv(algorithm, key, iv)
167 Creates and returns a decipher object, with the given algorithm, key and iv.
168 This is the mirror of the [createCipheriv()][] above.
172 Class for decrypting data.
174 Returned by `crypto.createDecipher` and `crypto.createDecipheriv`.
176 ### decipher.update(data, [input_encoding], [output_encoding])
178 Updates the decipher with `data`, which is encoded in `'binary'`, `'base64'`
179 or `'hex'`. Defaults to `'binary'`.
181 The `output_decoding` specifies in what format to return the deciphered
182 plaintext: `'binary'`, `'ascii'` or `'utf8'`. Defaults to `'binary'`.
184 ### decipher.final([output_encoding])
186 Returns any remaining plaintext which is deciphered,
187 with `output_encoding` being one of: `'binary'`, `'ascii'` or `'utf8'`.
188 Defaults to `'binary'`.
190 Note: `decipher` object can not be used after `final()` method been called.
192 ### decipher.setAutoPadding(auto_padding=true)
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`.
198 ## crypto.createSign(algorithm)
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'`.
206 Class for generating signatures.
208 Returned by `crypto.createSign`.
210 ### signer.update(data)
212 Updates the signer object with data.
213 This can be called many times with new data as it is streamed.
215 ### signer.sign(private_key, [output_format])
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.
220 Returns the signature in `output_format` which can be `'binary'`, `'hex'` or
221 `'base64'`. Defaults to `'binary'`.
223 Note: `signer` object can not be used after `sign()` method been called.
225 ## crypto.createVerify(algorithm)
227 Creates and returns a verification object, with the given algorithm.
228 This is the mirror of the signing object above.
232 Class for verifying signatures.
234 Returned by `crypto.createVerify`.
236 ### verifier.update(data)
238 Updates the verifier object with data.
239 This can be called many times with new data as it is streamed.
241 ### verifier.verify(object, signature, [signature_format])
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'`.
249 Returns true or false depending on the validity of the signature for the data and public key.
251 Note: `verifier` object can not be used after `verify()` method been called.
253 ## crypto.createDiffieHellman(prime_length)
255 Creates a Diffie-Hellman key exchange object and generates a prime of the
256 given bit length. The generator used is `2`.
258 ## crypto.createDiffieHellman(prime, [encoding])
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'`.
264 ## Class: DiffieHellman
266 The class for creating Diffie-Hellman key exchanges.
268 Returned by `crypto.createDiffieHellman`.
270 ### diffieHellman.generateKeys([encoding])
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'`.
277 ### diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])
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.
286 ### diffieHellman.getPrime([encoding])
288 Returns the Diffie-Hellman prime in the specified encoding, which can be
289 `'binary'`, `'hex'`, or `'base64'`. Defaults to `'binary'`.
291 ### diffieHellman.getGenerator([encoding])
293 Returns the Diffie-Hellman prime in the specified encoding, which can be
294 `'binary'`, `'hex'`, or `'base64'`. Defaults to `'binary'`.
296 ### diffieHellman.getPublicKey([encoding])
298 Returns the Diffie-Hellman public key in the specified encoding, which can
299 be `'binary'`, `'hex'`, or `'base64'`. Defaults to `'binary'`.
301 ### diffieHellman.getPrivateKey([encoding])
303 Returns the Diffie-Hellman private key in the specified encoding, which can
304 be `'binary'`, `'hex'`, or `'base64'`. Defaults to `'binary'`.
306 ### diffieHellman.setPublicKey(public_key, [encoding])
308 Sets the Diffie-Hellman public key. Key encoding can be `'binary'`, `'hex'`,
309 or `'base64'`. Defaults to `'binary'`.
311 ### diffieHellman.setPrivateKey(public_key, [encoding])
313 Sets the Diffie-Hellman private key. Key encoding can be `'binary'`, `'hex'`,
314 or `'base64'`. Defaults to `'binary'`.
316 ## crypto.getDiffieHellman(group_name)
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
331 Example (obtaining a shared secret):
333 var crypto = require('crypto');
334 var alice = crypto.getDiffieHellman('modp5');
335 var bob = crypto.getDiffieHellman('modp5');
337 alice.generateKeys();
340 var alice_secret = alice.computeSecret(bob.getPublicKey(), 'binary', 'hex');
341 var bob_secret = bob.computeSecret(alice.getPublicKey(), 'binary', 'hex');
343 /* alice_secret and bob_secret should be the same */
344 console.log(alice_secret == bob_secret);
346 ## crypto.pbkdf2(password, salt, iterations, keylen, callback)
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)`.
352 ## crypto.randomBytes(size, [callback])
354 Generates cryptographically strong pseudo-random data. Usage:
357 crypto.randomBytes(256, function(ex, buf) {
359 console.log('Have %d bytes of random data: %s', buf.length, buf);
364 var buf = crypto.randomBytes(256);
365 console.log('Have %d bytes of random data: %s', buf.length, buf);
370 ## Proposed API Changes in Future Versions of Node
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
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.
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.
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
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
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.
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