php - 将解密函数从 PHP 移植到 NodeJs
问题描述
将函数从 PHP 移植到 NodeJS 时遇到一些问题。我试过用 Node JS 实现这个 PHP 代码,但它不起作用。
这是PHP中的代码
<?php
require_once 'vendor/autoload.php';
// function decrypt
function stringDecrypt($key, $string){
$encrypt_method = 'AES-256-CBC';
// hash
$key_hash = hex2bin(hash('sha256', $key));
// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hex2bin(hash('sha256', $key)), 0, 16);
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key_hash, OPENSSL_RAW_DATA, $iv);
return $output;
}
?>
这是我在 NodeJs 中的代码
function decryptResponse(timestamp, string, key) {
var key_hash = hex2bin(crypto.createHash("sha256").update(key).digest('hex'));
var iv = key_hash.substr(0,16);
var decoder = crypto.createDecipheriv('aes-256-cbc', key_hash, iv);
var output = decoder.update(Buffer.from(string).toString('base64'),'base64','utf8') += decoder.final('utf8');
console.log("Decrypt Result : ", output); //Not Showing on Log
}
function hex2bin(hex) {
var bytes = [];
var str;
for(var i=0; i< hex.length-1; i+=2){
bytes.push(parseInt(hex.substr(i, 2), 16));
}
str = String.fromCharCode.apply(String, bytes);
return str;
}
当我从 API 获得响应并需要将其发送给用户时,将调用此函数。
var decompressedResponse = decryptResponse(timestamp, response.data.response, key);
res.send(decompressedResponse);
我需要这个函数来解密来自 API 的响应,所以我真的需要这个函数。谢谢您的帮助。
解决方案
该hex2bin()
功能不是必需的,可以删除。
此外,更容易将 key 和 IV 确定为缓冲区。
密文目前在update()
. 为避免这种情况,应将其直接传递给update()
.
update()
并且调用结果的连接final()
必须使用+
代替+=
(这可能只是一个错字或复制/粘贴错误)。
全面的:
function decryptResponse(timestamp, string, key) {
var key_hash = crypto.createHash("sha256").update(key).digest(); // remove hex2bin; use Buffer
var iv = key_hash.slice(0,16); // use Buffer
var decoder = crypto.createDecipheriv('aes-256-cbc', key_hash, iv);
var output = decoder.update(string,'base64','utf8') + decoder.final('utf8'); // don't Base64 encode twice, pass ciphertext directly; apply + instead of +=
console.log("Decrypt Result : ", output);
}
请注意,将密钥或密钥的一部分用作 IV 是不安全的。通常,(非秘密)IV 是为每次加密随机生成的,并与密文(通常是连接的)一起传递。
此外,使用散列作为密钥派生函数是不安全的。相反,应该应用可靠的密钥派生函数,例如 PBKDF2。
推荐阅读
- reactjs - 如何将graphql api与react frontEnd一起使用?
- c# - 使用 c#.net 从 url 下载文件并在我们的本地计算机中打开该文件后,它显示文件已损坏
- python - 如何将 2 个数组列表添加到具有两个单独列名的单个熊猫数据框中
- logging - 没有更多本地 Skype 日志?
- c# - FileSystemWatcher - 文件夹重命名问题
- algorithm - 无连接和间接图的 BFS 运行时间复杂度
- android - 屏幕质量非常低的 Android 模拟器
- java - 在 Java (Android) 中使用 Node.js-module OrbitDB 的 API
- angular - 如何在 Angular 5 中重叠组件
- python - 使用 Python 抓取电子邮件中的文本,将文本记录在 Excel 文件中,然后编写包含文本的新电子邮件