// worker.js import {Sha256} from "@aws-crypto/sha256-js"; import SparkMD5 from "spark-md5"; onmessage = async function (event) { const data = event.data; // chunk方式读取文件 const chunkSize = 1024 * 1024; // 每次读取1MB const fileSize = data.size; let offset = 0; const hash = new Sha256(); const spark = new SparkMD5.ArrayBuffer(); while (offset < fileSize) { const chunk = data.slice(offset, offset + chunkSize); const buffer = await chunk.arrayBuffer(); hash.update(buffer); spark.append(buffer); offset += chunkSize; console.log(offset / fileSize * 100 , '%'); } const sha256Value = await hash.digest(); const buffer = Array.from(new Int8Array(sha256Value)); const md5Value = spark.end(); const md5Buffer = Array.from(new Int8Array(md5Value)); console.log(sha256Value, buffer); // 输出文件的sha256值 console.log(md5Value, md5Buffer); // 输出文件的MD5值 postMessage(buffer); };优化代码计算sah256
时间: 2024-01-16 12:03:49 浏览: 147
sha-256.js
4星 · 用户满意度95%
可以考虑使用 Web Crypto API 中的 SubtleCrypto.digest() 方法来计算 SHA-256 值,这样可以避免引入第三方库。修改后的代码如下所示:
```
onmessage = async function (event) {
const data = event.data;
const chunkSize = 1024 * 1024; // 每次读取1MB
const fileSize = data.size;
let offset = 0;
const hash = await crypto.subtle.digest('SHA-256');
while (offset < fileSize) {
const chunk = data.slice(offset, offset + chunkSize);
const buffer = await chunk.arrayBuffer();
await crypto.subtle.digest('SHA-256', buffer);
offset += chunkSize;
console.log(offset / fileSize * 100 , '%');
}
const sha256Value = new Uint8Array(hash);
const buffer = Array.from(sha256Value);
console.log(sha256Value, buffer); // 输出文件的sha256值
postMessage(buffer);
};
```
其中,`crypto.subtle.digest()` 方法返回一个 Promise,该 Promise 会 resolve 为一个 ArrayBuffer,包含计算好的 SHA-256 值。可以通过将其转换为 Uint8Array 来得到最终的值。
阅读全文