首页 > 解决方案 > 使用 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)'

我应该怎么办?

标签: javascript

解决方案


crypto.subtle.digest() 需要ArrayBuffer 或 ArrayBufferView。

文件可以通过file.arrayBuffer().

上面示例中的函数应该asyncMDN 示例中的一样,并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);
} 

推荐阅读