在PHP 7中加密,在Node.js中解密

在PHP 7中加密,在Node.js中解密,node.js,encryption,Node.js,Encryption,我需要在PHP中加密数据,在Node.js中解密 我用PHP对其进行加密: $encrypt_method = "AES-256-CBC"; $secret_key = '7CEsPlLfVXcHf2S4wsnPnfNqYa+N/D/1zCXExN4aJSs='; $secret_iv = 'StqUaIcbO9LFZ9QiuguXR6M/BepqZDV8p1now0FA/C4='; // hash $key = hash('sha256', $secret_key); // iv - enc

我需要在PHP中加密数据,在Node.js中解密

我用PHP对其进行加密:

$encrypt_method = "AES-256-CBC";
$secret_key = '7CEsPlLfVXcHf2S4wsnPnfNqYa+N/D/1zCXExN4aJSs=';
$secret_iv = 'StqUaIcbO9LFZ9QiuguXR6M/BepqZDV8p1now0FA/C4=';
// hash
$key = hash('sha256', $secret_key);

// iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
$iv = substr(hash('sha256', $secret_iv), 0, 16);
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
结果:

VU5pckRaWHA4bjNaUjU3dGhscys3QT09

并在Node.js中解密:

var crypto = require("crypto");
const decrypt = (textBase64, keyBase64, ivBase64) => {
    const algorithm = 'AES-256-CBC';
    const ivBuffer = Buffer.from(ivBase64, 'base64');
    const keyBuffer = Buffer.from(keyBase64, 'base64');

    const decipher = crypto.createDecipheriv(algorithm, keyBuffer, ivBuffer);
    decipher.setAutoPadding(false);

    let decrypted = decipher.update(textBase64, 'base64', 'utf8');
    decrypted += decipher.final('utf8');
    return decrypted;
}

const encryptedMessage = 'VU5pckRaWHA4bjNaUjU3dGhscys3QT09';
const key = '7CEsPlLfVXcHf2S4wsnPnfNqYa+N/D/1zCXExN4aJSs=';
const iv = Buffer.from('StqUaIcbO9LFZ9QiuguXR6M/BepqZDV8p1now0FA/C4=', 'base64').slice(0, 16);

// the message comes from the bytes AFTER the IV - this is what you should decrypt
const message = Buffer.from(encryptedMessage, 'base64').slice(16);

const result = decrypt(message, key, iv);

res.send("Decrypted: " + result);
错误:错误:0606508A:数字信封例程:EVP_DecryptFinal_ex:数据不是块长度的倍数


我不理解错误消息,请帮助制作一个工作示例。

您的
entryptedMessage
已两次转换为Base 64,正常吗?另外,您读过这个问题吗:?php代码不会从base64提取bin数据,但node.js会。另外,您的node.js代码也遗漏了php散列('sha256',ivBuffer).slice(0,16)的步骤。在OPENSSL_加密中也使用OPENSSL_ZERO_填充而不是零