SubtleCrypto: digest() 方法
注意:此功能在 Web Workers 中可用。
digest() 方法是 SubtleCrypto 接口的一个方法,它使用指定的 哈希函数 为给定的数据生成一个摘要。摘要是从可变长度输入派生出的短的固定长度值。加密摘要应具有抗碰撞性,意味着很难找到两个不同的输入产生相同的摘要值。
它接受两个参数:用于指定摘要算法的标识符和需要进行摘要的数据。它返回一个 Promise,该 Promise 将在摘要生成后解析(fulfilled)。
请注意,此 API 不支持流式输入:在将输入传递给 digest 函数之前,必须将整个输入读入内存。
语法
js
digest(algorithm, data)
参数
algorithm-
这可以是一个字符串,或者一个具有单个名为
name的字符串属性的对象。该字符串用于指定要使用的哈希函数。支持的值有:"SHA-1"(但在加密应用中不应使用此值)"SHA-256""SHA-384""SHA-512".
data-
包含要摘要的数据的
ArrayBuffer、TypedArray或DataView对象。
返回值
一个 Promise,它会解析(fulfill)为一个包含摘要的 ArrayBuffer。
支持的算法
摘要算法,也称为 哈希函数,将任意大的数据块转换为固定大小的输出,通常比输入短得多。它们在密码学中有多种应用。
| 算法 | 输出长度(比特) | 块大小(比特) | 规范 |
|---|---|---|---|
| SHA-1 | 160 | 512 | FIPS 180-4,第 6.1 节 |
| SHA-256 | 256 | 512 | FIPS 180-4,第 6.2 节 |
| SHA-384 | 384 | 1024 | FIPS 180-4,第 6.5 节 |
| SHA-512 | 512 | 1024 | FIPS 180-4,第 6.4 节 |
警告:SHA-1 现在被认为是不安全的,不应用于加密应用。
注意:如果您在这里寻找如何创建密钥哈希消息认证码(HMAC),您需要改用 SubtleCrypto.sign()。
示例
有关使用 digest() API 的更多示例,请参阅 SubtleCrypto 的非加密用途。
基本示例
此示例对消息进行编码,然后计算其 SHA-256 摘要并记录摘要长度
js
const text =
"An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.";
async function digestMessage(message) {
const encoder = new TextEncoder();
const data = encoder.encode(message);
const hash = await window.crypto.subtle.digest("SHA-256", data);
return hash;
}
digestMessage(text).then((digestBuffer) =>
console.log(digestBuffer.byteLength),
);
将摘要转换为十六进制字符串
摘要作为 ArrayBuffer 返回,但为了进行比较和显示,摘要通常表示为十六进制字符串。此示例计算一个摘要,然后将 ArrayBuffer 转换为十六进制字符串
js
const text =
"An obscure body in the S-K System, your majesty. The inhabitants refer to it as the planet Earth.";
async function digestMessage(message) {
const msgUint8 = new TextEncoder().encode(message); // encode as (utf-8) Uint8Array
const hashBuffer = await window.crypto.subtle.digest("SHA-256", msgUint8); // hash the message
const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
const hashHex = hashArray
.map((b) => b.toString(16).padStart(2, "0"))
.join(""); // convert bytes to hex string
return hashHex;
}
digestMessage(text).then((digestHex) => console.log(digestHex));
规范
| 规范 |
|---|
| Web 加密级别 2 # SubtleCrypto-method-digest |
浏览器兼容性
加载中…
另见
- SubtleCrypto 的非加密用途
- Chromium 安全来源规范
- FIPS 180-4 规定了 SHA 系列摘要算法。