---

title: Content-Digest头与响应完整性治理(sha-256)最佳实践

keywords:

  • Content-Digest
  • sha-256
  • 完整性
  • 条件请求
  • 校验

description: 通过在响应中下发Content-Digest(sha-256)并在客户端进行校验,提升传输完整性与缓存安全,协同ETag与条件请求治理。

categories:

  • 文章资讯
  • 编程技术

---

背景与价值

响应完整性可防止传输与缓存中的篡改。Content-Digest提供标准化哈希头用于校验。

统一规范

  • 算法:统一 sha-256
  • 生成:服务端对响应体计算并下发头。
  • 校验:客户端验证后入缓存或使用。

核心实现

生成与下发

type Res = { setHeader: (k: string, v: string) => void; end: (b?: any) => void }

function b64url(buf: ArrayBuffer): string { const u = new Uint8Array(buf); let s=''; for (let i=0;i<u.length;i++) s+=String.fromCharCode(u[i]); return btoa(s).replace(/\+/g,'-').replace(/\//g,'_').replace(/=+$/,'') }

async function setContentDigest(res: Res, body: ArrayBuffer) {
  const d = await crypto.subtle.digest('SHA-256', body)
  res.setHeader('Content-Digest', 'sha-256=' + b64url(d))
  res.end(body)
}

客户端校验

async function verifyContentDigest(resp: Response): Promise<boolean> {
  const h = resp.headers.get('Content-Digest') || ''
  const m = h.match(/sha-256=([^,\s]+)/)
  if (!m) return false
  const body = await resp.arrayBuffer()
  const d = await crypto.subtle.digest('SHA-256', body)
  const hash = b64url(d)
  return hash === m[1]
}

落地建议

  • 对敏感与缓存型响应统一计算并下发Content-Digest(sha-256),客户端验证后缓存。
  • 与ETag/条件请求协同,提升一致性与完整性。

验证清单

  • 是否下发Content-Digest;客户端是否校验一致并再使用或缓存。

点赞(0) 打赏

评论列表 共有 0 条评论

暂无评论
立即
投稿

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部