當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


Node.js crypto.createHash(algorithm[, options])用法及代碼示例

crypto.createHash(algorithm[, options])

曆史
版本變化
v12.8.0

為 XOF 哈希函數添加了 outputLength 選項。

v0.1.92

添加於:v0.1.92


參數

創建並返回一個 Hash 對象,該對象可用於使用給定的 algorithm 生成哈希摘要。可選的 options 參數控製流行為。對於 'shake256' 等 XOF 哈希函數,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', () => {
  // 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}`);
  }
});

相關用法


注:本文由純淨天空篩選整理自nodejs.org大神的英文原創作品 crypto.createHash(algorithm[, options])。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。