我需要能够在NodeJS中创建一个与PHP openssl_encrypt相同的加密。出于紧急原因,我们创建了一个PHP,我们的节点服务器使用它来进行加密。我们不能更改PHP中的加密,因为它是一个遗留系统。
使用的键是一个15个字符字符串。使用的iv是一个16字符字符串。
PHP加密API
$string = $_GET["string"];
$key = $_GET["key"];
$iv = $_GET["iv"];
$encrypt_method = 'AES-256-CBC';
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
echo $output;PHP解密API
$string = $_GET["string"];
$key = $_GET["key"];
$iv = $_GET["iv"];
$encrypt_method = 'AES-256-CBC';
$string = base64_decode($string);
$output = openssl_decrypt($string, $encrypt_method, $key, 0, $iv);
echo $output;NodeJS加密
static aesEncrypt = ({ toEncrypt }) => {
const cipher = crypto.createCipheriv('aes-256-cbc', aesKey, aesIv);
let encrypted = cipher.update(toEncrypt, 'utf8', 'base64');
return encrypted + cipher.final('base64');
};NodeJS密码解密
static aesDecrypt = ({ toDecrypt }) => {
const decipher = crypto.createDecipheriv('aes-256-cbc', aesKey, aesIv);
let decrypted = decipher.update(toDecrypt, 'base64', 'utf8');
return decrypted + decipher.final('utf8');
};我用过密码和密码-js,但我不能复制结果。我已经在堆栈溢出中找到了一些例子,但是它们对php加密的使用是不同的,因此得到了不同的结果。
发布于 2022-10-31 08:27:01
PHP代码Base64编码/解码两次。这是不必要的,只会增加要加密/解密的数据量。实际上,PHP代码应该是固定的。但是,由于这显然是一个不能更改的遗留代码,所以必须修改NodeJS代码。
向加密中添加加密文本的附加Base64编码,并将加密文本的附加Base64解码添加到解密中。
对于第二个Base64编码encrypted,必须将utf8 (或latin1)编码到缓冲区中,最后将Base64编码为字符串(反之亦然,用于Base64解码):
const aesEncrypt = (toEncrypt) => {
const cipher = crypto.createCipheriv('aes-256-cbc', aesKey, aesIv);
let encrypted = cipher.update(toEncrypt, 'utf8', 'base64'); // 1st Base64 encoding
encrypted += cipher.final('base64');
return Buffer.from(encrypted, 'utf8').toString('base64'); // 2nd Base64 encoding
};
const aesDecrypt = (toDecrypt) => {
toDecrypt = Buffer.from(toDecrypt, 'base64').toString('utf8'); // 1st Base64 decoding
const decipher = crypto.createDecipheriv('aes-256-cbc', aesKey, aesIv);
let decrypted = decipher.update(toDecrypt, 'base64', 'utf8'); // 2nd Base64 decoding
return decrypted + decipher.final('utf8');
};https://stackoverflow.com/questions/74254859
复制相似问题