【发布时间】:2021-04-13 05:39:25
【问题描述】:
我有一个应用程序,我在其中使用 AES CBC 128 算法加密一个 json 编码数组,然后在 javascript(React/Next Js 项目)中解密它。我在php中的加密如下代码所示
加密 PHP
$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 );
我在用 Javascript 解密时遇到问题
到目前为止我的代码如下所示
const baseenc = CryptoJS.enc.Base64.parse(cipher).toString();
var encrypted = CryptoJS.AES.decrypt(cipher, key, { iv: iv }).toString();
var plaintext = CryptoJS.enc.Latin1.stringify(encrypted);
请任何机构显示错误是什么或帮助我获得正确的输出
【问题讨论】:
-
您的 CryptoJS 代码缺少 IV、HMAC 和实际密文的分离。此外,必须计算密文的 HMAC。如果计算和接收到的 HMAC 匹配,则密文是真实的。认证成功后,您需要 IV 和密钥来解密实际密文。另请参阅here,了解使用相同的密钥进行加密和身份验证。
-
@Topaco 那么你能帮我吗?我怎样才能分离 iv hmac 和密文
-
好的,请看我的回答。
标签: javascript php encryption aes