【发布时间】:2019-06-06 23:16:01
【问题描述】:
我一直在尝试找出如何制作这个:
function encrypt_decrypt($action, $string) {
$output = false;
$encrypt_method = "AES-256-CBC";
$secret_key = 'HqFdkh2FX126fH1r';
$secret_iv = 'iS2dk82dXd26f61K';
// 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);
if ( $action == 'encrypt' ) {
$output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
$output = base64_encode($output);
} else if( $action == 'decrypt' ) {
$output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
}
return $output;
}
在 Node.js 中
原因是加密由PHP处理,解密由Node处理。
编辑:
我设法做到了这一点:
var crypto = require('crypto')
, key = 'cI8Jd96NDoasd09jcI8Jd96NDoasd09j'
, iv = 'cI8Jd96NDoasd09j'
, plaintext = '2';
hashedKey = crypto.createHash('sha256').update(key, 'utf-8').digest('hex');
console.log('hashed key=', hashedKey);
// corresponds to the hashed key in PHP
hashedIv = crypto.createHash('sha256').update(iv, 'utf-8').digest('hex').substring(0,16);
console.log('hashed iv=', hashedIv);
// corresponds to the hashed iv in PHP
var buf = Buffer.from(teamId, 'base64');
console.log("buffer: " + buf);
而变量buf实际上和PHP代码中的base64_decode($string是一样的。
但是,当我这样做时:
var decipher = crypto.createDecipheriv("aes-256-cbc",key, iv);
var decrypted = decipher.update(buf, 'base64', 'utf8');
console.log("decrypted.toString(): " + decrypted.toString());
我在控制台中收到Z���ߋd�M:��,而不是所需的2。
【问题讨论】:
-
IV 必须相同且密钥
-
他们是。我一直在尝试使用散列键/iv 和未散列来执行此操作,但问题仍然存在。
-
让我纠正一下,php中的密钥是
HqFdkh2FX126fH1r和JScI8Jd96NDoasd09jcI8Jd96NDoasd09j,解密部分在哪里?你看到了吗this -
我明白了。我尝试放置相同的密钥,但在对其进行哈希处理后(就像我在 PHP 中所做的那样)节点抱怨密钥和 iv 字符太多。
-
那是因为您对摘要进行了十六进制编码,因此您的密钥是 64 个字符的字符串。 PHP 的
hash()默认也对哈希进行十六进制编码;如果$raw_output参数设置为 true,它将返回原始字节。
标签: php node.js encryption