【发布时间】:2019-02-22 12:02:05
【问题描述】:
我有一个 API,要求我对通过 AES 密码发送给它的数据进行编码。
但是,我得到的唯一示例代码是 Node.js 代码。
我想,用 PHP 重新实现它有多难?
显然很难。
您可以在下面看到这两种方法,但您也可以看到不同的结果。
有人知道可能出了什么问题吗?
NODE.js 版本
var crypto = require('crypto');
var algorithm = 'aes-128-ctr';
function encrypt(text, password) {
const key = Buffer.from(password, "hex").slice(0, 16);
const ivBuffer = Buffer.alloc(16);
const cipher = crypto.createCipheriv(algorithm, key, ivBuffer);
let crypted = cipher.update(text, "utf8", 'hex');
crypted += cipher.final('hex');
console.log(crypted);
}
encrypt('test','ed8f68b144f94c30b8add43276f0fa14');
结果:3522ca23
PHP 版本
function encrypt($text, $password) {
$iv = "0000000000000000";
$encrypted = openssl_encrypt($text, 'aes-128-ctr', $password, OPENSSL_RAW_DATA, $iv);
return bin2hex($encrypted);
}
echo encrypt('test', 'ed8f68b144f94c30b8add43276f0fa14');
结果:8faa39d2
【问题讨论】:
-
您使用不同的密钥和 IV。在 PHP 中,您不是对密钥进行十六进制解码,因此它是一个 32 字节的 a-f0-9 字符串。此外,您在 PHP 中的 IV 是 16 个零字符,而不是 16 个零字节。
-
在浏览相关部分时,我已经遇到了一个似乎符合您逻辑的解决方案。还是谢谢你的回复!!
-
没问题!你知道,你可以发布一个答案,如果你认为它可能对其他人有用。
-
我刚刚做了,请随意看看我是否正确理解了我的错误所在:)
标签: php node.js encryption aes