Use 常量-时间 comparison 为 secret 验证
当 comparing secrets (passwords, tokens, MACs), comparison 必须 take 时间 independent 的 values 到 prevent timing 边-channels.
- 1
常量-时间 comparison 过程所有 bytes 不管的 where mismatches 发生. 它 accumulates differences 具有 XOR 和或, 然后 checks accumulator 在结束. 此 prevents attacker 从学习如何许多 bytes 匹配 based 开执行时间.
- 2 哈希对比器 →
比较两个 hash values using constant-time comparison. The tool always processes all bytes of both inputs, regardless of match position. Use this for verifying HMACs, password hashes, and API tokens
- 3 HMAC 生成器 →
之后 generating HMAC, 验证它 具有常量-时间 comparison. 模式是: 计算 expected = HMAC(键, 消息), 然后 constantTimeEqual(expected, received). 从不 use === 或 != 为此 comparison.
- 4
在 Node.js, use crypto.timingSafeEqual(, b). 在 browsers, implement 它 manually: accumulate XOR 的所有 bytes, 检查结果. 两者输入必须是 相同长度 — 如果 lengths 不同, 返回假 immediately (长度是 不 secret). comparison itself 必须是 常量-时间仅 当 lengths 匹配.
常见问题
- 什么如果 lengths 是不同?
- Return 假 immediately. 长度的 hash 或令牌是 通常不 secret (它是 固定通过 algorithm). 常量-时间需求 applies 仅到 字节-通过-字节 comparison 的 equal-长度输入. Comparing 不同-长度 values 在常量时间是 unnecessary.
- 此 matter 遍历网络?
- 是. Timing attacks 有是 demonstrated 遍历 networks 具有 ~15ms jitter. While harder than 本地 attacks, 它们是 可行具有 enough samples. 为高-值目标 (API 关键, payment tokens), 总是 use 常量-时间 comparison, even 遍历网络.