Skip to content

Latest commit

 

History

History
147 lines (107 loc) · 4.22 KB

Crypto.md

File metadata and controls

147 lines (107 loc) · 4.22 KB

Crypto

The crypto module provides cryptographic functionality that includes a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions.

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

Class: Hash

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

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

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

Example: Using Hash objects as streams:

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

hash.on('readable', () => {
  const 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:

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

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

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

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

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

hash.digest([encoding])

  • encoding {string}

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; otherwise a [Buffer][] is returned.

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

hash.update(data[, inputEncoding])

  • data {string | Buffer | TypedArray | DataView}
  • inputEncoding {string}

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

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

crypto module methods and properties

crypto.createHash(algorithm[, options])

  • algorithm {string}
  • options {Object} [stream.transform options][]

Creates and returns a Hash object that can be used to generate hash digests using the given algorithm. Optional options argument controls stream behavior.

The algorithm is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are 'sha256', 'sha512', etc. On recent releases of OpenSSL, openssl list-message-digest-algorithms will display the available digest algorithms.

Example: generating the sha256 sum of a file

const filename = process.argv[2];
const crypto = require('crypto');
const fs = require('fs');
const hash = crypto.createHash('sha256');

const input = fs.createReadStream(filename);
input.on('readable', () => {
  const data = input.read();
  if (data)
    hash.update(data);
  else {
    console.log(`${hash.digest('hex')} ${filename}`);
  }
});

crypto.getHashes()

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

Example:

const hashes = crypto.getHashes();
console.log(hashes);

crypto.randomBytes(size[, callback])

  • size {Number}
  • callback {Function}
    • err {Error}
    • buf {Buffer}

Generates cryptographically strong pseudo-random data. The size argument is a number indicating the number of bytes to generate.

If a callback function is provided, the bytes are generated asynchronously and the callback function is invoked with two arguments: err and buf. If an error occurs, err will be an Error object; otherwise it is null. The buf argument is a Buffer containing the generated bytes.