如何在 php hash_pbkdf2 中使用 nodejs 加密 pbkdf2 类型字节数组的盐



我在 Nodejs 和 PHP 中使用 pbkdf2 来获取 KEY 和 IV 值,而如果我尝试使用盐值作为字符串,它会给我正确的结果,而如果我必须使用盐作为字节数组,那么如何在 PHP 端完成它:new Buffer.from([1, 2, 3, 4, 5, 6, 7, 8], "utf-8")

Nodejs:

const crypto = require('crypto');
const encryptKey = '012345678901234599887767';
var password = Buffer.from(encryptKey, "utf-8");
var hashPassword = crypto.createHash('sha256').update(password).digest();
const salt = new Buffer.from([1, 2, 3, 4, 5, 6, 7, 8], "utf-8");
crypto.pbkdf2(hashPassword, salt, 1000, 48, 'SHA1', (err, key) => {
var key1 = key.slice(0, 32);
var iv1  = key.slice(32, 48);
console.log(key1.toString('base64')); //+Zh7sEM+QMPGIQeNz3tiIyrZSK1ibvRlLUTnBlJYkIE=
console.log(iv1.toString('base64'));  //VgxNzyZJGvrd77wLuz3G8g==
});

.PHP:

$salt = " "; 
//how to use salt as bytes as same as we are doing in Nodejs crypto as hash_pbkdf2 only allowed salt value as a string 
//and if I convert salt byte value as a string then it is giving me different KEY AND IV
$pass = "012345678901234599887767";
$hashPass = hash("sha256",mb_convert_encoding($pass,"UTF-8"),true); 
$hash = hash_pbkdf2("SHA1", $hashPass, $salt , 1000, 48,true);
echo base64_encode(substr($hash , 0, 32));
echo '<br/>'.base64_encode(substr($hash , 32, 48));

盐是:

"x01x02x03x04x05x06x07x08"

所以从字面上看。

或者,如果您希望它看起来像JS代码一样过于复杂:

$salt = implode('', array_map('chr', [ 1, 2, 3, 4, 5, 6, 7, 8 ]));

也:

  1. 每个哈希的盐应该是唯一的。
  2. 盐不被视为秘密价值。
  3. 大多数密码散列库只是将盐打包到输出的前 X 字节中。

最新更新