Crypto

The crypto module provides cryptographic functionality that includes a set of wrappers for Mbedtls’s hash, HMAC, cipher and decipher functions.

Use require('crypto') to access this module.

Class: Cipher

Ruff available: v1.11.0

Instances of the Cipher class are used to encrypt data. The class can be used in one of two ways:

  • As a stream that is both readable and writable, where plain unencrypteddata is written to produce encrypted data on the readable side, or
  • Using the cipher.update and cipher.final methods to producethe encrypted data.

The crypto.createCipher() or crypto.createCipheriv() methods are used to create Cipher instances. Cipher objects are not to be createddirectly using the new keyword.

Example: Using Cipher objects as streams:

var crypto = require('crypto');
var cipher = crypto.createCipher('aes192', 'a password');

var encrypted = '';
cipher.on('readable', function() {
var data = cipher.read();
if (data)
encrypted += data.toString('hex');
});
cipher.on('end', function() {
console.log(encrypted);
// Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504
});

cipher.write('some clear text data');
cipher.end();

Example: Using Cipher and piped streams:

var crypto = require('crypto');
var fs = require('fs');
var cipher = crypto.createCipher('aes192', 'a password');

var input = fs.createReadStream('test.js');
var output = fs.createWriteStream('test.enc');

input.pipe(cipher).pipe(output);

Example: Using the cipher.update() and cipher.final() methods:

var crypto = require('crypto');
var cipher = crypto.createCipher('aes192', 'a password');

var encrypted = cipher.update('some clear text data', 'utf8', 'hex');
encrypted += cipher.final('hex');
console.log(encrypted);
// Prints: ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504

cipher.final([outputEncoding])

Ruff available: v1.11.0

  • outputEncoding

Returns any remaining enciphered contents. If outputEncoding parameter is one of 'base64' or 'hex', a string is returned.If an outputEncoding is not provided, a Buffer is returned.

Once the cipher.final() method has been called, the Cipher object can nolonger be used to encrypt data. Attempts to call cipher.final() more thanonce will result in an error being thrown.

cipher.setAutoPadding([autoPadding])

Ruff available: v1.11.0

  • autoPaddingDefaults to true.
  • Returns thefor method chaining.

When using block encryption algorithms, the Cipher class will automaticallyadd padding to the input data to the appropriate block size. To disable thedefault padding call cipher.setAutoPadding(false).

When autoPadding is false, the length of the entire input data must be amultiple of the cipher’s block size or cipher.final will throw an Error.Disabling automatic padding is useful for non-standard padding, for instanceusing 0x0 instead of PKCS padding.

The cipher.setAutoPadding() method must be called before cipher.final().

Returns this for method chaining.

cipher.update(data[, input_encoding][, output_encoding])

Ruff available: v1.11.0

  • data|
  • inputEncoding
  • outputEncoding

Updates the cipher with data. If the input_encoding argument is given,its value must be one of 'utf8' or 'ascii', and the dataargument is a string using the specified encoding. If the input_encodingargument is not given, data must be a Buffer. If data is a Buffer then input_encoding is ignored.

The output_encoding specifies the output format of the enciphereddata, and can be 'base64' or 'hex'. If the output_encodingis specified, a string using the specified encoding is returned. If no output_encoding is provided, a Buffer is returned.

The cipher.update() method can be called multiple times with new data until cipher.final() is called. Calling cipher.update() after cipher.final() will result in an error being thrown.

Class: Decipher

Ruff available: v1.11.0

Instances of the Decipher class are used to decrypt data. The class can beused in one of two ways:

  • As a stream that is both readable and writable, where plain encrypteddata is written to produce unencrypted data on the readable side, or
  • Using the decipher.update() and decipher.final() methods toproduce the unencrypted data.

The crypto.createDecipher() or crypto.createDecipheriv() methods areused to create Decipher instances. Decipher objects are not to be createddirectly using the new keyword.

Example: Using Decipher objects as streams:

var crypto = require('crypto');
var decipher = crypto.createDecipher('aes192', 'a password');

var decrypted = '';
decipher.on('readable', function() {
var data = decipher.read();
if (data)
decrypted += data.toString('utf8');
});
decipher.on('end', function() {
console.log(decrypted);
// Prints: some clear text data
});

var encrypted =
'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
decipher.write(encrypted, 'hex');
decipher.end();

Example: Using Decipher and piped streams:

var crypto = require('crypto');
var fs = require('fs');
var decipher = crypto.createDecipher('aes192', 'a password');

var input = fs.createReadStream('test.enc');
var output = fs.createWriteStream('test.js');

input.pipe(decipher).pipe(output);

Example: Using the decipher.update() and decipher.final() methods:

var crypto = require('crypto');
var decipher = crypto.createDecipher('aes192', 'a password');

var encrypted =
'ca981be48e90867604588e75d04feabb63cc007a8f8ad89b10616ed84d815504';
var decrypted = decipher.update(encrypted, 'hex', 'utf8');
decrypted += decipher.final('utf8');
console.log(decrypted);
// Prints: some clear text data

decipher.final([output_encodin])

Ruff available: v1.11.0

  • outputEncoding

Returns any remaining deciphered contents. If output_encodingparameter is one of 'ascii' or 'utf8', a string is returned.If an output_encoding is not provided, a Buffer is returned.

Once the decipher.final() method has been called, the Decipher object canno longer be used to decrypt data. Attempts to call decipher.final() morethan once will result in an error being thrown.

decipher.setAutoPadding(auto_padding=true)

Ruff available: v1.11.0

  • autoPaddingDefaults to true.
  • Returns thefor method chaining.

When data has been encrypted without standard block padding, calling decipher.setAutoPadding(false) will disable automatic padding to prevent decipher.final() from checking for and removing padding.

Turning auto padding off will only work if the input data’s length is amultiple of the ciphers block size.

The decipher.setAutoPadding() method must be called before decipher.update().

Returns this for method chaining.

decipher.update(data[, inputEncoding][, outputEncoding])

Ruff available: v1.11.0

  • data|
  • inputEncoding
  • outputEncoding

Updates the decipher with data. If the inputEncoding argument is given,its value must be one of 'base64' or 'hex' and the data argument is a string using the specified encoding. If the inputEncodingargument is not given, data must be a Buffer. If data is a Buffer then inputEncoding is ignored.

The outputEncoding specifies the output format of the enciphereddata, and can be 'ascii' or 'utf8'. If the outputEncodingis specified, a string using the specified encoding is returned. If nooutputEncoding is provided, a Buffer is returned.

The decipher.update() method can be called multiple times with new data until decipher.final() is called. Calling decipher.update() after decipher.final() will result in an error being thrown.

Class: Hash

Ruff available: v1.11.0

The Hash class is a utility for creating hash digests of data. It can beused in one of two ways:

  • As a stream that is both readable and writable, where data is writtento produce a computed hash digest on the readable side, or
  • Using the hash.update() and hash.digest() methods to produce thecomputed hash.

The crypto.createHash() method is used to create Hash instances. Hashobjects are not to be created directly using the new keyword.

Example: Using Hash objects as streams:

var crypto = require('crypto');
var hash = crypto.createHash('sha256');

hash.on('readable', function() {
var data = hash.read();
if (data) {
console.log(data.toString('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50
}
});

hash.write('some data to hash');
hash.end();

Example: Using Hash and piped streams:

var crypto = require('crypto');
var fs = require('fs');
var hash = crypto.createHash('sha256');

var input = fs.createReadStream('test.js');
input.pipe(hash).pipe(process.stdout);

Example: Using the hash.update() and hash.digest() methods:

var crypto = require('crypto');
var hash = crypto.createHash('sha256');

hash.update('some data to hash');
console.log(hash.digest('hex'));
// Prints:
// 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50

hash.digest([encoding])

Ruff available: v1.11.0

  • encoding

Calculates the digest of all of the data passed to be hashed (using the hash.update() method). The encoding can be 'hex', 'latin1' or'base64'. If encoding is provided a string will be returned; otherwisea Buffer is returned.

The Hash object can not be used again after hash.digest() method has beencalled. Multiple calls will cause an error to be thrown.

hash.update(data[, inputEncoding])

Ruff available: v1.11.0

  • data|
  • inputEncoding

Updates the hash content with the given data, the encoding of whichis given in inputEncoding and can be 'utf8', 'ascii' or'latin1'. If encoding is not provided, and the data is a string, anencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, orDataView, then inputEncoding is ignored.

This can be called many times with new data as it is streamed.

Class: Hmac

Ruff available: v1.11.0

The Hmac Class is a utility for creating cryptographic HMAC digests. It canbe used in one of two ways:

  • As a stream that is both readable and writable, where data is writtento produce a computed HMAC digest on the readable side, or
  • Using the hmac.update() and hmac.digest() methods to produce thecomputed HMAC digest.

The crypto.createHmac() method is used to create Hmac instances. Hmacobjects are not to be created directly using the new keyword.

Example: Using Hmac objects as streams:

var crypto = require('crypto');
var hmac = crypto.createHmac('sha256', 'a secret');

hmac.on('readable', function() {
var data = hmac.read();
if (data) {
console.log(data.toString('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e
}
});

hmac.write('some data to hash');
hmac.end();

Example: Using Hmac and piped streams:

var crypto = require('crypto');
var fs = require('fs');
var hmac = crypto.createHmac('sha256', 'a secret');

var input = fs.createReadStream('test.js');
input.pipe(hmac).pipe(process.stdout);

Example: Using the hmac.update() and hmac.digest() methods:

var crypto = require('crypto');
var hmac = crypto.createHmac('sha256', 'a secret');

hmac.update('some data to hash');
console.log(hmac.digest('hex'));
// Prints:
// 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e

hmac.digest([encoding])

Ruff available: v1.11.0

  • encoding

Calculates the HMAC digest of all of the data passed using hmac.update().The encoding can be 'hex', 'latin1' or 'base64'. If encoding isprovided a string is returned; otherwise a Buffer is returned;

The Hmac object can not be used again after hmac.digest() has beencalled. Multiple calls to hmac.digest() will result in an error being thrown.

hmac.update(data[, inputEncoding])

Ruff available: v1.11.0

  • data|
  • inputEncoding

Updates the Hmac content with the given data, the encoding of whichis given in inputEncoding and can be 'utf8', 'ascii' or'latin1'. If encoding is not provided, and the data is a string, anencoding of 'utf8' is enforced. If data is a Buffer, TypedArray, orDataView, then inputEncoding is ignored.

This can be called many times with new data as it is streamed.

crypto module methods and properties

crypto.createCipher(algorithm, password)

Ruff available: v1.11.0

  • algorithm
  • password|

Creates and returns a Cipher object that uses the given algorithm and password.

The algorithm is dependent on Mbedtls, examples are 'aes192'.

The password is used to derive the cipher key and initialization vector (IV).The value must be either a string or a Buffer.

The implementation of crypto.createCipher() derives keys same as nodejs.

crypto.createCipheriv(algorithm, key, iv)

Ruff available: v1.11.0

  • algorithm
  • key|
  • iv|

Creates and returns a Cipher object, with the given algorithm, key andinitialization vector (iv).

The algorithm is dependent on Mbedtls, examples are 'aes192', etc.

The key is the raw key used by the algorithm and iv is an initialization vector. Both arguments must be 'utf8' encoded strings orBuffers.

crypto.createDecipher(algorithm, password)

Ruff available: v1.11.0

  • algorithm
  • password|

Creates and returns a Decipher object that uses the given algorithm and password (key).

The implementation of crypto.createDecipher() derives keys same as nodejs.

crypto.createDecipheriv(algorithm, key, iv)

Ruff available: v1.11.0

  • algorithm
  • key|
  • iv|

Creates and returns a Decipher object that uses the given algorithm, keyand initialization vector (iv).

The algorithm is dependent on Mbedtls, examples are 'aes192', etc.

The key is the raw key used by the algorithm and iv is an initialization vector. Both arguments must be 'utf8' encoded strings or Buffers.

crypto.createHash(algorithm)

Ruff available: v1.11.0

  • algorithm

Creates and returns a Hash object that can be used to generate hash digestsusing the given algorithm.

The algorithm is dependent on the available algorithms supported by the Mbedtls. Examples are 'sha256', 'sha512', etc.

crypto.createHmac(algorithm, key)

Ruff available: v1.11.0

  • algorithm
  • key|

Creates and returns an Hmac object that uses the given algorithm and key.

The algorithm is dependent on the available algorithms supported by Mbedtls. Examples are 'sha256', 'sha512', etc.

The key is the HMAC key used to generate the cryptographic HMAC hash.

crypto.getCiphers()

Ruff available: v1.11.0

Returns an array with the names of the supported cipher algorithms.

Example:

var ciphers = crypto.getCiphers();
console.log(ciphers); // ['aes-128-cbc', 'aes-128-ecb', ...]

crypto.getHashes()

Ruff available: v1.11.0

Returns an array of the names of the supported hash algorithms,such as RSA-SHA256.

Example:

var hashes = crypto.getHashes();
console.log(hashes); // ['md5', 'sha1', 'sha224', ...]

crypto.publicEncrypt(publicKey, buffer)

Ruff available: v1.11.1

  • publicKey
  • buffer|

Encrypts the content of buffer with publicKey and returns a new Buffer with encrypted content.

publicKey is a string, it is treated as the key with no passphrase and will use RSA_PKCS1_OAEP_PADDING.