crypto.hash(algorithm, data[, outputEncoding])


稳定性: 1.2 - 发布候选

¥Stability: 1.2 - Release candidate

  • algorithm <string> | <undefined>

  • data <string> | <Buffer> | <TypedArray> | <DataView>data 是字符串时,在进行哈希处理之前,它将被编码为 UTF-8。如果字符串输入需要不同的输入编码,用户可以使用 TextEncoderBuffer.from() 将字符串编码为 TypedArray,然后将编码后的 TypedArray 传递到此 API。

    ¥data <string> | <Buffer> | <TypedArray> | <DataView> When data is a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user could encode the string into a TypedArray using either TextEncoder or Buffer.from() and passing the encoded TypedArray into this API instead.

  • outputEncoding <string> | <undefined> 编码 用于对返回的摘要进行编码。默认值:'hex'

    ¥outputEncoding <string> | <undefined> Encoding used to encode the returned digest. Default: 'hex'.

  • 返回:<string> | <Buffer>

    ¥Returns: <string> | <Buffer>

一种用于创建数据的一次性哈希摘要的实用程序。当散列少量可用数据(<= 5MB)时,它比基于对象的 crypto.createHash() 更快。如果数据量很大或者是流式传输,仍然建议使用 crypto.createHash()

¥A utility for creating one-shot hash digests of data. It can be faster than the object-based crypto.createHash() when hashing a smaller amount of data (<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use crypto.createHash() instead.

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

¥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:

const crypto = require('node:crypto');
const { Buffer } = require('node:buffer');

// Hashing a string and return the result as a hex-encoded string.
const string = 'Node.js';
// 10b3493287f831e81a438811a1ffba01f8cec4b7
console.log(crypto.hash('sha1', string));

// Encode a base64-encoded string into a Buffer, hash it and return
// the result as a buffer.
const base64 = 'Tm9kZS5qcw==';
// <Buffer 10 b3 49 32 87 f8 31 e8 1a 43 88 11 a1 ff ba 01 f8 ce c4 b7>
console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer'));import crypto from 'node:crypto';
import { Buffer } from 'node:buffer';

// Hashing a string and return the result as a hex-encoded string.
const string = 'Node.js';
// 10b3493287f831e81a438811a1ffba01f8cec4b7
console.log(crypto.hash('sha1', string));

// Encode a base64-encoded string into a Buffer, hash it and return
// the result as a buffer.
const base64 = 'Tm9kZS5qcw==';
// <Buffer 10 b3 49 32 87 f8 31 e8 1a 43 88 11 a1 ff ba 01 f8 ce c4 b7>
console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer'));