node.js - 在 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:数据不是块长度的倍数
我不明白错误消息,帮助制作一个工作示例。
解决方案
推荐阅读
- ember.js - 保存表单数据时如何获取当前公司ID?
- pandas - TypeError:Series.name 必须是可散列类型
- python - 无法为链接提供href,错误:“找不到'foo'的反向”
- html - 将 unicode 放入 CSS 内容是否合法?
- spring - 在没有@RequestParam 名称的控制器中获取文件
- ruby-on-rails - 与图像的多态关联
- c++ - 如何使用被覆盖函数中的子类引用覆盖纯虚函数
- python - 在 SNMP 代理端动态增加 OID
- swift - 如何快速隐藏状态栏?
- python - “tensorflow/core/platform/posix/subprocess.cc:208] 无法启动 fork() 子进程:无法分配内存”