【问题标题】:How to use nodejs crypto pbkdf2 salt of type bytes array in php hash_pbkdf2如何在php hash_pbkdf2中使用字节数组类型的nodejs crypto pbkdf2 salt
【发布时间】:2020-10-14 01:27:39
【问题描述】:

我在 Nodejs 和 PHP 中使用 pbkdf2 来获取 KEY 和 IV 值,而如果我尝试使用 salt 值作为字符串,它会给我正确的结果,而如果我必须使用 salt 作为字节数组,那么如何可以在 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));

【问题讨论】:

  • "\x01\x02\x03\x04\x05\x06\x07\x08"
  • @Sammitch 是的,它有效,谢谢
  • 这是用于密钥派生的,对吧?您没有使用它来计算身份验证令牌?
  • @Sammitch 是的,这是为了获取密钥和 iv

标签: php node.js encryption pbkdf2 nodejs-server


【解决方案1】:

盐是:

"\x01\x02\x03\x04\x05\x06\x07\x08"

字面意思就是这样。

或者如果你想让它看起来像 JS 代码一样过于复杂:

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

还有:

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

【讨论】:

    猜你喜欢
    • 2013-06-17
    • 2013-11-17
    • 1970-01-01
    • 2014-02-03
    • 2018-11-22
    • 2014-04-15
    • 2018-09-10
    • 1970-01-01
    • 2017-08-06
    相关资源
    最近更新 更多