【问题标题】:Password encryption sha1 php to node js crypto密码加密 sha1 php 到节点 js 加密
【发布时间】:2019-09-09 10:28:34
【问题描述】:

我在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;
}

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

这是我尝试过的。

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

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

【问题讨论】:

  • 你做不同的事情。首先,一定要使用相同的saltpassword。然后在您的 php 代码中,在计算结果时使用两次salt。这当然会导致不同的结果

标签: php node.js sha1 cryptojs


【解决方案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));

【讨论】:

  • 这非常接近。
  • 检查哈希结果:VT3R9IR7dZDX+MHMPZWKfg/aGN8=993f075527 VT3R9IR7dZDX+MHMPZWKfg/aGN85OTNmMDc1NTI3 第一个来自您的节点,第二个来自 PHP
  • 我猜主要区别是盐,$encrypted_pa​​ssword = base64_encode(sha1($password . $salt, true).$salt);这条线在base64中覆盖了盐,但在节点中没有,任何想法@terry感谢您的帮助。
  • @RutulPatel 酷,让我检查一下代码,我会更新。
  • 我已经更新了代码,你可以试试,谢谢!
【解决方案2】:

它们都显示不同的结果,因为在您的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-03
    • 2012-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-26
    相关资源
    最近更新 更多