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 offers a way of encapsulating secure credentials to be
9 used as part of a secure HTTPS net or http connection.
11 It also offers a set of wrappers for OpenSSL's hash, hmac, cipher,
12 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); // ['AES-128-CBC', 'AES-128-CBC-HMAC-SHA1', ...]
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
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.
51 <http://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT>
52 for details on the format.
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>.
59 ## crypto.createHash(algorithm)
61 Creates and returns a hash object, a cryptographic hash with the given
62 algorithm which can be used to generate hash digests.
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
70 Example: this program that takes the sha1 sum of a file
72 var filename = process.argv[2];
73 var crypto = require('crypto');
74 var fs = require('fs');
76 var shasum = crypto.createHash('sha1');
78 var s = fs.ReadStream(filename);
79 s.on('data', function(d) {
83 s.on('end', function() {
84 var d = shasum.digest('hex');
85 console.log(d + ' ' + filename);
90 The class for creating hash digests of data.
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.
97 Returned by `crypto.createHash`.
99 ### hash.update(data, [input_encoding])
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 If `data` is a `Buffer` then `input_encoding` is ignored.
106 This can be called many times with new data as it is streamed.
108 ### hash.digest([encoding])
110 Calculates the digest of all of the passed data to be hashed. The
111 `encoding` can be `'hex'`, `'binary'` or `'base64'`. If no encoding
112 is provided, then a buffer is returned.
114 Note: `hash` object can not be used after `digest()` method has been
118 ## crypto.createHmac(algorithm, key)
120 Creates and returns a hmac object, a cryptographic hmac with the given
123 It is a [stream](stream.html) that is both readable and writable. The
124 written data is used to compute the hmac. Once the writable side of
125 the stream is ended, use the `read()` method to get the computed
126 digest. The legacy `update` and `digest` methods are also supported.
128 `algorithm` is dependent on the available algorithms supported by
129 OpenSSL - see createHash above. `key` is the hmac key to be used.
133 Class for creating cryptographic hmac content.
135 Returned by `crypto.createHmac`.
137 ### hmac.update(data)
139 Update the hmac content with the given `data`. This can be called
140 many times with new data as it is streamed.
142 ### hmac.digest([encoding])
144 Calculates the digest of all of the passed data to the hmac. The
145 `encoding` can be `'hex'`, `'binary'` or `'base64'`. If no encoding
146 is provided, then a buffer is returned.
148 Note: `hmac` object can not be used after `digest()` method has been
152 ## crypto.createCipher(algorithm, password)
154 Creates and returns a cipher object, with the given algorithm and
157 `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
158 recent releases, `openssl list-cipher-algorithms` will display the
159 available cipher algorithms. `password` is used to derive key and IV,
160 which must be a `'binary'` encoded string or a [buffer](buffer.html).
162 It is a [stream](stream.html) that is both readable and writable. The
163 written data is used to compute the hash. Once the writable side of
164 the stream is ended, use the `read()` method to get the computed hash
165 digest. The legacy `update` and `digest` methods are also supported.
167 ## crypto.createCipheriv(algorithm, key, iv)
169 Creates and returns a cipher object, with the given algorithm, key and
172 `algorithm` is the same as the argument to `createCipher()`. `key` is
173 the raw key used by the algorithm. `iv` is an [initialization
174 vector](http://en.wikipedia.org/wiki/Initialization_vector).
176 `key` and `iv` must be `'binary'` encoded strings or
177 [buffers](buffer.html).
181 Class for encrypting data.
183 Returned by `crypto.createCipher` and `crypto.createCipheriv`.
185 Cipher objects are [streams](stream.html) that are both readable and
186 writable. The written plain text data is used to produce the
187 encrypted data on the readable side. The legacy `update` and `final`
188 methods are also supported.
190 ### cipher.update(data, [input_encoding], [output_encoding])
192 Updates the cipher with `data`, the encoding of which is given in
193 `input_encoding` and can be `'utf8'`, `'ascii'` or `'binary'`. If no
194 encoding is provided, then a buffer is expected.
195 If `data` is a `Buffer` then `input_encoding` is ignored.
197 The `output_encoding` specifies the output format of the enciphered
198 data, and can be `'binary'`, `'base64'` or `'hex'`. If no encoding is
199 provided, then a buffer is returned.
201 Returns the enciphered contents, and can be called many times with new
202 data as it is streamed.
204 ### cipher.final([output_encoding])
206 Returns any remaining enciphered contents, with `output_encoding`
207 being one of: `'binary'`, `'base64'` or `'hex'`. If no encoding is
208 provided, then a buffer is returned.
210 Note: `cipher` object can not be used after `final()` method has been
213 ### cipher.setAutoPadding(auto_padding=true)
215 You can disable automatic padding of the input data to block size. If
216 `auto_padding` is false, the length of the entire input data must be a
217 multiple of the cipher's block size or `final` will fail. Useful for
218 non-standard padding, e.g. using `0x0` instead of PKCS padding. You
219 must call this before `cipher.final`.
222 ## crypto.createDecipher(algorithm, password)
224 Creates and returns a decipher object, with the given algorithm and
225 key. This is the mirror of the [createCipher()][] above.
227 ## crypto.createDecipheriv(algorithm, key, iv)
229 Creates and returns a decipher object, with the given algorithm, key
230 and iv. This is the mirror of the [createCipheriv()][] above.
234 Class for decrypting data.
236 Returned by `crypto.createDecipher` and `crypto.createDecipheriv`.
238 Decipher objects are [streams](stream.html) that are both readable and
239 writable. The written enciphered data is used to produce the
240 plain-text data on the the readable side. The legacy `update` and
241 `final` methods are also supported.
243 ### decipher.update(data, [input_encoding], [output_encoding])
245 Updates the decipher with `data`, which is encoded in `'binary'`,
246 `'base64'` or `'hex'`. If no encoding is provided, then a buffer is
248 If `data` is a `Buffer` then `input_encoding` is ignored.
250 The `output_decoding` specifies in what format to return the
251 deciphered plaintext: `'binary'`, `'ascii'` or `'utf8'`. If no
252 encoding is provided, then a buffer is returned.
254 ### decipher.final([output_encoding])
256 Returns any remaining plaintext which is deciphered, with
257 `output_encoding` being one of: `'binary'`, `'ascii'` or `'utf8'`. If
258 no encoding is provided, then a buffer is returned.
260 Note: `decipher` object can not be used after `final()` method has been
263 ### decipher.setAutoPadding(auto_padding=true)
265 You can disable auto padding if the data has been encrypted without
266 standard block padding to prevent `decipher.final` from checking and
267 removing it. Can only work if the input data's length is a multiple of
268 the ciphers block size. You must call this before streaming data to
271 ## crypto.createSign(algorithm)
273 Creates and returns a signing object, with the given algorithm. On
274 recent OpenSSL releases, `openssl list-public-key-algorithms` will
275 display the available signing algorithms. Examples are `'RSA-SHA256'`.
279 Class for generating signatures.
281 Returned by `crypto.createSign`.
283 Sign objects are writable [streams](stream.html). The written data is
284 used to generate the signature. Once all of the data has been
285 written, the `sign` method will return the signature. The legacy
286 `update` method is also supported.
288 ### sign.update(data)
290 Updates the sign object with data. This can be called many times
291 with new data as it is streamed.
293 ### sign.sign(private_key, [output_format])
295 Calculates the signature on all the updated data passed through the
296 sign. `private_key` is a string containing the PEM encoded private
299 Returns the signature in `output_format` which can be `'binary'`,
300 `'hex'` or `'base64'`. If no encoding is provided, then a buffer is
303 Note: `sign` object can not be used after `sign()` method has been
306 ## crypto.createVerify(algorithm)
308 Creates and returns a verification object, with the given algorithm.
309 This is the mirror of the signing object above.
313 Class for verifying signatures.
315 Returned by `crypto.createVerify`.
317 Verify objects are writable [streams](stream.html). The written data
318 is used to validate against the supplied signature. Once all of the
319 data has been written, the `verify` method will return true if the
320 supplied signature is valid. The legacy `update` method is also
323 ### verifier.update(data)
325 Updates the verifier object with data. This can be called many times
326 with new data as it is streamed.
328 ### verifier.verify(object, signature, [signature_format])
330 Verifies the signed data by using the `object` and `signature`.
331 `object` is a string containing a PEM encoded object, which can be
332 one of RSA public key, DSA public key, or X.509 certificate.
333 `signature` is the previously calculated signature for the data, in
334 the `signature_format` which can be `'binary'`, `'hex'` or `'base64'`.
335 If no encoding is specified, then a buffer is expected.
337 Returns true or false depending on the validity of the signature for
338 the data and public key.
340 Note: `verifier` object can not be used after `verify()` method has been
343 ## crypto.createDiffieHellman(prime_length)
345 Creates a Diffie-Hellman key exchange object and generates a prime of
346 the given bit length. The generator used is `2`.
348 ## crypto.createDiffieHellman(prime, [encoding])
350 Creates a Diffie-Hellman key exchange object using the supplied prime.
351 The generator used is `2`. Encoding can be `'binary'`, `'hex'`, or
352 `'base64'`. If no encoding is specified, then a buffer is expected.
354 ## Class: DiffieHellman
356 The class for creating Diffie-Hellman key exchanges.
358 Returned by `crypto.createDiffieHellman`.
360 ### diffieHellman.generateKeys([encoding])
362 Generates private and public Diffie-Hellman key values, and returns
363 the public key in the specified encoding. This key should be
364 transferred to the other party. Encoding can be `'binary'`, `'hex'`,
365 or `'base64'`. If no encoding is provided, then a buffer is returned.
367 ### diffieHellman.computeSecret(other_public_key, [input_encoding], [output_encoding])
369 Computes the shared secret using `other_public_key` as the other
370 party's public key and returns the computed shared secret. Supplied
371 key is interpreted using specified `input_encoding`, and secret is
372 encoded using specified `output_encoding`. Encodings can be
373 `'binary'`, `'hex'`, or `'base64'`. If the input encoding is not
374 provided, then a buffer is expected.
376 If no output encoding is given, then a buffer is returned.
378 ### diffieHellman.getPrime([encoding])
380 Returns the Diffie-Hellman prime in the specified encoding, which can
381 be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided,
382 then a buffer is returned.
384 ### diffieHellman.getGenerator([encoding])
386 Returns the Diffie-Hellman prime in the specified encoding, which can
387 be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided,
388 then a buffer is returned.
390 ### diffieHellman.getPublicKey([encoding])
392 Returns the Diffie-Hellman public key in the specified encoding, which
393 can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is provided,
394 then a buffer is returned.
396 ### diffieHellman.getPrivateKey([encoding])
398 Returns the Diffie-Hellman private key in the specified encoding,
399 which can be `'binary'`, `'hex'`, or `'base64'`. If no encoding is
400 provided, then a buffer is returned.
402 ### diffieHellman.setPublicKey(public_key, [encoding])
404 Sets the Diffie-Hellman public key. Key encoding can be `'binary'`,
405 `'hex'` or `'base64'`. If no encoding is provided, then a buffer is
408 ### diffieHellman.setPrivateKey(private_key, [encoding])
410 Sets the Diffie-Hellman private key. Key encoding can be `'binary'`,
411 `'hex'` or `'base64'`. If no encoding is provided, then a buffer is
414 ## crypto.getDiffieHellman(group_name)
416 Creates a predefined Diffie-Hellman key exchange object. The
417 supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in [RFC
418 2412][]) and `'modp14'`, `'modp15'`, `'modp16'`, `'modp17'`,
419 `'modp18'` (defined in [RFC 3526][]). The returned object mimics the
420 interface of objects created by [crypto.createDiffieHellman()][]
421 above, but will not allow to change the keys (with
422 [diffieHellman.setPublicKey()][] for example). The advantage of using
423 this routine is that the parties don't have to generate nor exchange
424 group modulus beforehand, saving both processor and communication
427 Example (obtaining a shared secret):
429 var crypto = require('crypto');
430 var alice = crypto.getDiffieHellman('modp5');
431 var bob = crypto.getDiffieHellman('modp5');
433 alice.generateKeys();
436 var alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
437 var bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
439 /* alice_secret and bob_secret should be the same */
440 console.log(alice_secret == bob_secret);
442 ## crypto.pbkdf2(password, salt, iterations, keylen, callback)
444 Asynchronous PBKDF2 applies pseudorandom function HMAC-SHA1 to derive
445 a key of given length from the given password, salt and iterations.
446 The callback gets two arguments `(err, derivedKey)`.
448 ## crypto.pbkdf2Sync(password, salt, iterations, keylen)
450 Synchronous PBKDF2 function. Returns derivedKey or throws error.
452 ## crypto.randomBytes(size, [callback])
454 Generates cryptographically strong pseudo-random data. Usage:
457 crypto.randomBytes(256, function(ex, buf) {
459 console.log('Have %d bytes of random data: %s', buf.length, buf);
464 var buf = crypto.randomBytes(256);
465 console.log('Have %d bytes of random data: %s', buf.length, buf);
470 ## crypto.pseudoRandomBytes(size, [callback])
472 Generates *non*-cryptographically strong pseudo-random data. The data
473 returned will be unique if it is sufficiently long, but is not
474 necessarily unpredictable. For this reason, the output of this
475 function should never be used where unpredictability is important,
476 such as in the generation of encryption keys.
478 Usage is otherwise identical to `crypto.randomBytes`.
480 ## crypto.DEFAULT_ENCODING
482 The default encoding to use for functions that can take either strings
483 or buffers. The default value is `'buffer'`, which makes it default
484 to using Buffer objects. This is here to make the crypto module more
485 easily compatible with legacy programs that expected `'binary'` to be
486 the default encoding.
488 Note that new programs will probably expect buffers, so only use this
489 as a temporary measure.
491 ## Recent API Changes
493 The Crypto module was added to Node before there was the concept of a
494 unified Stream API, and before there were Buffer objects for handling
497 As such, the streaming classes don't have the typical methods found on
498 other Node classes, and many methods accepted and returned
499 Binary-encoded strings by default rather than Buffers. This was
500 changed to use Buffers by default instead.
502 This is a breaking change for some use cases, but not all.
504 For example, if you currently use the default arguments to the Sign
505 class, and then pass the results to the Verify class, without ever
506 inspecting the data, then it will continue to work as before. Where
507 you once got a binary string and then presented the binary string to
508 the Verify object, you'll now get a Buffer, and present the Buffer to
511 However, if you were doing things with the string data that will not
512 work properly on Buffers (such as, concatenating them, storing in
513 databases, etc.), or you are passing binary strings to the crypto
514 functions without an encoding argument, then you will need to start
515 providing encoding arguments to specify which encoding you'd like to
516 use. To switch to the previous style of using binary strings by
517 default, set the `crypto.DEFAULT_ENCODING` field to 'binary'. Note
518 that new programs will probably expect buffers, so only use this as a
522 [createCipher()]: #crypto_crypto_createcipher_algorithm_password
523 [createCipheriv()]: #crypto_crypto_createcipheriv_algorithm_key_iv
524 [crypto.createDiffieHellman()]: #crypto_crypto_creatediffiehellman_prime_encoding
525 [diffieHellman.setPublicKey()]: #crypto_diffiehellman_setpublickey_public_key_encoding
526 [RFC 2412]: http://www.rfc-editor.org/rfc/rfc2412.txt
527 [RFC 3526]: http://www.rfc-editor.org/rfc/rfc3526.txt