防止哈希字符串比较的定时攻击的一种方法是执行额外的 HMAC 签名以随机化验证过程(请参阅https://www.nccgroup.trust/us/about-us/newsroom-and-events/blog/2011 /二月/双hmac验证/)。
除了每个散列的第二个 HMAC 散列之外,还向两者添加了一个随机长度的随机盐,以使散列时间/过程更加难以预测。
我的实现如下所示:
function hmac_verify ($hash_original, $message, $key) {
$hmac_salt = '...'; // was added at the original HMAC signing
$random_salt = openssl_random_pseudo_bytes (rand(16,96));
$raw_hash = hash_hmac('sha512', $message . $hmac_salt, $key, true);
$hash_compare = base64_encode ($raw_hash); // $hash_original is in base64
$hash_compare_safe = hash_hmac('sha512', $hash_compare, $random_salt, true);
$hash_original_safe = hash_hmac('sha512', $hash_original, $random_salt, true);
if ($hash_compare_safe === $hash_original_safe) return true;
else return false;
}
解密密文后调用该函数以验证解密结果:
if (!hmac_verify ($hmac_hash, $plaintext . $cipher_text, $key . $iv)) return "HASH ERROR";
这会成功防止定时攻击吗?我做了什么不必要的事情吗?有什么可以改进的吗?
第二个问题是对明文、密文或两者(如我的示例)执行 HMAC 验证是否更可取,以及为什么。