javascript - 使用 crypto.subtle.digest 生成给定文件的摘要是否可行?
问题描述
我已经运行了这个来自MDN doc的示例
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 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;
}
const digestHex = await digestMessage(text);
console.log(digestHex);
我了解示例中显示的基本用法。
但是,我不知道如何生成给定文件/blob 的摘要。我试过这个
const hashBuffer = crypto.subtle.digest('SHA-256', file);
点击https://jsfiddle.net/5dn4bjfw/查看完整版。
并得到这个错误。
The provided value is not of type '(ArrayBuffer or ArrayBufferView)'
我应该怎么办?
解决方案
crypto.subtle.digest()
需要ArrayBuffer 或 ArrayBufferView。
文件可以通过file.arrayBuffer()
.
上面示例中的函数应该async
与MDN 示例中的一样,并await
用于所有返回 Promises 的调用。
async function myFunction(){
const finput = document.getElementById('fileinput');
const file = finput.files[0];
const arrayBuffer = await file.arrayBuffer();
const hashBuffer = await crypto.subtle.digest('SHA-256', arrayBuffer); // hash the message
console.log(hashBuffer);
const hashArray = Array.from(new Uint8Array(hashBuffer)); // convert buffer to byte array
const hashHex = hashArray.map(b => b.toString(16).padStart(2, '0')).join('');
console.log(hashHex);
}
推荐阅读
- android - 如何在 Android Studio 中为当前 API 选择替代来源
- ios - 在 applicationWillTerminate 中调用云函数
- json - 从一个目录导入多个 JSON/csv 文件,然后使用 powershell 转换后移动到不同的目录
- php - 在 aLaravel 照片库中显示图像
- powershell - 如何降级 VS Code powershell 扩展?
- node.js - 两个自签名 CA,用于前端和后端本地测试
- python - 在python中将二维列表制作成一维列表
- python - 使用 boto 的 SSLError
- rust - 包含期货的 Vec 的完整类型签名是什么?
- swift - 收到警告 xpression 类型“@lvalue 字符串?” 没有更多上下文是模棱两可的