概述为每条记录计算并保存摘要,可在读取时验证一致性,发现损坏或意外覆盖。写入与验证function openDB(name) { return new Promise((resolve, reject) => { const r = indexedDB.open(name, 1); r.onupgradeneeded = () => { const db = r.result; if (!db.objectStoreNames.contains('items')) db.createObjectStore('items', { keyPath:'id' }); }; r.onsuccess = () => resolve(r.result); r.onerror = () => reject(r.error); }); }

async function sha256Text(text) { const buf = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)); return Array.from(new Uint8Array(buf)).map(x=>x.toString(16).padStart(2,'0')).join(''); }

async function putRecord(rec) {

const db = await openDB('chk');

const tx = db.transaction('items','readwrite');

const hash = await sha256Text(JSON.stringify(rec));

tx.objectStore('items').put({ ...rec, _hash: hash });

await new Promise((res, rej) => { tx.oncomplete = res; tx.onerror = () => rej(tx.error); });

db.close();

}

async function getRecord(id) {

const db = await openDB('chk');

const tx = db.transaction('items','readonly');

const req = tx.objectStore('items').get(id);

const rec = await new Promise((res, rej) => { req.onsuccess = () => res(req.result); req.onerror = () => rej(req.error); });

db.close();

if (!rec) return null;

const vhash = await sha256Text(JSON.stringify({ ...rec, _hash: undefined }));

if (vhash !== rec._hash) throw new Error('checksum mismatch');

return rec;

}

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部