5 The `crypto` module provides cryptographic functionality that includes a set of
6 wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign and verify functions.
8 Use `require('crypto')` to access this module.
10 const crypto = require('crypto');
12 const secret = 'abcdefg';
13 const hash = crypto.createHmac('sha256', secret)
14 .update('I love cupcakes')
18 // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e
22 SPKAC is a Certificate Signing Request mechanism originally implemented by
23 Netscape and now specified formally as part of [HTML5's `keygen` element][].
25 The `crypto` module provides the `Certificate` class for working with SPKAC
26 data. The most common usage is handling output generated by the HTML5
27 `<keygen>` element. Node.js uses [OpenSSL's SPKAC implementation][] internally.
29 ### new crypto.Certificate()
31 Instances of the `Certificate` class can be created using the `new` keyword
32 or by calling `crypto.Certificate()` as a function:
34 const crypto = require('crypto');
36 const cert1 = new crypto.Certificate();
37 const cert2 = crypto.Certificate();
39 ### certificate.exportChallenge(spkac)
41 The `spkac` data structure includes a public key and a challenge. The
42 `certificate.exportChallenge()` returns the challenge component in the
43 form of a Node.js [`Buffer`][]. The `spkac` argument can be either a string
46 const cert = require('crypto').Certificate();
47 const spkac = getSpkacSomehow();
48 const challenge = cert.exportChallenge(spkac);
49 console.log(challenge.toString('utf8'));
50 // Prints the challenge as a UTF8 string
52 ### Certificate.exportPublicKey(spkac)
54 The `spkac` data structure includes a public key and a challenge. The
55 `certificate.exportPublicKey()` returns the public key component in the
56 form of a Node.js [`Buffer`][]. The `spkac` argument can be either a string
59 const cert = require('crypto').Certificate();
60 const spkac = getSpkacSomehow();
61 const publicKey = cert.exportPublicKey(spkac);
62 console.log(publicKey);
63 // Prints the public key as <Buffer ...>
65 ### Certificate.verifySpkac(spkac)
67 Returns `true` if the given `spkac` data structure is valid, `false` otherwise.
68 The `spkac` argument must be a Node.js [`Buffer`][].
70 const cert = require('crypto').Certificate();
71 const spkac = getSpkacSomehow();
72 console.log(cert.verifySpkac(new Buffer(spkac)));
73 // Prints true or false
77 Instances of the `Cipher` class are used to encrypt data. The class can be
78 used in one of two ways:
80 - As a [stream][] that is both readable and writable, where plain unencrypted
81 data is written to produce encrypted data on the readable side, or
82 - Using the `cipher.update()` and `cipher.final()` methods to produce the
85 The `crypto.createCipher()` or `crypto.createCipheriv()` methods are used to
86 create `Cipher` instances. `Cipher` objects are not to be created directly
87 using the `new` keyword.
89 Example: Using `Cipher` objects as streams:
91 const crypto = require('crypto');
92 const cipher = crypto.createCipher('aes192', 'a password');
94 cipher.on('readable', () => {
95 var data = cipher.read();
97 console.log(data.toString('hex'));
98 // Prints: b919f20fc5ac2f9c1d2cce94cb1d9c2d
101 cipher.write('clear text data');
104 Example: Using `Cipher` and piped streams:
106 const crypto = require('crypto');
107 const fs = require('fs');
108 const cipher = crypto.createCipher('aes192', 'a password');
110 const input = fs.createReadStream('test.js');
111 const output = fs.createWriteStream('test.enc');
113 input.pipe(cipher).pipe(output);
115 Example: Using the `cipher.update()` and `cipher.final()` methods:
117 const crypto = require('crypto');
118 const cipher = crypto.createCipher('aes192', 'a password');
120 cipher.update('clear text data');
121 console.log(cipher.final('hex'));
122 // Prints: b919f20fc5ac2f9c1d2cce94cb1d9c2d
124 ### cipher.final([output_encoding])
126 Returns any remaining enciphered contents. If `output_encoding`
127 parameter is one of `'binary'`, `'base64'` or `'hex'`, a string is returned.
128 If an `output_encoding` is not provided, a [`Buffer`][] is returned.
130 Once the `cipher.final()` method has been called, the `Cipher` object can no
131 longer be used to encrypt data. Attempts to call `cipher.final()` more than
132 once will result in an error being thrown.
134 ### cipher.setAAD(buffer)
136 When using an authenticated encryption mode (only `GCM` is currently
137 supported), the `cipher.getAAD()` method sets the value used for the
138 _additional authenticated data_ (AAD) input parameter.
140 ### cipher.getAuthTag()
142 When using an authenticated encryption mode (only `GCM` is currently
143 supported), the `cipher.getAuthTag()` method returns a [`Buffer`][] containing
144 the _authentication tag_ that has been computed from the given data.
146 The `cipher.getAuthTag()` method should only be called after encryption has
147 been completed using the `cipher.final()` method.
149 ### cipher.setAutoPadding(auto_padding=true)
151 When using block encryption algorithms, the `Cipher` class will automatically
152 add padding to the input data to the appropriate block size. To disable the
153 default padding call `cipher.setAutoPadding(false)`.
155 When `auto_padding` is `false`, the length of the entire input data must be a
156 multiple of the cipher's block size or `cipher.final()` will throw an Error.
157 Disabling automatic padding is useful for non-standard padding, for instance
158 using `0x0` instead of PKCS padding.
160 The `cipher.setAutoPadding()` method must be called before `cipher.final()`.
162 ### cipher.update(data[, input_encoding][, output_encoding])
164 Updates the cipher with `data`. If the `input_encoding` argument is given,
165 it's value must be one of `'utf8'`, `'ascii'`, or `'binary'` and the `data`
166 argument is a string using the specified encoding. If the `input_encoding`
167 argument is not given, `data` must be a [`Buffer`][]. If `data` is a
168 [`Buffer`][] then `input_encoding` is ignored.
170 The `output_encoding` specifies the output format of the enciphered
171 data, and can be `'binary'`, `'base64'` or `'hex'`. If the `output_encoding`
172 is specified, a string using the specified encoding is returned. If no
173 `output_encoding` is provided, a [`Buffer`][] is returned.
175 The `cipher.update()` method can be called multiple times with new data until
176 `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()`
177 will result in an error being thrown.
181 Instances of the `Decipher` class are used to decrypt data. The class can be
182 used in one of two ways:
184 - As a [stream][] that is both readable and writable, where plain encrypted
185 data is written to produce unencrypted data on the readable side, or
186 - Using the `decipher.update()` and `decipher.final()` methods to produce the
189 The `crypto.createDecipher()` or `crypto.createDecipheriv()` methods are used
190 to create `Decipher` instances. `Decipher` objects are not to be created
191 directly using the `new` keyword.
193 Example: Using `Decipher` objects as streams:
195 const crypto = require('crypto');
196 const decipher = crypto.createDecipher('aes192', 'a password');
198 decipher.on('readable', () => {
199 var data = decipher.read();
201 console.log(data.toString());
202 // Prints: clear text data
205 decipher.write('b919f20fc5ac2f9c1d2cce94cb1d9c2d', 'hex');
208 Example: Using `Decipher` and piped streams:
210 const crypto = require('crypto');
211 const fs = require('fs');
212 const decipher = crypto.createDecipher('aes192', 'a password');
214 const input = fs.createReadStream('test.enc');
215 const output = fs.createWriteStream('test.js');
217 input.pipe(decipher).pipe(output);
219 Example: Using the `decipher.update()` and `decipher.final()` methods:
221 const crypto = require('crypto');
222 const decipher = crypto.createDecipher('aes192', 'a password');
224 decipher.update('b919f20fc5ac2f9c1d2cce94cb1d9c2d', 'hex');
225 console.log(decipher.final('utf8'));
226 // Prints: clear text data
228 ### decipher.final([output_encoding])
230 Returns any remaining deciphered contents. If `output_encoding`
231 parameter is one of `'binary'`, `'base64'` or `'hex'`, a string is returned.
232 If an `output_encoding` is not provided, a [`Buffer`][] is returned.
234 Once the `decipher.final()` method has been called, the `Decipher` object can
235 no longer be used to decrypt data. Attempts to call `decipher.final()` more
236 than once will result in an error being thrown.
238 ### decipher.setAAD(buffer)
240 When using an authenticated encryption mode (only `GCM` is currently
241 supported), the `cipher.getAAD()` method sets the value used for the
242 _additional authenticated data_ (AAD) input parameter.
244 ### decipher.setAuthTag(buffer)
246 When using an authenticated encryption mode (only `GCM` is currently
247 supported), the `decipher.setAuthTag()` method is used to pass in the
248 received _authentication tag_. If no tag is provided, or if the ciphertext
249 has been tampered with, `decipher.final()` with throw, indicating that the
250 ciphertext should be discarded due to failed authentication.
252 ### decipher.setAutoPadding(auto_padding=true)
254 When data has been encrypted without standard block padding, calling
255 `decipher.setAuthPadding(false)` will disable automatic padding to prevent
256 `decipher.final()` from checking for and removing padding.
258 Turning auto padding off will only work if the input data's length is a
259 multiple of the ciphers block size.
261 The `decipher.setAutoPadding()` method must be called before
264 ### decipher.update(data[, input_encoding][, output_encoding])
266 Updates the decipher with `data`. If the `input_encoding` argument is given,
267 it's value must be one of `'binary'`, `'base64'`, or `'hex'` and the `data`
268 argument is a string using the specified encoding. If the `input_encoding`
269 argument is not given, `data` must be a [`Buffer`][]. If `data` is a
270 [`Buffer`][] then `input_encoding` is ignored.
272 The `output_encoding` specifies the output format of the enciphered
273 data, and can be `'binary'`, `'ascii'` or `'utf8'`. If the `output_encoding`
274 is specified, a string using the specified encoding is returned. If no
275 `output_encoding` is provided, a [`Buffer`][] is returned.
277 The `decipher.update()` method can be called multiple times with new data until
278 `decipher.final()` is called. Calling `decipher.update()` after
279 `decipher.final()` will result in an error being thrown.
281 ## Class: DiffieHellman
283 The `DiffieHellman` class is a utility for creating Diffie-Hellman key
286 Instances of the `DiffieHellman` class can be created using the
287 `crypto.createDiffieHellman()` function.
289 const crypto = require('crypto');
290 const assert = require('assert');
292 // Generate Alice's keys...
293 const alice = crypto.createDiffieHellman(11);
294 const alice_key = alice.generateKeys();
296 // Generate Bob's keys...
297 const bob = crypto.createDiffieHellman(11);
298 const bob_key = bob.generateKeys();
300 // Exchange and generate the secret...
301 const alice_secret = alice.computeSecret(bob_key);
302 const bob_secret = bob.computeSecret(alice_key);
304 assert(alice_secret, bob_secret);
307 ### diffieHellman.computeSecret(other_public_key[, input_encoding][, output_encoding])
309 Computes the shared secret using `other_public_key` as the other
310 party's public key and returns the computed shared secret. The supplied
311 key is interpreted using the specified `input_encoding`, and secret is
312 encoded using specified `output_encoding`. Encodings can be
313 `'binary'`, `'hex'`, or `'base64'`. If the `input_encoding` is not
314 provided, `other_public_key` is expected to be a [`Buffer`][].
316 If `output_encoding` is given a string is returned; otherwise, a
317 [`Buffer`][] is returned.
319 ### diffieHellman.generateKeys([encoding])
321 Generates private and public Diffie-Hellman key values, and returns
322 the public key in the specified `encoding`. This key should be
323 transferred to the other party. Encoding can be `'binary'`, `'hex'`,
324 or `'base64'`. If `encoding` is provided a string is returned; otherwise a
325 [`Buffer`][] is returned.
327 ### diffieHellman.getGenerator([encoding])
329 Returns the Diffie-Hellman generator in the specified `encoding`, which can
330 be `'binary'`, `'hex'`, or `'base64'`. If `encoding` is provided a string is
331 returned; otherwise a [`Buffer`][] is returned.
333 ### diffieHellman.getPrime([encoding])
335 Returns the Diffie-Hellman prime in the specified `encoding`, which can
336 be `'binary'`, `'hex'`, or `'base64'`. If `encoding` is provided a string is
337 returned; otherwise a [`Buffer`][] is returned.
339 ### diffieHellman.getPrivateKey([encoding])
341 Returns the Diffie-Hellman private key in the specified `encoding`,
342 which can be `'binary'`, `'hex'`, or `'base64'`. If `encoding` is provided a
343 string is returned; otherwise a [`Buffer`][] is returned.
345 ### diffieHellman.getPublicKey([encoding])
347 Returns the Diffie-Hellman public key in the specified `encoding`, which
348 can be `'binary'`, `'hex'`, or `'base64'`. If `encoding` is provided a
349 string is returned; otherwise a [`Buffer`][] is returned.
351 ### diffieHellman.setPrivateKey(private_key[, encoding])
353 Sets the Diffie-Hellman private key. If the `encoding` argument is provided
354 and is either `'binary'`, `'hex'`, or `'base64'`, `private_key` is expected
355 to be a string. If no `encoding` is provided, `private_key` is expected
356 to be a [`Buffer`][].
358 ### diffieHellman.setPublicKey(public_key[, encoding])
360 Sets the Diffie-Hellman public key. If the `encoding` argument is provided
361 and is either `'binary'`, `'hex'` or `'base64'`, `public_key` is expected
362 to be a string. If no `encoding` is provided, `public_key` is expected
363 to be a [`Buffer`][].
365 ### diffieHellman.verifyError
367 A bit field containing any warnings and/or errors resulting from a check
368 performed during initialization of the `DiffieHellman` object.
370 The following values are valid for this property (as defined in `constants`
373 * `DH_CHECK_P_NOT_SAFE_PRIME`
374 * `DH_CHECK_P_NOT_PRIME`
375 * `DH_UNABLE_TO_CHECK_GENERATOR`
376 * `DH_NOT_SUITABLE_GENERATOR`
380 The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH)
383 Instances of the `ECDH` class can be created using the
384 `crypto.createECDH()` function.
386 const crypto = require('crypto');
387 const assert = require('assert');
389 // Generate Alice's keys...
390 const alice = crypto.createECDH('secp521r1');
391 const alice_key = alice.generateKeys();
393 // Generate Bob's keys...
394 const bob = crypto.createECDH('secp521r1');
395 const bob_key = bob.generateKeys();
397 // Exchange and generate the secret...
398 const alice_secret = alice.computeSecret(bob_key);
399 const bob_secret = bob.computeSecret(alice_key);
401 assert(alice_secret, bob_secret);
404 ### ECDH.computeSecret(other_public_key[, input_encoding][, output_encoding])
406 Computes the shared secret using `other_public_key` as the other
407 party's public key and returns the computed shared secret. The supplied
408 key is interpreted using specified `input_encoding`, and the returned secret
409 is encoded using the specified `output_encoding`. Encodings can be
410 `'binary'`, `'hex'`, or `'base64'`. If the `input_encoding` is not
411 provided, `other_public_key` is expected to be a [`Buffer`][].
413 If `output_encoding` is given a string will be returned; otherwise a
414 [`Buffer`][] is returned.
416 ### ECDH.generateKeys([encoding[, format]])
418 Generates private and public EC Diffie-Hellman key values, and returns
419 the public key in the specified `format` and `encoding`. This key should be
420 transferred to the other party.
422 The `format` arguments specifies point encoding and can be `'compressed'`,
423 `'uncompressed'`, or `'hybrid'`. If `format` is not specified, the point will
424 be returned in `'uncompressed'` format.
426 The `encoding` argument can be `'binary'`, `'hex'`, or `'base64'`. If
427 `encoding` is provided a string is returned; otherwise a [`Buffer`][]
430 ### ECDH.getPrivateKey([encoding])
432 Returns the EC Diffie-Hellman private key in the specified `encoding`,
433 which can be `'binary'`, `'hex'`, or `'base64'`. If `encoding` is provided
434 a string is returned; otherwise a [`Buffer`][] is returned.
436 ### ECDH.getPublicKey([encoding[, format]])
438 Returns the EC Diffie-Hellman public key in the specified `encoding` and
441 The `format` argument specifies point encoding and can be `'compressed'`,
442 `'uncompressed'`, or `'hybrid'`. If `format` is not specified the point will be
443 returned in `'uncompressed'` format.
445 The `encoding` argument can be `'binary'`, `'hex'`, or `'base64'`. If
446 `encoding` is specified, a string is returned; otherwise a [`Buffer`][] is
449 ### ECDH.setPrivateKey(private_key[, encoding])
451 Sets the EC Diffie-Hellman private key. The `encoding` can be `'binary'`,
452 `'hex'` or `'base64'`. If `encoding` is provided, `private_key` is expected
453 to be a string; otherwise `private_key` is expected to be a [`Buffer`][]. If
454 `private_key` is not valid for the curve specified when the `ECDH` object was
455 created, an error is thrown. Upon setting the private key, the associated
456 public point (key) is also generated and set in the ECDH object.
458 ### ECDH.setPublicKey(public_key[, encoding])
460 Stability: 0 - Deprecated
462 Sets the EC Diffie-Hellman public key. Key encoding can be `'binary'`,
463 `'hex'` or `'base64'`. If `encoding` is provided `public_key` is expected to
464 be a string; otherwise a [`Buffer`][] is expected.
466 Note that there is not normally a reason to call this method because `ECDH`
467 only requires a private key and the other party's public key to compute the
468 shared secret. Typically either `ecdh.generateKeys()` or `ecdh.setPrivateKey()`
469 will be called. The `ecdh.setPrivateKey()` method attempts to generate the
470 public point/key associated with the private key being set.
472 Example (obtaining a shared secret):
474 const crypto = require('crypto');
475 const alice = crypto.createECDH('secp256k1');
476 const bob = crypto.createECDH('secp256k1');
478 // Note: This is a shortcut way to specify one of Alice's previous private
479 // keys. It would be unwise to use such a predictable private key in a real
482 crypto.createHash('sha256').update('alice', 'utf8').digest()
485 // Bob uses a newly generated cryptographically strong
486 // pseudorandom key pair bob.generateKeys();
488 const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
489 const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
491 /* alice_secret and bob_secret should be the same */
492 console.log(alice_secret == bob_secret);
494 ### ECDH.setPublicKey(public_key[, encoding])
496 Sets the EC Diffie-Hellman public key. Key encoding can be `'binary'`,
497 `'hex'` or `'base64'`. If no encoding is provided, then a buffer is
502 The `Hash` class is a utility for creating hash digests of data. It can be
503 used in one of two ways:
505 - As a [stream][] that is both readable and writable, where data is written
506 to produce a computed hash digest on the readable side, or
507 - Using the `hash.update()` and `hash.final()` methods to produce the
510 The `crypto.createHash()` method is used to create `Hash` instances. `Hash`
511 objects are not to be created directly using the `new` keyword.
513 Example: Using `Hash` objects as streams:
515 const crypto = require('crypto');
516 const hash = crypto.createHash('sha256');
518 hash.on('readable', () => {
519 var data = hash.read();
521 console.log(data.toString('hex'));
523 // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
526 hash.write('some data to hash');
529 Example: Using `Hash` and piped streams:
531 const crypto = require('crypto');
532 const fs = require('fs');
533 const hash = crypto.createHash('sha256');
535 const input = fs.createReadStream('test.js');
536 input.pipe(hash).pipe(process.stdout);
538 Example: Using the `hash.update()` and `hash.digest()` methods:
540 const crypto = require('crypto');
541 const hash = crypto.createHash('sha256');
543 hash.update('some data to hash');
544 console.log(hash.digest('hex'));
546 // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
548 ### hash.digest([encoding])
550 Calculates the digest of all of the data passed to be hashed (using the
551 `hash.update()` method). The `encoding` can be `'hex'`, `'binary'` or
552 `'base64'`. If `encoding` is provided a string will be returned; otherwise
553 a [`Buffer`][] is returned.
555 The `Hash` object can not be used again after `hash.digest()` method has been
556 called. Multiple calls will cause an error to be thrown.
558 ### hash.update(data[, input_encoding])
560 Updates the hash content with the given `data`, the encoding of which
561 is given in `input_encoding` and can be `'utf8'`, `'ascii'` or
562 `'binary'`. If `encoding` is not provided, and the `data` is a string, an
563 encoding of `'binary'` is enforced. If `data` is a [`Buffer`][] then
564 `input_encoding` is ignored.
566 This can be called many times with new data as it is streamed.
570 The `Hmac` Class is a utility for creating cryptographic HMAC digests. It can
571 be used in one of two ways:
573 - As a [stream][] that is both readable and writable, where data is written
574 to produce a computed HMAC digest on the readable side, or
575 - Using the `hmac.update()` and `hmac.final()` methods to produce the
576 computed HMAC digest.
578 The `crypto.createHmac()` method is used to create `Hmac` instances. `Hmac`
579 objects are not to be created directly using the `new` keyword.
581 Example: Using `Hmac` objects as streams:
583 const crypto = require('crypto');
584 const hmac = crypto.createHmac('sha256', 'a secret');
586 hmac.on('readable', () => {
587 var data = hmac.read();
589 console.log(data.toString('hex'));
591 // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
594 hmac.write('some data to hash');
597 Example: Using `Hmac` and piped streams:
599 const crypto = require('crypto');
600 const fs = require('fs');
601 const hmac = crypto.createHmac('sha256', 'a secret');
603 const input = fs.createReadStream('test.js');
604 input.pipe(hmac).pipe(process.stdout);
606 Example: Using the `hmac.update()` and `hmac.digest()` methods:
608 const crypto = require('crypto');
609 const hmac = crypto.createHmac('sha256', 'a secret');
611 hmac.update('some data to hash');
612 console.log(hmac.digest('hex'));
614 // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
616 ### hmac.digest([encoding])
618 Calculates the HMAC digest of all of the data passed using `hmac.update()`. The
619 `encoding` can be `'hex'`, `'binary'` or `'base64'`. If `encoding` is provided
620 a string is returned; otherwise a [`Buffer`][] is returned;
622 The `Hmac` object can not be used again after `hmac.digest()` has been
623 called. Multiple calls to `hmac.digest()` will result in an error being thrown.
625 ### hmac.update(data)
627 Update the `Hmac` content with the given `data`. This can be called
628 many times with new data as it is streamed.
632 The `Sign` Class is a utility for generating signatures. It can be used in one
635 - As a writable [stream][], where data to be signed is written and the
636 `sign.sign()` method is used to generate and return the signature, or
637 - Using the `sign.update()` and `sign.sign()` methods to produce the
640 The `crypto.createSign()` method is used to create `Sign` instances. `Sign`
641 objects are not to be created directly using the `new` keyword.
643 Example: Using `Sign` objects as streams:
645 const crypto = require('crypto');
646 const sign = crypto.createSign('rsa-sha256');
648 sign.write('some data to sign');
651 const private_key = getPrivateKeySomehow();
652 console.log(sign.sign(private_key, 'hex'));
653 // Prints the calculated signature
655 Example: Using the `sign.update()` and `sign.sign()` methods:
657 const crypto = require('crypto');
658 const sign = crypto.createSign('rsa-sha256');
660 sign.update('some data to sign');
662 const private_key = getPrivateKeySomehow();
663 console.log(sign.sign(private_key, 'hex'));
664 // Prints the calculated signature
666 ### sign.sign(private_key[, output_format])
668 Calculates the signature on all the data passed through using either
669 `sign.update()` or `sign.write()`.
671 The `private_key` argument can be an object or a string. If `private_key` is a
672 string, it is treated as a raw key with no passphrase. If `private_key` is an
673 object, it is interpreted as a hash containing two properties:
675 * `key` : A string holding the PEM encoded private key
676 * `passphrase` : A string of passphrase for the private key
678 The `output_format` can specify one of `'binary'`, `'hex'` or `'base64'`. If
679 `output_format` is provided a string is returned; otherwise a [`Buffer`][] is
682 The `Sign` object can not be again used after `sign.sign()` method has been
683 called. Multiple calls to `sign.sign()` will result in an error being thrown.
685 ### sign.update(data)
687 Updates the sign object with the given `data`. This can be called many times
688 with new data as it is streamed.
692 The `Verify` class is a utility for verifying signatures. It can be used in one
695 - As a writable [stream][] where written data is used to validate against the
696 supplied signature, or
697 - Using the `verify.update()` and `verify.verify()` methods to verify the
700 The `crypto.createSign()` method is used to create `Sign` instances. `Sign`
701 objects are not to be created directly using the `new` keyword.
703 Example: Using `Verify` objects as streams:
705 const crypto = require('crypto');
706 const verify = crypto.createVerify('rsa-sha256');
708 verify.write('some data to sign');
711 const public_key = getPublicKeySomehow();
712 const signature = getSignatureToVerify();
713 console.log(sign.verify(public_key, signature));
714 // Prints true or false
716 Example: Using the `verify.update()` and `verify.verify()` methods:
718 const crypto = require('crypto');
719 const verify = crypto.createVerify('rsa-sha256');
721 verify.update('some data to sign');
723 const public_key = getPublicKeySomehow();
724 const signature = getSignatureToVerify();
725 console.log(verify.verify(public_key, signature));
726 // Prints true or false
728 ### verifier.update(data)
730 Updates the verifier object with the given `data`. This can be called many
731 times with new data as it is streamed.
733 ### verifier.verify(object, signature[, signature_format])
735 Verifies the provided data using the given `object` and `signature`.
736 The `object` argument is a string containing a PEM encoded object, which can be
737 one an RSA public key, a DSA public key, or an X.509 certificate.
738 The `signature` argument is the previously calculated signature for the data, in
739 the `signature_format` which can be `'binary'`, `'hex'` or `'base64'`.
740 If a `signature_format` is specified, the `signature` is expected to be a
741 string; otherwise `signature` is expected to be a [`Buffer`][].
743 Returns `true` or `false` depending on the validity of the signature for
744 the data and public key.
746 The `verifier` object can not be used again after `verify.verify()` has been
747 called. Multiple calls to `verify.verify()` will result in an error being
750 ## `crypto` module methods and properties
752 ### crypto.DEFAULT_ENCODING
754 The default encoding to use for functions that can take either strings
755 or [buffers][]. The default value is `'buffer'`, which makes methods default
756 to [`Buffer`][] objects.
758 The `crypto.DEFAULT_ENCODING` mechanism is provided for backwards compatibility
759 with legacy programs that expect `'binary'` to be the default encoding.
761 New applications should expect the default to be `'buffer'`. This property may
762 become deprecated in a future Node.js release.
764 ### crypto.createCipher(algorithm, password)
766 Creates and returns a `Cipher` object that uses the given `algorithm` and
769 The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
770 recent OpenSSL releases, `openssl list-cipher-algorithms` will display the
771 available cipher algorithms.
773 The `password` is used to derive the cipher key and initialization vector (IV).
774 The value must be either a `'binary'` encoded string or a [`Buffer`[].
776 The implementation of `crypto.createCipher()` derives keys using the OpenSSL
777 function [`EVP_BytesToKey`][] with the digest algorithm set to MD5, one
778 iteration, and no salt. The lack of salt allows dictionary attacks as the same
779 password always creates the same key. The low iteration count and
780 non-cryptographically secure hash algorithm allow passwords to be tested very
783 In line with OpenSSL's recommendation to use pbkdf2 instead of
784 [`EVP_BytesToKey`][] it is recommended that developers derive a key and IV on
785 their own using [`crypto.pbkdf2`][] and to use [`crypto.createCipheriv()`][]
786 to create the `Cipher` object.
788 ### crypto.createCipheriv(algorithm, key, iv)
790 Creates and returns a `Cipher` object, with the given `algorithm`, `key` and
791 initialization vector (`iv`).
793 The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
794 recent OpenSSL releases, `openssl list-cipher-algorithms` will display the
795 available cipher algorithms.
797 The `key` is the raw key used by the `algorithm` and `iv` is an
798 [initialization vector][]. Both arguments must be `'binary'` encoded strings or
801 ### crypto.createCredentials(details)
803 Stability: 0 - Deprecated: Use [`tls.createSecureContext`][] instead.
805 The `crypto.createCredentials()` method is a deprecated alias for creating
806 and returning a `tls.SecureContext` object. The `crypto.createCredentials()`
807 method should not be used.
809 The optional `details` argument is a hash object with keys:
811 * `pfx` : A string or [`Buffer`][] holding the PFX or PKCS12 encoded private
812 key, certificate and CA certificates
813 * `key` : A string holding the PEM encoded private key
814 * `passphrase` : The string passphrase for the private key or PFX
815 * `cert` : A string holding the PEM encoded certificate
816 * `ca` : Either a string or array of strings of PEM encoded CA
817 certificates to trust.
818 * `crl` : Either a string or array of strings of PEM encoded CRLs
819 (Certificate Revocation List)
820 * `ciphers`: A string using the [OpenSSL cipher list format][] describing the
821 cipher algorithms to use or exclude.
823 If no 'ca' details are given, Node.js will use Mozilla's default
824 [publicly trusted list of CAs][].
826 ### crypto.createDecipher(algorithm, password)
828 Creates and returns a `Decipher` object that uses the given `algorithm` and
831 The implementation of `crypto.createDecipher()` derives keys using the OpenSSL
832 function [`EVP_BytesToKey`][] with the digest algorithm set to MD5, one
833 iteration, and no salt. The lack of salt allows dictionary attacks as the same
834 password always creates the same key. The low iteration count and
835 non-cryptographically secure hash algorithm allow passwords to be tested very
838 In line with OpenSSL's recommendation to use pbkdf2 instead of
839 [`EVP_BytesToKey`][] it is recommended that developers derive a key and IV on
840 their own using [`crypto.pbkdf2`][] and to use [`crypto.createDecipheriv()`][]
841 to create the `Decipher` object.
843 ### crypto.createDecipheriv(algorithm, key, iv)
845 Creates and returns a `Decipher` object that uses the given `algorithm`, `key`
846 and initialization vector (`iv`).
848 The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On
849 recent OpenSSL releases, `openssl list-cipher-algorithms` will display the
850 available cipher algorithms.
852 The `key` is the raw key used by the `algorithm` and `iv` is an
853 [initialization vector][]. Both arguments must be `'binary'` encoded strings or
856 ## crypto.createDiffieHellman(prime[, prime_encoding][, generator][, generator_encoding])
858 Creates a `DiffieHellman` key exchange object using the supplied `prime` and an
859 optional specific `generator`.
861 The `generator` argument can be a number, string, or [`Buffer`][]. If
862 `generator` is not specified, the value `2` is used.
864 The `prime_encoding` and `generator_encoding` arguments can be `'binary'`,
865 `'hex'`, or `'base64'`.
867 If `prime_encoding` is specified, `prime` is expected to be a string; otherwise
868 a [`Buffer`][] is expected.
870 If `generator_encoding` is specified, `generator` is expected to be a string;
871 otherwise either a number or [`Buffer`][] is expected.
873 ### crypto.createDiffieHellman(prime_length[, generator])
875 Creates a `DiffieHellman` key exchange object and generates a prime of
876 `prime_length` bits using an optional specific numeric `generator`.
877 If `generator` is not specified, the value `2` is used.
879 ### crypto.createECDH(curve_name)
881 Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a
882 predefined curve specified by the `curve_name` string. Use
883 [`crypto.getCurves()`][] to obtain a list of available curve names. On recent
884 OpenSSL releases, `openssl ecparam -list_curves` will also display the name
885 and description of each available elliptic curve.
887 ### crypto.createHash(algorithm)
889 Creates and returns a `Hash` object that can be used to generate hash digests
890 using the given `algorithm`.
892 The `algorithm` is dependent on the available algorithms supported by the
893 version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
894 On recent releases of OpenSSL, `openssl list-message-digest-algorithms` will
895 display the available digest algorithms.
897 Example: generating the sha256 sum of a file
899 const filename = process.argv[2];
900 const crypto = require('crypto');
901 const fs = require('fs');
903 const hash = crypto.createHash('sha256');
905 const input = fs.createReadStream(filename);
906 input.on('readable', () => {
907 var data = input.read();
911 console.log(`${hash.digest('hex')} ${filename}`);
915 ### crypto.createHmac(algorithm, key)
917 Creates and returns an `Hmac` object that uses the given `algorithm` and `key`.
919 The `algorithm` is dependent on the available algorithms supported by the
920 version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc.
921 On recent releases of OpenSSL, `openssl list-message-digest-algorithms` will
922 display the available digest algorithms.
924 The `key` is the HMAC key used to generate the cryptographic HMAC hash.
926 Example: generating the sha256 HMAC of a file
928 const filename = process.argv[2];
929 const crypto = require('crypto');
930 const fs = require('fs');
932 const hmac = crypto.createHmac('sha256', 'a secret');
934 const input = fs.createReadStream(filename);
935 input.on('readable', () => {
936 var data = input.read();
940 console.log(`${hmac.digest('hex')} ${filename}`);
944 ### crypto.createSign(algorithm)
946 Creates and returns a `Sign` object that uses the given `algorithm`. On
947 recent OpenSSL releases, `openssl list-public-key-algorithms` will
948 display the available signing algorithms. One example is `'RSA-SHA256'`.
950 ### crypto.createVerify(algorithm)
952 Creates and returns a `Verify` object that uses the given algorithm. On
953 recent OpenSSL releases, `openssl list-public-key-algorithms` will
954 display the available signing algorithms. One example is `'RSA-SHA256'`.
956 ### crypto.getCiphers()
958 Returns an array with the names of the supported cipher algorithms.
962 const ciphers = crypto.getCiphers();
963 console.log(ciphers); // ['aes-128-cbc', 'aes-128-ccm', ...]
965 ### crypto.getCurves()
967 Returns an array with the names of the supported elliptic curves.
971 const curves = crypto.getCurves();
972 console.log(curves); // ['secp256k1', 'secp384r1', ...]
974 ### crypto.getDiffieHellman(group_name)
976 Creates a predefined `DiffieHellman` key exchange object. The
977 supported groups are: `'modp1'`, `'modp2'`, `'modp5'` (defined in
978 [RFC 2412][], but see [Caveats][]) and `'modp14'`, `'modp15'`,
979 `'modp16'`, `'modp17'`, `'modp18'` (defined in [RFC 3526][]). The
980 returned object mimics the interface of objects created by
981 [`crypto.createDiffieHellman()`][], but will not allow changing
982 the keys (with [`diffieHellman.setPublicKey()`][] for example). The
983 advantage of using this method is that the parties do not have to
984 generate nor exchange a group modulus beforehand, saving both processor
985 and communication time.
987 Example (obtaining a shared secret):
989 const crypto = require('crypto');
990 const alice = crypto.getDiffieHellman('modp14');
991 const bob = crypto.getDiffieHellman('modp14');
993 alice.generateKeys();
996 const alice_secret = alice.computeSecret(bob.getPublicKey(), null, 'hex');
997 const bob_secret = bob.computeSecret(alice.getPublicKey(), null, 'hex');
999 /* alice_secret and bob_secret should be the same */
1000 console.log(alice_secret == bob_secret);
1002 ### crypto.getHashes()
1004 Returns an array with the names of the supported hash algorithms.
1008 const hashes = crypto.getHashes();
1009 console.log(hashes); // ['sha', 'sha1', 'sha1WithRSAEncryption', ...]
1011 ### crypto.pbkdf2(password, salt, iterations, keylen[, digest], callback)
1013 Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2)
1014 implementation. A selected HMAC digest algorithm specified by `digest` is
1015 applied to derive a key of the requested byte length (`keylen`) from the
1016 `password`, `salt` and `iterations`. If the `digest` algorithm is not specified,
1017 a default of `'sha1'` is used.
1019 The supplied `callback` function is called with two arguments: `err` and
1020 `derivedKey`. If an error occurs, `err` will be set; otherwise `err` will be
1021 null. The successfully generated `derivedKey` will be passed as a [`Buffer`][].
1023 The `iterations` argument must be a number set as high as possible. The
1024 higher the number of iterations, the more secure the derived key will be,
1025 but will take a longer amount of time to complete.
1027 The `salt` should also be as unique as possible. It is recommended that the
1028 salts are random and their lengths are greater than 16 bytes. See
1029 [NIST SP 800-132][] for details.
1033 const crypto = require('crypto');
1034 crypto.pbkdf2('secret', 'salt', 100000, 512, 'sha512', (err, key) => {
1036 console.log(key.toString('hex')); // 'c5e478d...1469e50'
1039 An array of supported digest functions can be retrieved using
1040 [`crypto.getHashes()`][].
1042 ### crypto.pbkdf2Sync(password, salt, iterations, keylen[, digest])
1044 Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2)
1045 implementation. A selected HMAC digest algorithm specified by `digest` is
1046 applied to derive a key of the requested byte length (`keylen`) from the
1047 `password`, `salt` and `iterations`. If the `digest` algorithm is not specified,
1048 a default of `'sha1'` is used.
1050 If an error occurs an Error will be thrown, otherwise the derived key will be
1051 returned as a [`Buffer`][].
1053 The `iterations` argument must be a number set as high as possible. The
1054 higher the number of iterations, the more secure the derived key will be,
1055 but will take a longer amount of time to complete.
1057 The `salt` should also be as unique as possible. It is recommended that the
1058 salts are random and their lengths are greater than 16 bytes. See
1059 [NIST SP 800-132][] for details.
1063 const crypto = require('crypto');
1064 const key = crypto.pbkdf2sync('secret', 'salt', 100000, 512, 'sha512');
1065 console.log(key.toString('hex')); // 'c5e478d...1469e50'
1067 An array of supported digest functions can be retrieved using
1068 [`crypto.getHashes()`][].
1070 ### crypto.privateDecrypt(private_key, buffer)
1072 Decrypts `buffer` with `private_key`.
1074 `private_key` can be an object or a string. If `private_key` is a string, it is
1075 treated as the key with no passphrase and will use `RSA_PKCS1_OAEP_PADDING`.
1076 If `private_key` is an object, it is interpreted as a hash object with the
1079 * `key` : A string holding the PEM encoded private key
1080 * `passphrase` : An optional string of passphrase for the private key
1081 * `padding` : An optional padding value, one of the following:
1082 * `constants.RSA_NO_PADDING`
1083 * `constants.RSA_PKCS1_PADDING`
1084 * `constants.RSA_PKCS1_OAEP_PADDING`
1086 All paddings are defined in the `constants` module.
1088 ### crypto.privateEncrypt(private_key, buffer)
1090 Encrypts `buffer` with `private_key`.
1092 `private_key` can be an object or a string. If `private_key` is a string, it is
1093 treated as the key with no passphrase and will use `RSA_PKCS1_PADDING`.
1094 If `private_key` is an object, it is interpreted as a hash object with the
1097 * `key` : A string holding the PEM encoded private key
1098 * `passphrase` : An optional string of passphrase for the private key
1099 * `padding` : An optional padding value, one of the following:
1100 * `constants.RSA_NO_PADDING`
1101 * `constants.RSA_PKCS1_PADDING`
1102 * `constants.RSA_PKCS1_OAEP_PADDING`
1104 All paddings are defined in the `constants` module.
1106 ### crypto.publicDecrypt(public_key, buffer)
1108 Decrypts `buffer` with `public_key`.
1110 `public_key` can be an object or a string. If `public_key` is a string, it is
1111 treated as the key with no passphrase and will use `RSA_PKCS1_PADDING`.
1112 If `public_key` is an object, it is interpreted as a hash object with the
1115 * `key` : A string holding the PEM encoded public key
1116 * `passphrase` : An optional string of passphrase for the private key
1117 * `padding` : An optional padding value, one of the following:
1118 * `constants.RSA_NO_PADDING`
1119 * `constants.RSA_PKCS1_PADDING`
1120 * `constants.RSA_PKCS1_OAEP_PADDING`
1122 Because RSA public keys can be derived from private keys, a private key may
1123 be passed instead of a public key.
1125 All paddings are defined in the `constants` module.
1127 ### crypto.publicEncrypt(public_key, buffer)
1129 Encrypts `buffer` with `public_key`.
1131 `public_key` can be an object or a string. If `public_key` is a string, it is
1132 treated as the key with no passphrase and will use `RSA_PKCS1_OAEP_PADDING`.
1133 If `public_key` is an object, it is interpreted as a hash object with the
1136 * `key` : A string holding the PEM encoded public key
1137 * `passphrase` : An optional string of passphrase for the private key
1138 * `padding` : An optional padding value, one of the following:
1139 * `constants.RSA_NO_PADDING`
1140 * `constants.RSA_PKCS1_PADDING`
1141 * `constants.RSA_PKCS1_OAEP_PADDING`
1143 Because RSA public keys can be derived from private keys, a private key may
1144 be passed instead of a public key.
1146 All paddings are defined in the `constants` module.
1148 ### crypto.randomBytes(size[, callback])
1150 Generates cryptographically strong pseudo-random data. The `size` argument
1151 is a number indicating the number of bytes to generate.
1153 If a `callback` function is provided, the bytes are generated asynchronously
1154 and the `callback` function is invoked with two arguments: `err` and `buf`.
1155 If an error occurs, `err` will be an Error object; otherwise it is null. The
1156 `buf` argument is a [`Buffer`][] containing the generated bytes.
1159 const crypto = require('crypto');
1160 crypto.randomBytes(256, (err, buf) => {
1163 `${buf.length}` bytes of random data: ${buf.toString('hex')});
1166 If the `callback` function is not provided, the random bytes are generated
1167 synchronously and returned as a [`Buffer`][]. An error will be thrown if
1168 there is a problem generating the bytes.
1171 const buf = crypto.randomBytes(256);
1173 `${buf.length}` bytes of random data: ${buf.toString('hex')});
1175 The `crypto.randomBytes()` method will block until there is sufficient entropy.
1176 This should normally never take longer than a few milliseconds. The only time
1177 when generating the random bytes may conceivably block for a longer period of
1178 time is right after boot, when the whole system is still low on entropy.
1180 ### crypto.setEngine(engine[, flags])
1182 Load and set the `engine` for some or all OpenSSL functions (selected by flags).
1184 `engine` could be either an id or a path to the engine's shared library.
1186 The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags`
1187 is a bit field taking one of or a mix of the following flags (defined in the
1188 `constants` module):
1190 * `ENGINE_METHOD_RSA`
1191 * `ENGINE_METHOD_DSA`
1192 * `ENGINE_METHOD_DH`
1193 * `ENGINE_METHOD_RAND`
1194 * `ENGINE_METHOD_ECDH`
1195 * `ENGINE_METHOD_ECDSA`
1196 * `ENGINE_METHOD_CIPHERS`
1197 * `ENGINE_METHOD_DIGESTS`
1198 * `ENGINE_METHOD_STORE`
1199 * `ENGINE_METHOD_PKEY_METH`
1200 * `ENGINE_METHOD_PKEY_ASN1_METH`
1201 * `ENGINE_METHOD_ALL`
1202 * `ENGINE_METHOD_NONE`
1206 ### Legacy Streams API (pre Node.js v0.10)
1208 The Crypto module was added to Node.js before there was the concept of a
1209 unified Stream API, and before there were [`Buffer`][] objects for handling
1210 binary data. As such, the many of the `crypto` defined classes have methods not
1211 typically found on other Node.js classes that implement the [streams][]
1212 API (e.g. `update()`, `final()`, or `digest()`). Also, many methods accepted
1213 and returned `'binary'` encoded strings by default rather than Buffers. This
1214 default was changed after Node.js v0.8 to use [`Buffer`][] objects by default
1217 ### Recent ECDH Changes
1219 Usage of `ECDH` with non-dynamically generated key pairs has been simplified.
1220 Now, `ecdh.setPrivateKey()` can be called with a preselected private key and the
1221 associated public point (key) will be computed and stored in the object.
1222 This allows code to only store and provide the private part of the EC key pair.
1223 `ecdh.setPrivateKey()` now also validates that the private key is valid for the
1226 The `ecdh.setPublicKey()` method is now deprecated as its inclusion in the API
1227 is not useful. Either a previously stored private key should be set, which
1228 automatically generates the associated public key, or `ecdh.generateKeys()`
1229 should be called. The main drawback of using `ecdh.setPublicKey()` is that it
1230 can be used to put the ECDH key pair into an inconsistent state.
1232 ### Support for weak or compromised algorithms
1234 The `crypto` module still supports some algorithms which are already
1235 compromised and are not currently recommended for use. The API also allows
1236 the use of ciphers and hashes with a small key size that are considered to be
1237 too weak for safe use.
1239 Users should take full responsibility for selecting the crypto
1240 algorithm and key size according to their security requirements.
1242 Based on the recommendations of [NIST SP 800-131A][]:
1244 - MD5 and SHA-1 are no longer acceptable where collision resistance is
1245 required such as digital signatures.
1246 - The key used with RSA, DSA and DH algorithms is recommended to have
1247 at least 2048 bits and that of the curve of ECDSA and ECDH at least
1248 224 bits, to be safe to use for several years.
1249 - The DH groups of `modp1`, `modp2` and `modp5` have a key size
1250 smaller than 2048 bits and are not recommended.
1252 See the reference for other recommendations and details.
1254 [HTML5's `keygen` element]: http://www.w3.org/TR/html5/forms.html#the-keygen-element
1255 [OpenSSL's SPKAC implementation]: https://www.openssl.org/docs/apps/spkac.html
1256 [`createCipher()`]: #crypto_crypto_createcipher_algorithm_password
1257 [`createCipheriv()`]: #crypto_crypto_createcipheriv_algorithm_key_iv
1258 [`createHash()`]: #crypto_crypto_createhash_algorithm
1259 [`crypto.createDecipher`]: #crypto_crypto_createdecipher_algorithm_password
1260 [`crypto.createDecipheriv`]: #crypto_crypto_createdecipheriv_algorithm_key_iv
1261 [`crypto.createDiffieHellman()`]: #crypto_crypto_creatediffiehellman_prime_prime_encoding_generator_generator_encoding
1262 [`crypto.getHashes()`]: #crypto_crypto_gethashes
1263 [`crypto.pbkdf2`]: #crypto_crypto_pbkdf2_password_salt_iterations_keylen_digest_callback
1264 [`decipher.update`]: #crypto_decipher_update_data_input_encoding_output_encoding
1265 [`diffieHellman.setPublicKey()`]: #crypto_diffiehellman_setpublickey_public_key_encoding
1266 [`EVP_BytesToKey`]: https://www.openssl.org/docs/crypto/EVP_BytesToKey.html
1267 [`getCurves()`]: #crypto_crypto_getcurves
1268 [`tls.createSecureContext`]: tls.html#tls_tls_createsecurecontext_details
1269 [`Buffer`]: buffer.html
1270 [buffers]: buffer.html
1271 [Caveats]: #crypto_support_for_weak_or_compromised_algorithms
1272 [initialization vector]: https://en.wikipedia.org/wiki/Initialization_vector
1273 [NIST SP 800-131A]: http://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-131Ar1.pdf
1274 [NIST SP 800-132]: http://csrc.nist.gov/publications/nistpubs/800-132/nist-sp800-132.pdf
1275 [RFC 2412]: https://www.rfc-editor.org/rfc/rfc2412.txt
1276 [RFC 3526]: https://www.rfc-editor.org/rfc/rfc3526.txt
1277 [stream]: stream.html
1278 [streams]: stream.html
1279 [OpenSSL cipher list format]: https://www.openssl.org/docs/apps/ciphers.html#CIPHER_LIST_FORMAT
1280 [publicly trusted list of CAs]: https://mxr.mozilla.org/mozilla/source/security/nss/lib/ckfw/builtins/certdata.txt