首页 > 解决方案 > 将解密函数从 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 的响应,所以我真的需要这个函数。谢谢您的帮助。

标签: phpnode.jscryptojs

解决方案


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。


推荐阅读