CryptoJS AES 加密(密钥大小 128 / 8)相当于 PHP
我是 PHP 新手,我试图在 PHP 中实现与 CryptoJS AES 加密等效的功能。我看到了这篇帖子,但不幸的是我无法实现相同的目标。我在 PHP 代码中得到了不同的输出作为加密字符串。
我哪里做错了?
Javascript代码
const customerObject = {
CustomerName: "test",
EmailID: "[email protected]",
Street: "Test",
City: "London",
Country: "United Kingdom",
ZipCode: "XXX XXX",
};
const token = "8056483646328123";
const key = CryptoJS.enc.Utf8.parse(token);
const iv = CryptoJS.enc.Utf8.parse(token);
const returnEncrypted = CryptoJS.AES.encrypt(
CryptoJS.enc.Utf8.parse(customerObject),
key,
{
iv: iv,
keySize: 128 / 8,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
}
);
PHP代码
<?php
$customer = [
'CustomerName' => "test",
'EmailID' => "[email protected]",
'Street' => "Test",
'City' => "London",
'Country' => "United Kingdom",
'ZipCode' => "XXX XXX",
];
$plaintext = json_encode($customer);
$method = 'AES-128-CBC';
$key = hex2bin("8056483646328123");
$iv = hex2bin("8056483646328123");
$ciphertext = openssl_encrypt(
$plaintext,
$method,
$key,
OPENSSL_RAW_DATA,
$iv
);
$ciphertext = base64_encode($ciphertext);
echo $ciphertext;
?>
I am newbie in PHP and I was trying to achieve the CryptoJS AES encryption equivalent in PHP. I saw this post but unfortunately I was not able to achieve the same. I was getting a different output in PHP code as encrypted string.
Where did I go wrong?
Javascript Code
const customerObject = {
CustomerName: "test",
EmailID: "[email protected]",
Street: "Test",
City: "London",
Country: "United Kingdom",
ZipCode: "XXX XXX",
};
const token = "8056483646328123";
const key = CryptoJS.enc.Utf8.parse(token);
const iv = CryptoJS.enc.Utf8.parse(token);
const returnEncrypted = CryptoJS.AES.encrypt(
CryptoJS.enc.Utf8.parse(customerObject),
key,
{
iv: iv,
keySize: 128 / 8,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
}
);
PHP Code
<?php
$customer = [
'CustomerName' => "test",
'EmailID' => "[email protected]",
'Street' => "Test",
'City' => "London",
'Country' => "United Kingdom",
'ZipCode' => "XXX XXX",
];
$plaintext = json_encode($customer);
$method = 'AES-128-CBC';
$key = hex2bin("8056483646328123");
$iv = hex2bin("8056483646328123");
$ciphertext = openssl_encrypt(
$plaintext,
$method,
$key,
OPENSSL_RAW_DATA,
$iv
);
$ciphertext = base64_encode($ciphertext);
echo $ciphertext;
?>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
正如 @Topaco 在评论中指出的,key 和 IV不得进行十六进制解码,即删除两个 hex2bin()。
更正后的代码如下。
As @Topaco pointed out in comments, the key and IV must not be hex decoded, i.e. remove both hex2bin().
The corrected code is given below.