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.
15 ## crypto.getCiphers()
17 Returns an array with the names of the supported ciphers.
21 var ciphers = crypto.getCiphers();
22 console.log(ciphers); // ['AES128-SHA', 'AES256-SHA', ...]
27 Returns an array with the names of the supported hash algorithms.
31 var hashes = crypto.getHashes();
32 console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]
35 ## crypto.createCredentials(details)
37 Creates a credentials object, with the optional details being a dictionary with keys:
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
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>.
53 ## crypto.createHash(algorithm)
55 Creates and returns a hash object, a cryptographic hash with the given algorithm
56 which can be used to generate hash digests.
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.
62 Example: this program that takes the sha1 sum of a file
64 var filename = process.argv[2];
65 var crypto = require('crypto');
66 var fs = require('fs');
68 var shasum = crypto.createHash('sha1');
70 var s = fs.ReadStream(filename);
71 s.on('data', function(d) {
75 s.on('end', function() {
76 var d = shasum.digest('hex');
77 console.log(d + ' ' + filename);
82 The class for creating hash digests of data.
84 Returned by `crypto.createHash`.
86 ### hash.update(data, [input_encoding])
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'`.
92 This can be called many times with new data as it is streamed.
94 ### hash.digest([encoding])
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'`.
100 Note: `hash` object can not be used after `digest()` method been called.
103 ## crypto.createHmac(algorithm, key)
105 Creates and returns a hmac object, a cryptographic hmac with the given algorithm and key.
107 `algorithm` is dependent on the available algorithms supported by OpenSSL - see createHash above.
108 `key` is the hmac key to be used.
112 Class for creating cryptographic hmac content.
114 Returned by `crypto.createHmac`.
116 ### hmac.update(data)
118 Update the hmac content with the given `data`.
119 This can be called many times with new data as it is streamed.
121 ### hmac.digest([encoding])
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'`.
127 Note: `hmac` object can not be used after `digest()` method been called.
130 ## crypto.createCipher(algorithm, password)
132 Creates and returns a cipher object, with the given algorithm and password.
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).
140 ## crypto.createCipheriv(algorithm, key, iv)
142 Creates and returns a cipher object, with the given algorithm, key and iv.
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).
149 `key` and `iv` must be `'binary'` encoded strings or [buffers](buffer.html).
153 Class for encrypting data.
155 Returned by `crypto.createCipher` and `crypto.createCipheriv`.
157 ### cipher.update(data, [input_encoding], [output_encoding])
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'`.
163 The `output_encoding` specifies the output format of the enciphered data,
164 and can be `'buffer'`, `'binary'`, `'base64'` or `'hex'`. Defaults to
167 Returns the enciphered contents, and can be called many times with new data as it is streamed.
169 ### cipher.final([output_encoding])
171 Returns any remaining enciphered contents, with `output_encoding` being one of:
172 `'buffer'`, `'binary'`, `'base64'` or `'hex'`. Defaults to `'buffer'`.
174 Note: `cipher` object can not be used after `final()` method been called.
176 ### cipher.setAutoPadding(auto_padding=true)
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`.
183 ## crypto.createDecipher(algorithm, password)
185 Creates and returns a decipher object, with the given algorithm and key.
186 This is the mirror of the [createCipher()][] above.
188 ## crypto.createDecipheriv(algorithm, key, iv)
190 Creates and returns a decipher object, with the given algorithm, key and iv.
191 This is the mirror of the [createCipheriv()][] above.
195 Class for decrypting data.
197 Returned by `crypto.createDecipher` and `crypto.createDecipheriv`.
199 ### decipher.update(data, [input_encoding], [output_encoding])
201 Updates the decipher with `data`, which is encoded in `'buffer'`, `'binary'`,
202 `'base64'` or `'hex'`. Defaults to `'buffer'`.
204 The `output_decoding` specifies in what format to return the deciphered
205 plaintext: `'buffer'`, `'binary'`, `'ascii'` or `'utf8'`.
206 Defaults to `'buffer'`.
208 ### decipher.final([output_encoding])
210 Returns any remaining plaintext which is deciphered,
211 with `output_encoding` being one of: `'buffer'`, `'binary'`, `'ascii'` or
213 Defaults to `'buffer'`.
215 Note: `decipher` object can not be used after `final()` method been called.
217 ### decipher.setAutoPadding(auto_padding=true)
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`.
223 ## crypto.createSign(algorithm)
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'`.
231 Class for generating signatures.
233 Returned by `crypto.createSign`.
235 ### signer.update(data)
237 Updates the signer object with data.
238 This can be called many times with new data as it is streamed.
240 ### signer.sign(private_key, [output_format])
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.
245 Returns the signature in `output_format` which can be `'buffer'`, `'binary'`,
246 `'hex'` or `'base64'`. Defaults to `'buffer'`.
248 Note: `signer` object can not be used after `sign()` method been called.
250 ## crypto.createVerify(algorithm)
252 Creates and returns a verification object, with the given algorithm.
253 This is the mirror of the signing object above.
257 Class for verifying signatures.
259 Returned by `crypto.createVerify`.
261 ### verifier.update(data)
263 Updates the verifier object with data.
264 This can be called many times with new data as it is streamed.
266 ### verifier.verify(object, signature, [signature_format])
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'`.
274 Returns true or false depending on the validity of the signature for the data and public key.
276 Note: `verifier` object can not be used after `verify()` method been called.
278 ## crypto.createDiffieHellman(prime_length)
280 Creates a Diffie-Hellman key exchange object and generates a prime of the
281 given bit length. The generator used is `2`.
283 ## crypto.createDiffieHellman(prime, [encoding])
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
288 Defaults to `'buffer'`.
290 ## Class: DiffieHellman
292 The class for creating Diffie-Hellman key exchanges.
294 Returned by `crypto.createDiffieHellman`.
296 ### diffieHellman.generateKeys([encoding])
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'`.
303 ### diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])
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.
312 ### diffieHellman.getPrime([encoding])
314 Returns the Diffie-Hellman prime in the specified encoding, which can be
315 `'buffer'`, `'binary'`, `'hex'`, or `'base64'`. Defaults to `'buffer'`.
317 ### diffieHellman.getGenerator([encoding])
319 Returns the Diffie-Hellman prime in the specified encoding, which can be
320 `'buffer'`, `'binary'`, `'hex'`, or `'base64'`. Defaults to `'buffer'`.
322 ### diffieHellman.getPublicKey([encoding])
324 Returns the Diffie-Hellman public key in the specified encoding, which can
325 be `'binary'`, `'hex'`, or `'base64'`. Defaults to `'buffer'`.
327 ### diffieHellman.getPrivateKey([encoding])
329 Returns the Diffie-Hellman private key in the specified encoding, which can
330 be `'buffer'`, `'binary'`, `'hex'`, or `'base64'`. Defaults to
333 ### diffieHellman.setPublicKey(public_key, [encoding])
335 Sets the Diffie-Hellman public key. Key encoding can be `'buffer', ``'binary'`,
336 `'hex'` or `'base64'`. Defaults to `'buffer'`.
338 ### diffieHellman.setPrivateKey(public_key, [encoding])
340 Sets the Diffie-Hellman private key. Key encoding can be `'buffer'`, `'binary'`,
341 `'hex'` or `'base64'`. Defaults to `'buffer'`.
343 ## crypto.getDiffieHellman(group_name)
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
358 Example (obtaining a shared secret):
360 var crypto = require('crypto');
361 var alice = crypto.getDiffieHellman('modp5');
362 var bob = crypto.getDiffieHellman('modp5');
364 alice.generateKeys();
367 var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
368 var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
370 /* alice_secret and bob_secret should be the same */
371 console.log(alice_secret == bob_secret);
373 ## crypto.pbkdf2(password, salt, iterations, keylen, callback)
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)`.
379 ## crypto.pbkdf2Sync(password, salt, iterations, keylen)
381 Synchronous PBKDF2 function. Returns derivedKey or throws error.
383 ## crypto.randomBytes(size, [callback])
385 Generates cryptographically strong pseudo-random data. Usage:
388 crypto.randomBytes(256, function(ex, buf) {
390 console.log('Have %d bytes of random data: %s', buf.length, buf);
395 var buf = crypto.randomBytes(256);
396 console.log('Have %d bytes of random data: %s', buf.length, buf);
401 ## Proposed API Changes in Future Versions of Node
403 The Crypto module was added to Node before there was the concept of a
404 unified Stream API, and before there were Buffer objects for handling
407 As such, the streaming classes don't have the typical methods found on
408 other Node classes, and many methods accept and return Binary-encoded
409 strings by default rather than Buffers.
411 A future version of node will make Buffers the default data type.
412 This will be a breaking change for some use cases, but not all.
414 For example, if you currently use the default arguments to the Sign
415 class, and then pass the results to the Verify class, without ever
416 inspecting the data, then it will continue to work as before. Where
417 you now get a binary string and then present the binary string to the
418 Verify object, you'll get a Buffer, and present the Buffer to the
421 However, if you are doing things with the string data that will not
422 work properly on Buffers (such as, concatenating them, storing in
423 databases, etc.), or you are passing binary strings to the crypto
424 functions without an encoding argument, then you will need to start
425 providing encoding arguments to specify which encoding you'd like to
428 Also, a Streaming API will be provided, but this will be done in such
429 a way as to preserve the legacy API surface.
432 [createCipher()]: #crypto_crypto_createcipher_algorithm_password
433 [createCipheriv()]: #crypto_crypto_createcipheriv_algorithm_key_iv
434 [crypto.createDiffieHellman()]: #crypto_crypto_creatediffiehellman_prime_encoding
435 [diffieHellman.setPublicKey()]: #crypto_diffiehellman_setpublickey_public_key_encoding
436 [RFC 2412]: http://www.rfc-editor.org/rfc/rfc2412.txt
437 [RFC 3526]: http://www.rfc-editor.org/rfc/rfc3526.txt