密码加密sha1 php到节点js加密

问题描述 投票:0回答:2

我在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'));

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

php node.js sha1 cryptojs
2个回答
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));

0
投票

它们都显示不同的结果,因为在你的PHP代码中你添加了盐,而在NodeJs中你添加了一些盐。这就是为什么两者都有不同的哈希值,但是如果你使用内置函数比较它们,结果应该返回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
© www.soinside.com 2019 - 2024. All rights reserved.