gpt4 book ai didi

php - 无法对 PHP 等效 NodeJS 加密进行加密/解密

转载 作者:太空宇宙 更新时间:2023-11-03 22:42:05 24 4
gpt4 key购买 nike

我在 PHP 中进行 AES-256-CTR 加密/解密时遇到了一些麻烦,因为之前使用 NodeJS 加密制作了加密字符串。

这是我的 JS 代码:

var crypto = require('crypto'),
algorithm = 'aes-256-ctr',
password = 'd6F3Efeq';

function encrypt(text){
var cipher = crypto.createCipher(algorithm,password)
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}

function decrypt(text){
var decipher = crypto.createDecipher(algorithm,password)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}

这是我的 PHP 代码:

$text = "pereira";

echo bin2hex(openssl_encrypt($text, "aes-256-ctr", "d6F3Efeq",OPENSSL_RAW_DATA));

JS 的版本在加密时返回此:

148bc695286379

PHP 版本在我的加密测试中返回此信息:

2f2ad5bb09fb56

我在这里遗漏了什么吗?显然,我都无法在 PHP 中正确解密。

提前致谢。

最佳答案

您必须在两侧设置 iv(初始化向量)。

Node JS 代码:

var crypto = require('crypto'),
password = '1234567890abcdef1234567890abcdef',
iv = '1234567890abcdef',
text = "pereira";

function encrypt(iv, text, password){
var cipher = crypto.createCipheriv('aes-256-ctr', password, iv)
var crypted = cipher.update(text,'utf8','hex')
crypted += cipher.final('hex');
return crypted;
}

function decrypt(iv, text, password){
var decipher = crypto.createDecipheriv('aes-256-ctr', password, iv)
var dec = decipher.update(text,'hex','utf8')
dec += decipher.final('utf8');
return dec;
}
console.log(encrypt(iv, text, password));

和 PHP 代码:

$text = 'pereira';
$algorithm = 'aes-256-ctr';
$password = '1234567890abcdef1234567890abcdef'; //node js required 32 byte length key
$iv = '1234567890abcdef'; //must be 16 byte length
echo bin2hex(openssl_encrypt($text, $algorithm, $password, OPENSSL_RAW_DATA, $iv));

关于php - 无法对 PHP 等效 NodeJS 加密进行加密/解密,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48441285/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com