将解密函数从 PHP 移植到 NodeJs

Porting Decryption Function From PHP to 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()中进行了第二次Base64编码。为避免这种情况,应将其直接传递给update()

并且 update()final() 调用的结果的串联必须使用 + 而不是 += (这可能只是一个错字或 copy/paste错误)。

总体:

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。