`title: WebCrypto SHA-256 完整性校验与去重持久化``categories: Web 开发/前端/数据管理``keywords: WebCrypto,SHA-256,完整性,去重,IndexedDB,OPFS``description: 使用 WebCrypto 计算 SHA-256 对资源与文件进行完整性校验,并以哈希索引实现去重持久化,减少重复存储与传输。`计算哈希async function sha256(bytes) {
const digest = await crypto.subtle.digest('SHA-256', bytes);
return Array.from(new Uint8Array(digest)).map(b => b.toString(16).padStart(2, '0')).join('');
}
去重写入async function dedupPut(db, name, bytes) {
const hash = await sha256(bytes);
// 查询是否已有同哈希记录
const exists = await hasHash(db, hash);
if (exists) return { skipped: true, hash };
const root = await navigator.storage.getDirectory();
const handle = await root.getFileHandle(name, { create: true });
const writable = await handle.createWritable();
await writable.write(bytes);
await writable.close();
await putMeta(db, { id: crypto.randomUUID(), name, hash, size: bytes.byteLength, ts: Date.now() });
return { skipped: false, hash };
}
索引与查询IndexedDB 以 `hash` 建索引,快速检测重复;读取时校验一致性并修复损坏。

发表评论 取消回复