【发布时间】:2021-02-19 09:07:05
【问题描述】:
我有一个使用密钥解密有效负载的 PHP 代码,我正在尝试使用 crypto-js 库在 JavaScript 中编写完全相同的代码,但我得到了错误的结果。
有效载荷中的前 16 个字节 - 是向量,其余部分 - 是有用的信息。
PHP 中的工作代码 - https://ideone.com/NJXkRK
function getPayload($app_secret_key, $data) {
// Get the encryption key (16 first bytes of the app's client_secret key)
$encryption_key = substr($app_secret_key, 0, 16);
// Decrypt payload
$json_data = aes_128_decrypt($encryption_key, $data);
// Decode json
$json_decoded = json_decode($json_data, true);
return $json_data;
}
function aes_128_decrypt($key, $data) {
// Ecwid sends data in url-safe base64. Convert the raw data to the original base64 first
$base64_original = str_replace(array('-', '_'), array('+', '/'), $data);
// Get binary data
$decoded = base64_decode($base64_original);
// Initialization vector is the first 16 bytes of the received data
$iv = substr($decoded, 0, 16);
// The payload itself is is the rest of the received data
$payload = substr($decoded, 16);
// Decrypt raw binary payload
$json = openssl_decrypt($payload, "aes-128-cbc", $key, OPENSSL_RAW_DATA, $iv);
//$json = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $payload, MCRYPT_MODE_CBC, $iv); // You can use this instead of openssl_decrupt, if mcrypt is enabled in your system
return $json;
}
// Get payload from the GET and process it
$ecwid_payload = "ng7W9c9jLhkX7ATMpafNAd5Vt_skEaFAqnQaw0Ing1iwYQOwB0Q_CuCS8yQeHeorTdCpZWDTNrzhcq_umX7IaAFUPPgs0zyddY7Er1tA0aze5kWGHUV54fJHoVEJHMmVEi-G5g8ZnNopIFu0YQgQqLpCq8TP2zFJunSTA7VXHTmqHNAD2JXaUb-VylcJWzgV0vaCoGyHqaPbsNNw6HSWkAzhh8dLmsYB0uzsZ_zl3wVXubCL4p2N53PmNPBLCgoC";
$client_secret = "zcKf1Zt0UsO43S46Un3pxIgs91R1xMGs";
$result = getPayload($client_secret, $ecwid_payload);
print($result);
不工作的 JS 代码
function getPayload() {
const payload =
"ng7W9c9jLhkX7ATMpafNAd5Vt_skEaFAqnQaw0Ing1iwYQOwB0Q_CuCS8yQeHeorTdCpZWDTNrzhcq_umX7IaAFUPPgs0zyddY7Er1tA0aze5kWGHUV54fJHoVEJHMmVEi-G5g8ZnNopIFu0YQgQqLpCq8TP2zFJunSTA7VXHTmqHNAD2JXaUb-VylcJWzgV0vaCoGyHqaPbsNNw6HSWkAzhh8dLmsYB0uzsZ_zl3wVXubCL4p2N53PmNPBLCgoC";
const key = "zcKf1Zt0UsO43S46Un3pxIgs91R1xMGs";
// Get the encryption key (16 first bytes of the app's client_secret key)
const encryption_key = key.substr(0, 16);
// Decrypt payload
const base64_original = payload.replace(/-/gi, "+").replace(/_/gi, "/");
const data = aes_128_decrypt(encryption_key, base64_original);
console.log(data);
}
function aes_128_decrypt(password, data) {
const decoded = atob(data);
let iv = decoded.substr(0, 16);
let payload = decoded.substr(16);
iv = CryptoJS.enc.Hex.parse(iv);
const decrypted = CryptoJS.AES.decrypt(payload, password, {
iv: iv,
padding: CryptoJS.pad.NoPadding
});
return decrypted.toString();
}
window.onload = function() {
getPayload();
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.0.0/crypto-js.min.js"></script>
请帮我改进这个JS代码
【问题讨论】:
标签: javascript encryption aes cryptojs