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

时间:2019-12-18 13:58:01

标签: 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 - 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:数据不是块长度的倍数

我不理解错误消息,请帮忙做一个可行的例子。

0 个答案:

没有答案