2 - Unstable

The crypto module offers a way of encapsulating secure credentials to be used as part of a secure HTTPS net or HTTP connection. To access this module, add require('crypto') to your code.

The module also offers a set of wrappers for OpenSSL's methods, which actually contains these objects:

This documentation is organized to describe those objects within their own sections.

Note:

All algorithm parameter implementations below are dependent on the OpenSSL version installed on the platform. Some common examples of these algoritihms are 'sha1', 'md5', 'sha256', and 'sha512'. On recent Node.js releases, openssl list-message-digest-algorithms displays the available digest algorithms.

Example

Proposed API Changes in Future Versions of Node

The Crypto module was added to Node before there was the concept of a unified Stream API, and before there were Buffer objects for handling binary data.

As such, the streaming classes don't have the typical methods found on other Node classes, and many methods accept and return Binary-encoded strings by default rather than Buffers.

A future version of node will make Buffers the default data type. This will be a breaking change for some use cases, but not all.

For example, if you currently use the default arguments to the Sign class, and then pass the results to the Verify class, without ever inspecting the data, then it will continue to work as before. Where you now get a binary string and then present the binary string to the Verify object, you'll get a Buffer, and present the Buffer to the Verify object.

However, if you are doing things with the string data that will not work properly on Buffers (such as, concatenating them, storing in databases, etc.), or you are passing binary strings to the crypto functions without an encoding argument, then you will need to start providing encoding arguments to specify which encoding you'd like to use.

Also, a Streaming API will be provided, but this will be done in such a way as to preserve the legacy API surface.

Methods

Creates and returns a cipher object with the given algorithm and password.

   

Creates and returns a cipher object with the given algorithm and password.

The password is used to derive both the key and IV, which must be a 'binary'-encoded string, or a buffer.

Arguments

algorithmString

Required. The algorithm to use

passwordString

Required. The password to use

Creates and returns a cipher object, with the given algorithm, key, and IV.

   

Creates and returns a cipher object, with the given algorithm, key, and IV.

key and iv must be 'binary'-encoded strings or a buffer.

Arguments

algorithmString

Required. The algorithm to use (same as the argument in createCipher())

keyString

Required. A raw key used by the algorithm

ivString

Required. The initialization vector

Creates a credentials object, with details being a dictionary with the following keys:

   

Creates a credentials object, with details being a dictionary with the following keys:

  • pfx: A string or buffer holding the PFX or PKCS12 encoded private key, certificate, and CA certificates
  • key: A string holding the PEM encoded private key file
  • cert: A string holding the PEM encoded certificate file
  • passphrase: A string of passphrases for the private key or pfx
  • ca: Either a string or list of strings of PEM encoded CA certificates to trust
  • crl : Either a string or list of strings of PEM encoded CRLs (Certificate Revocation List)
  • ciphers: A string describing the ciphers to use or exclude. Consult OpenSSL.org for details on the format

If no ca details are given, then Node.js uses the default publicly trusted list of CAs as given by Mozilla.

Example

Arguments

detailsString

Required. A dictionary of fields to populate the credential with

Creates and returns a decipher object, with the given algorithm and key.

   

Creates and returns a decipher object, with the given algorithm and key.

Arguments

algorithmString

Required. The algorithm to use

passwordString

Required. The password to use

Creates a Diffie-Hellman key exchange object and generates a prime of the given bit length. The generator used is 2.

   

Creates a Diffie-Hellman key exchange object and generates a prime of the given bit length. The generator used is 2.

Example

Arguments

prime_lengthNumber

Required. The bit length to calculate with

primeNumber

Required. The prime to calculate with

encodingNumber

Required. The encoding to use; defaults to 'binary'

Creates and returns a cryptographic hash object with the given algorithm. The object can be used to generate hash digests.

   

Creates and returns a cryptographic hash object with the given algorithm. The object can be used to generate hash digests.

Examples

Testing an MD5 Hash:

This program takes the sha1 sum of a file:

var filename = "my_secret_file.txt";
var crypto = require('crypto');
var fs = require('fs');

var shasum = crypto.createHash('sha1');

var s = fs.ReadStream(filename);
s.on('data', function(d) {
  shasum.update(d);
});

s.on('end', function() {
  var d = shasum.digest('hex');
  console.log(d + '  ' + filename);
});

Arguments

algorithmString

Required. The hash algorithm to use

Creates and returns a cryptographic HMAC object with the given algorithm and key. For more information on HMAC, see this article.

   

Creates and returns a cryptographic HMAC object with the given algorithm and key. For more information on HMAC, see this article.

Example

Arguments

algorithmString

Required. The algorithm to use

keyString

Required. The HMAC key to be used

Creates and returns a signing object string, with the given algorithm.

   

Creates and returns a signing object string, with the given algorithm.

Arguments

algorithmString

Required. The algorithm to use

Creates and returns a verification object, with the given algorithm.

   

Creates and returns a verification object, with the given algorithm.

This is the mirror of the signer object.

Arguments

algorithmString

Required. The algorithm to use

Creates a predefined Diffie-Hellman key exchange object.

   

Creates a predefined Diffie-Hellman key exchange object.

The returned object mimics the interface of objects created by createDiffieHellman(), but will not allow you to change the keys (for example, with diffieHellman.setPublicKey()).

The advantage of using this routine is that the parties don't have to generate nor exchange group modulus beforehand, saving both processor and communication time.

Example: Obtaining a shared secret:

var crypto = require('crypto');
var alice = crypto.getDiffieHellman('modp5');
var bob = crypto.getDiffieHellman('modp5');

alice.generateKeys();
bob.generateKeys();

var alice_secret = alice.computeSecret(bob.getPublicKey(), 'binary', 'hex');
var bob_secret = bob.computeSecret(alice.getPublicKey(), 'binary', 'hex');

/* alice_secret and bob_secret should be the same */
console.log(alice_secret == bob_secret);

Arguments

group_nameString

Required. One of the following group names:

An asynchronous PBKDF2 function that applies pseudorandom function HMAC-SHA1 to derive a key of the given length from the given password, salt, and number of iterations.

   

An asynchronous PBKDF2 function that applies pseudorandom function HMAC-SHA1 to derive a key of the given length from the given password, salt, and number of iterations.

Example

Arguments

passwordString

Required. The password to use

saltString

Required. The salt to use

iterationsString

Required. The number of iterations to use

keylenString

Required. The final key length

callbackFunction

Required. The callback to execute when finished

errError

Required. The error object

derivedKeyString

Required. The resulting key

Generates cryptographically strong pseudo-random data, either asynchronously or synchronously.

   

Generates cryptographically strong pseudo-random data, either asynchronously or synchronously.

Example

Arguments

sizeNumber

Required. The size of the cryptographic data

callbackFunction

Required. The callback to execute when finished

exError

Required. The error object

bufString

Required. The resulting crypto data

Methods

    • crypto.cipher.final([String output_encoding = "binary"])

Returns any remaining enciphered contents. output_encoding can be 'binary', 'base64', or 'hex'.

   

Returns any remaining enciphered contents. output_encoding can be 'binary', 'base64', or 'hex'.

Note:

The cipher object can't be used after the final() method has been called.

Arguments

output_encodingString

Required. The encoding to use for the output; defaults to

*binary

    • crypto.cipher.setAutoPadding(Boolean auto_padding = true)

You can disable automatic padding of the input data to block size.

   

You can disable automatic padding of the input data to block size.

If auto_padding is false, the length of the entire input data must be a multiple of the cipher's block size or final will fail.

This is useful for non-standard padding, e.g. using 0x0 instead of PKCS padding. You must call this before cipher.final.

Arguments

auto_paddingBoolean

Required. Specifies wheter automatic padding is on, or not

Updates the cipher with data. This returns the enciphered contents, and can be called many times with new data as it is streamed.

   

Updates the cipher with data. This returns the enciphered contents, and can be called many times with new data as it is streamed.

Arguments

dataString

Required. The data to use for an update

input_encodingString

Required. Defines how the input is encoded; can be 'utf8',

*'ascii' or 'binary'

output_encodingString

Required. Defines how the output is encoded; can be

*'binary', 'base64' or 'hex'

Methods

    • crypto.decipher.final([String output_encoding = "binary"])

Returns any remaining plaintext which is deciphered.

   

Returns any remaining plaintext which is deciphered.

Note:

The decipher object can't be used after the final() method been called.

Arguments

output_encodingString

Required. The encoding to use for the output; can be either

*'binary', 'ascii', or 'utf8'

    • crypto.decipher.setAutoPadding(Boolean auto_padding = true)

You can disable auto padding if the data has been encrypted without standard block padding to prevent decipher.final from checking and removing it. Can only work if the input data's length is a multiple of the ciphers block size. You must call this before streaming data to decipher.update.

   

You can disable auto padding if the data has been encrypted without standard block padding to prevent decipher.final from checking and removing it. Can only work if the input data's length is a multiple of the ciphers block size. You must call this before streaming data to decipher.update.

Arguments

auto_paddingBoolean

Required. Specifies wheter automatic padding is on, or not

Updates the decipher with data.

   

Updates the decipher with data.

The input_encoding can be 'binary', 'base64' or 'hex'. The output_encoding can be 'binary', 'ascii' or 'utf8'.

Arguments

dataString

Required. The data to use for an update

input_encodingString

Required. Defines how the input is encoded

output_encodingString

Required. Defines how the output is encoded

Methods

    • crypto.diffieHellman.computeSecret(String other_public_key[, String input_encoding = "binary"][, String output_encoding = "input_encoding"])

Computes the shared secret and returns the computed shared secret.

   

Computes the shared secret and returns the computed shared secret.

Arguments

other_public_keyString

Required. The other party's public key

input_encodingString

Required. The encoding used to interprate the public key; can

*be 'binary', 'base64', or 'hex'.

output_encodingString

Required. The encoding of the returned computation; defaults

*to the input_encoding

    • crypto.diffieHellman.generateKeys([String encoding = "binary"])

Generates private and public Diffie-Hellman key values, and returns the public key in the specified encoding. This key should be transferred to the other party.

   

Generates private and public Diffie-Hellman key values, and returns the public key in the specified encoding. This key should be transferred to the other party.

Arguments

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

    • crypto.diffieHellman.getGenerator([String encoding = "binary"])

Returns the Diffie-Hellman prime in the specified encoding.

   

Returns the Diffie-Hellman prime in the specified encoding.

Example

Arguments

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

    • crypto.diffieHellman.getPrime([String encoding = "binary"])

Returns the Diffie-Hellman prime in the specified encoding.

   

Returns the Diffie-Hellman prime in the specified encoding.

Example

Arguments

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

    • crypto.diffieHellman.getPrivateKey([String encoding = "binary"])

Returns the Diffie-Hellman private key in the specified encoding.

   

Returns the Diffie-Hellman private key in the specified encoding.

Arguments

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

    • crypto.diffieHellman.getPublicKey([String encoding = "binary"])

Returns the Diffie-Hellman public key in the specified encoding.

   

Returns the Diffie-Hellman public key in the specified encoding.

Arguments

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

    • crypto.diffieHellman.setPrivateKey(String public_key[, String encoding = "binary"])

Sets the Diffie-Hellman private key.

   

Sets the Diffie-Hellman private key.

Arguments

public_keyString

Required. The public key that's shared

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

    • crypto.diffieHellman.setPublicKey(String public_key[, String encoding = "binary"])

Sets the Diffie-Hellman public key.

   

Sets the Diffie-Hellman public key.

Arguments

public_keyString

Required. The public key that's shared

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

Methods

    • crypto.hash.digest([String encoding = "binary"])

Calculates the digest of all of the passed data to be hashed.

   

Calculates the digest of all of the passed data to be hashed.

Note:

The hash object can't be used after the digest() method been called.

Arguments

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

Updates the hash content with the given data. This can be called many times with new data as it is streamed.

   

Updates the hash content with the given data. This can be called many times with new data as it is streamed.

Arguments

dataString

Required. The data to use for an update

input_encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

Methods

Calculates the digest of all of the passed data to the hmac.

   

Calculates the digest of all of the passed data to the hmac.

Note:

The hmac object can't be used after the digest() method been called.

Arguments

encodingString

Required. The encoding to use; can be 'hex', 'binary' or

*'base64'

Update the HMAC content with the given data. This can be called many times with new data as it is streamed.

   

Update the HMAC content with the given data. This can be called many times with new data as it is streamed.

Arguments

dataString

Required. The data to use for an update

This class is used to generate certificates for OpenSSL. It can be created as a returned value from crypto.createSign().

Example

var s1 = crypto.createSign('RSA-SHA1')

         .update('Test123')
         .sign(keyPem, 'base64');

var verified = crypto.createVerify('RSA-SHA1')

               .update('Test')
               .update('123')
               .verify(certPem, s1, 'base64');

assert.strictEqual(verified, true, 'sign and verify (base 64)');

Methods

Calculates the signature on all the updated data passed through the signer.

   

Calculates the signature on all the updated data passed through the signer.

Note:

The signer object can not be used after the sign() method has been called.

Returns

The signature in a format defined by output_format.

Arguments

private_keyString

Required. A string containing the PEM encoded private key for

*signing

output_formatString

Required. The output encoding format; can be 'binary', 'hex'

*or 'base64'

Updates the signer object with data. This can be called many times with new data as it is streamed.

   

Updates the signer object with data. This can be called many times with new data as it is streamed.

Arguments

dataString

Required. The data to use for an update

crypto.verifier [edit]

This class is used to verify signed certificates for OpenSSL. It can be created as a returned value from crypto.createVerify().

Example

var s1 = crypto.createSign('RSA-SHA1')

         .update('Test123')
         .sign(keyPem, 'base64');

var verified = crypto.createVerify('RSA-SHA1')

               .update('Test')
               .update('123')
               .verify(certPem, s1, 'base64');

assert.strictEqual(verified, true, 'sign and verify (base 64)');

Methods

Updates the verifier object with data. This can be called many times with new data as it is streamed.

   

Updates the verifier object with data. This can be called many times with new data as it is streamed.

Arguments

dataString

Required. The data to use for an update

Returns true or false depending on the validity of the signature for the data and public key.

   

Returns true or false depending on the validity of the signature for the data and public key.

Note:

The verifier object can't be used after the verify() method has been called.

Arguments

objectString

Required. A string containing a PEM encoded object, which can be one of

*the following: an RSA public key, a DSA public key or an X.509 certificate

signatureString

Required. The previously calculated signature for the data

signature_formatString

Required. The format of the signature; can be 'binary',

*'hex', or 'base64'

Methods

    • crypto.cipher.final([String output_encoding = "binary"])

Returns any remaining enciphered contents. output_encoding can be 'binary', 'base64', or 'hex'.

   

Returns any remaining enciphered contents. output_encoding can be 'binary', 'base64', or 'hex'.

Note:

The cipher object can't be used after the final() method has been called.

Arguments

output_encodingString

Required. The encoding to use for the output; defaults to

*binary

    • crypto.cipher.setAutoPadding(Boolean auto_padding = true)

You can disable automatic padding of the input data to block size.

   

You can disable automatic padding of the input data to block size.

If auto_padding is false, the length of the entire input data must be a multiple of the cipher's block size or final will fail.

This is useful for non-standard padding, e.g. using 0x0 instead of PKCS padding. You must call this before cipher.final.

Arguments

auto_paddingBoolean

Required. Specifies wheter automatic padding is on, or not

Updates the cipher with data. This returns the enciphered contents, and can be called many times with new data as it is streamed.

   

Updates the cipher with data. This returns the enciphered contents, and can be called many times with new data as it is streamed.

Arguments

dataString

Required. The data to use for an update

input_encodingString

Required. Defines how the input is encoded; can be 'utf8',

*'ascii' or 'binary'

output_encodingString

Required. Defines how the output is encoded; can be

*'binary', 'base64' or 'hex'

Methods

    • crypto.decipher.final([String output_encoding = "binary"])

Returns any remaining plaintext which is deciphered.

   

Returns any remaining plaintext which is deciphered.

Note:

The decipher object can't be used after the final() method been called.

Arguments

output_encodingString

Required. The encoding to use for the output; can be either

*'binary', 'ascii', or 'utf8'

    • crypto.decipher.setAutoPadding(Boolean auto_padding = true)

You can disable auto padding if the data has been encrypted without standard block padding to prevent decipher.final from checking and removing it. Can only work if the input data's length is a multiple of the ciphers block size. You must call this before streaming data to decipher.update.

   

You can disable auto padding if the data has been encrypted without standard block padding to prevent decipher.final from checking and removing it. Can only work if the input data's length is a multiple of the ciphers block size. You must call this before streaming data to decipher.update.

Arguments

auto_paddingBoolean

Required. Specifies wheter automatic padding is on, or not

Updates the decipher with data.

   

Updates the decipher with data.

The input_encoding can be 'binary', 'base64' or 'hex'. The output_encoding can be 'binary', 'ascii' or 'utf8'.

Arguments

dataString

Required. The data to use for an update

input_encodingString

Required. Defines how the input is encoded

output_encodingString

Required. Defines how the output is encoded

Methods

    • crypto.diffieHellman.computeSecret(String other_public_key[, String input_encoding = "binary"][, String output_encoding = "input_encoding"])

Computes the shared secret and returns the computed shared secret.

   

Computes the shared secret and returns the computed shared secret.

Arguments

other_public_keyString

Required. The other party's public key

input_encodingString

Required. The encoding used to interprate the public key; can

*be 'binary', 'base64', or 'hex'.

output_encodingString

Required. The encoding of the returned computation; defaults

*to the input_encoding

    • crypto.diffieHellman.generateKeys([String encoding = "binary"])

Generates private and public Diffie-Hellman key values, and returns the public key in the specified encoding. This key should be transferred to the other party.

   

Generates private and public Diffie-Hellman key values, and returns the public key in the specified encoding. This key should be transferred to the other party.

Arguments

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

    • crypto.diffieHellman.getGenerator([String encoding = "binary"])

Returns the Diffie-Hellman prime in the specified encoding.

   

Returns the Diffie-Hellman prime in the specified encoding.

Example

Arguments

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

    • crypto.diffieHellman.getPrime([String encoding = "binary"])

Returns the Diffie-Hellman prime in the specified encoding.

   

Returns the Diffie-Hellman prime in the specified encoding.

Example

Arguments

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

    • crypto.diffieHellman.getPrivateKey([String encoding = "binary"])

Returns the Diffie-Hellman private key in the specified encoding.

   

Returns the Diffie-Hellman private key in the specified encoding.

Arguments

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

    • crypto.diffieHellman.getPublicKey([String encoding = "binary"])

Returns the Diffie-Hellman public key in the specified encoding.

   

Returns the Diffie-Hellman public key in the specified encoding.

Arguments

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

    • crypto.diffieHellman.setPrivateKey(String public_key[, String encoding = "binary"])

Sets the Diffie-Hellman private key.

   

Sets the Diffie-Hellman private key.

Arguments

public_keyString

Required. The public key that's shared

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

    • crypto.diffieHellman.setPublicKey(String public_key[, String encoding = "binary"])

Sets the Diffie-Hellman public key.

   

Sets the Diffie-Hellman public key.

Arguments

public_keyString

Required. The public key that's shared

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

Methods

    • crypto.hash.digest([String encoding = "binary"])

Calculates the digest of all of the passed data to be hashed.

   

Calculates the digest of all of the passed data to be hashed.

Note:

The hash object can't be used after the digest() method been called.

Arguments

encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

Updates the hash content with the given data. This can be called many times with new data as it is streamed.

   

Updates the hash content with the given data. This can be called many times with new data as it is streamed.

Arguments

dataString

Required. The data to use for an update

input_encodingString

Required. The encoding to use; can be 'binary', 'hex', or

*'base64'

Methods

Calculates the digest of all of the passed data to the hmac.

   

Calculates the digest of all of the passed data to the hmac.

Note:

The hmac object can't be used after the digest() method been called.

Arguments

encodingString

Required. The encoding to use; can be 'hex', 'binary' or

*'base64'

Update the HMAC content with the given data. This can be called many times with new data as it is streamed.

   

Update the HMAC content with the given data. This can be called many times with new data as it is streamed.

Arguments

dataString

Required. The data to use for an update

This class is used to generate certificates for OpenSSL. It can be created as a returned value from crypto.createSign().

Example

var s1 = crypto.createSign('RSA-SHA1')

         .update('Test123')
         .sign(keyPem, 'base64');

var verified = crypto.createVerify('RSA-SHA1')

               .update('Test')
               .update('123')
               .verify(certPem, s1, 'base64');

assert.strictEqual(verified, true, 'sign and verify (base 64)');

Methods

Calculates the signature on all the updated data passed through the signer.

   

Calculates the signature on all the updated data passed through the signer.

Note:

The signer object can not be used after the sign() method has been called.

Returns

The signature in a format defined by output_format.

Arguments

private_keyString

Required. A string containing the PEM encoded private key for

*signing

output_formatString

Required. The output encoding format; can be 'binary', 'hex'

*or 'base64'

Updates the signer object with data. This can be called many times with new data as it is streamed.

   

Updates the signer object with data. This can be called many times with new data as it is streamed.

Arguments

dataString

Required. The data to use for an update

crypto.verifier [edit]

This class is used to verify signed certificates for OpenSSL. It can be created as a returned value from crypto.createVerify().

Example

var s1 = crypto.createSign('RSA-SHA1')

         .update('Test123')
         .sign(keyPem, 'base64');

var verified = crypto.createVerify('RSA-SHA1')

               .update('Test')
               .update('123')
               .verify(certPem, s1, 'base64');

assert.strictEqual(verified, true, 'sign and verify (base 64)');

Methods

Updates the verifier object with data. This can be called many times with new data as it is streamed.

   

Updates the verifier object with data. This can be called many times with new data as it is streamed.

Arguments

dataString

Required. The data to use for an update

Returns true or false depending on the validity of the signature for the data and public key.

   

Returns true or false depending on the validity of the signature for the data and public key.

Note:

The verifier object can't be used after the verify() method has been called.

Arguments

objectString

Required. A string containing a PEM encoded object, which can be one of

*the following: an RSA public key, a DSA public key or an X.509 certificate

signatureString

Required. The previously calculated signature for the data

signature_formatString

Required. The format of the signature; can be 'binary',

*'hex', or 'base64'