crypto.hash(algorithm, data[, options])
algorithm<string> | <undefined>data<string> | <Buffer> | <TypedArray> | <DataView> 当data是字符串时,它将在哈希之前以 UTF-8 编码。如果希望对字符串输入使用不同的编码,用户可以使用TextEncoder或Buffer.from()将字符串编码为TypedArray,然后将编码后的TypedArray传入此 API。options<Object> | <string>- 返回:<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.
如果 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'));