crypto.hash(algorithm, data[, options])
¥Stability: 1.2 - Release candidate
-
algorithm<string> | <undefined> -
data<string> | <Buffer> | <TypedArray> | <DataView> 当data是字符串时,在进行哈希处理之前,它将被编码为 UTF-8。如果字符串输入需要不同的输入编码,用户可以使用TextEncoder或Buffer.from()将字符串编码为TypedArray,然后将编码后的TypedArray传递到此 API。¥
data<string> | <Buffer> | <TypedArray> | <DataView> Whendatais 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 aTypedArrayusing eitherTextEncoderorBuffer.from()and passing the encodedTypedArrayinto this API instead. -
-
outputEncoding<string> 编码 用于对返回的摘要进行编码。默认值:'hex'。¥
outputEncoding<string> Encoding used to encode the returned digest. Default:'hex'. -
outputLength<number> 对于 XOF 哈希函数(例如 'shake256'),可以使用 outputLength 选项指定所需的输出长度(以字节为单位)。¥
outputLength<number> For XOF hash functions such as 'shake256', the outputLength option can be used to specify the desired output length in bytes.
-
一种用于创建数据的一次性哈希摘要的实用程序。当散列少量可用数据(<= 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.
如果 options 是字符串,则它指定 outputEncoding。
¥If options is a string, then it specifies the outputEncoding.
示例:
¥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'));