在Nodejs中加密,在PHP中解密
我正在尝试用PHP解密一个字符串,它最初是在NodeJS中加密的 PHP:在Nodejs中加密,在PHP中解密,php,encryption,openssl,node-crypto,Php,Encryption,Openssl,Node Crypto,我正在尝试用PHP解密一个字符串,它最初是在NodeJS中加密的 PHP: openssl\u decrypt($raw\u id,“aes-128-cbc”,“s7UbmJpfm56r6CAC6mz7KVZdRc3Fxc4m”,0,空) 这似乎总是返回false Nodejs中的加密: function encrypt(text) { var cipher = crypto.createCipher('aes-128-cbc', 's7UbmJpfm56r6CAC6mz7KVZdRc3
openssl\u decrypt($raw\u id,“aes-128-cbc”,“s7UbmJpfm56r6CAC6mz7KVZdRc3Fxc4m”,0,空)
这似乎总是返回false
Nodejs中的加密:
function encrypt(text) {
var cipher = crypto.createCipher('aes-128-cbc', 's7UbmJpfm56r6CAC6mz7KVZdRc3Fxc4m');
var encrypted = cipher.update(text, 'utf8', 'hex')
encrypted += cipher.final('hex')
return encrypted;
}
function decrypt(text) {
var cipher = crypto.createDecipher('aes-128-cbc', 's7UbmJpfm56r6CAC6mz7KVZdRc3Fxc4m');
var decrypted = cipher.update(text, 'hex', 'utf8')
decrypted += cipher.final('utf8');
return decrypted;
}
我基本上想要加密,例如,加密(“Pizza”)
在Nodejs中,将它发送到PHP页面(3879f91a59e9a458db62f905b0a488a1
),然后从那里解密它(openssl\u decrypt:return Pizza
)
我知道这个代码是不安全的,因为我不使用IV,但是我不知道如何加一个。
< P>你的方法不安全,也可能是中间攻击的受害者,你应该总是使用IV和HMAC。 您可以像这样在php中加密$key = substr('encyptionsec123342',0,32)
function encrypt ($message, $method, $secret, &$hmac) {
$iv = substr(bin2hex(openssl_random_pseudo_bytes(16)),0,16);
$encrypted = base64_encode($iv) . openssl_encrypt($message, $method, $secret, 0, $iv);
$hmac = hash_hmac('md5', $encrypted, $secret);
return $encrypted;
}
function decrypt ($encrypted, $method, $secret, $hmac) {
if (hash_hmac('md5', $encrypted, $secret) == $hmac) {
$iv = base64_decode(substr($encrypted, 0, 24));
return openssl_decrypt(substr($encrypted, 24), $method, $secret, 0, $iv);
}
}
function encryptWithTSValidation ($message, $method, $secret, &$hmac) {
date_default_timezone_set('UTC');
$message = substr(date('c'),0,19) . "$message";
return encrypt($message, $method, $secret, $hmac);
}
function decryptWithTSValidation ($encrypted, $method, $secret, $hmac, $intervalThreshold) {
$decrypted = decrypt($encrypted, $method, $secret, $hmac);
$now = new DateTime();
$msgDate = new DateTime(str_replace("T"," ",substr($decrypted,0,19)));
if (($now->getTimestamp() - $msgDate->getTimestamp()) <= $intervalThreshold) {
return substr($decrypted,19);
}
}
要生成hmac,可以使用简单的md5哈希
$hmac = hash_hmac('md5', $recipent, $key);
在node.js中
var decrypted = decryptWithTSValidation(encString, method, secret, hmac, 60 * 60);
var encrypted = decryptWithTSValidation(string, method, secret, hmac);
注意:确保在nodejs和php中进行加密和解密时使用32位的唯一密钥。还要确保其安全,切勿将其存储在数据库中。代码参考:@AppelFlap乐意帮忙这里的MitM攻击是什么?如果您想建议更好的替代方案,建议使用TLS 1中包含的AES-GCM身份验证加密。4@kelalakanodejs用于“实时”应用程序,用户可能在web套接字等中使用它。@kelalaka不,我的意思是op可能在像WebCokets这样的直接通信中使用它也许这就是为什么他像我曾经做的那样集成node.js和php
$hmac = hash_hmac('md5', $recipent, $key);
var decrypted = decryptWithTSValidation(encString, method, secret, hmac, 60 * 60);
var encrypted = decryptWithTSValidation(string, method, secret, hmac);