首页 > 解决方案 > 在 PHP 7 中加密并在 Node.js 中解密

问题描述

我需要在 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:数据不是块长度的倍数

我不明白错误消息,帮助制作一个工作示例。

标签: node.jsencryption

解决方案


推荐阅读