对称加密为什么要使用消息认证码 (MAC) 签名
来源
在 PHP 文档看到用 openssl_encrypt()
实现 AES 对称加密算法
// PHP 5.6+ 的 AES 认证加密例子
//$key previously generated safely, ie: openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode( $iv.$hmac.$ciphertext_raw );
//decrypt later....
$c = base64_decode($ciphertext);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen+$sha2len);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
if (hash_equals($hmac, $calcmac))// timing attack safe comparison
{
echo $original_plaintext."\n";
}
疑惑
为什么要进行 mac 校验呢?我有几点疑惑:
- 是防止他人传入一个伪造的 code,通过 decrypt 的结果可以推算出密钥($key)吗?
- 不使用 mac 校验的情况,有可能伪造成功一个加密后的值并能
openssl_decrypt()
成功吗?
不是
目的:
第一:防篡改 基于加密原理那一套的理由是:保证消息在传输过程中没有被篡改。
第二:防重放 加密后的密文的hmac具有唯一性,短时间内相同hash的密文第二次被投递,可以根据该hash直接判定为重放攻击拒绝处理。