密码加密sha1 php到node js crypto

时间:2019-04-19 05:20:48

标签: php node.js sha1 cryptojs

我在php中有这两个功能。

public function hashSSHA($password) {
    $salt = sha1(rand());
    $salt = substr($salt, 0, 10);
    $encrypted_password = base64_encode(sha1($password . $salt, true).$salt);
    $hash = array("salt"=>$salt, "encrypted"=>$encrypted_password);
    return $hash;
}

//Password Decryption 
public function checkhashSSHA($salt, $password) {
    $hash = base64_encode(sha1($password . $salt, true).$salt);
    return $hash;
}

我正在尝试在节点js中编写这两个函数。

这是我尝试过的东西。

const hash = crypto.createHash('sha1', 'my different salt from DB');
hash.update(password);
console.log(hash.digest('base64'));

但是他们都产生了不同的结果。

2 个答案:

答案 0 :(得分:1)

这些Node.js函数应等效于您的PHP代码:

const crypto = require("crypto");

function hashSSHA(password){
    let salt = crypto.createHash('sha1').update(crypto.randomBytes(8)).digest('base64');
    salt = salt.substring(0,10);
    const hash = crypto.createHash('sha1');
    hash.update(password + salt);
    return {
        salt: salt,
        encrypted: Buffer.concat([hash.digest(), Buffer.from(salt)]).toString('base64')
    };
};

function checkhashSSHA(salt, password) {
    const hash = crypto.createHash('sha1');
    hash.update(password + salt);
    return Buffer.concat([hash.digest(), Buffer.from(salt)]).toString('base64');
}

const password = "some password";
const hashResult = hashSSHA(password);
console.log("Hash result: ", hashResult);
console.log("Check hash result: ", checkhashSSHA(hashResult.salt, password));

答案 1 :(得分:0)

它们都显示不同的结果,因为在PHP代码中添加了盐,而在NodeJ中添加了其他盐。这就是为什么两者都有不同的哈希值的原因,但是如果您使用内置函数比较它们,则结果应返回true。

npm install bcrypt

...

var bcrypt = require('bcrypt');
var hash = bcrypt.hashSync("my password");

bcrypt.compareSync("my password", hash); // true
bcrypt.compareSync("not my password", hash); // false