crypto.createHash(algorithm[, options])


创建并返回 Hash 对象,该对象可用于使用给定的 algorithm 生成哈希摘要。 可选的 options 参数控制流的行为。 对于 XOF 哈希函数(例如 'shake256'),可以使用 outputLength 选项指定所需的输出长度(以字节为单位)。

algorithm 取决于平台上 OpenSSL 版本支持的可用算法。 例如 'sha256''sha512' 等。 在最近的 OpenSSL 版本中,openssl list -digest-algorithms 将显示可用的摘要算法。

示例:生成文件的 sha256 总和

import {
  createReadStream
} from 'fs';
import { argv } from 'node:process';
const {
  createHash
} = await import('node:crypto');

const filename = argv[2];

const hash = createHash('sha256');

const input = createReadStream(filename);
input.on('readable', () => {
  // 哈希流只生成
  // 一个元素。
  const data = input.read();
  if (data)
    hash.update(data);
  else {
    console.log(`${hash.digest('hex')} ${filename}`);
  }
});const {
  createReadStream,
} = require('node:fs');
const {
  createHash,
} = require('node:crypto');
const { argv } = require('node:process');

const filename = argv[2];

const hash = createHash('sha256');

const input = createReadStream(filename);
input.on('readable', () => {
  // 哈希流只生成
  // 一个元素。
  const data = input.read();
  if (data)
    hash.update(data);
  else {
    console.log(`${hash.digest('hex')} ${filename}`);
  }
});

Creates and returns a Hash object that can be used to generate hash digests using the given algorithm. Optional options argument controls stream behavior. For XOF hash functions such as 'shake256', the outputLength option can be used to specify the desired output length in bytes.

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 -digest-algorithms will display the available digest algorithms.

Example: generating the sha256 sum of a file

import {
  createReadStream
} from 'fs';
import { argv } from 'node:process';
const {
  createHash
} = await import('node:crypto');

const filename = argv[2];

const hash = createHash('sha256');

const input = createReadStream(filename);
input.on('readable', () => {
  // Only one element is going to be produced by the
  // hash stream.
  const data = input.read();
  if (data)
    hash.update(data);
  else {
    console.log(`${hash.digest('hex')} ${filename}`);
  }
});const {
  createReadStream,
} = require('node:fs');
const {
  createHash,
} = require('node:crypto');
const { argv } = require('node:process');

const filename = argv[2];

const hash = createHash('sha256');

const input = createReadStream(filename);
input.on('readable', () => {
  // Only one element is going to be produced by the
  // hash stream.
  const data = input.read();
  if (data)
    hash.update(data);
  else {
    console.log(`${hash.digest('hex')} ${filename}`);
  }
});