在Golang中加密密码哈希(与Node.js兼容)? [英] Bcrypt password hashing in Golang (compatible with Node.js)?

查看:406
本文介绍了在Golang中加密密码哈希(与Node.js兼容)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Node.js +护照为用户身份验证设置了一个站点。

现在我需要迁移到Golang,并且需要使用保存在db中的用户密码进行身份验证。



Node.js加密代码是:

  var bcrypt =要求( 'bcrypt'); 

bcrypt.genSalt(10,函数(err,salt){
if(err)return next(err);

bcrypt.hash(user.password ,salt,function(err,hash){
if(err)return next(err);
user.password = hash;
next();
});
});

如何与Node.js一起使用与Golang相同的散列字符串?

解决方案

使用 golang.org/x/crypto/bcrypt 包,我相信相当于:

  hashedPassword,err: = bcrypt.GenerateFromPassword(password,bcrypt.DefaultCost)

工作示例:

 包主

导入(
golang.org/x/crypto/bcrypt
fmt


func main(){
password:= [] byte(MyDarkSecret)

/ /散列密码的默认值为10
hashedPassword,err:= bcrypt.GenerateFromPassword(password,bcrypt.DefaultCost)
if err!= nil {
panic(err)
}
fmt.Println(string(hashedPassword))

//比较密码和散列
e rr = bcrypt.CompareHashAndPassword(hashedPassword,password)
fmt.Println(err)// nil表示它是匹配
}


I set up a site with Node.js+passport for user authentication.

Now I need to migrate to Golang, and need to do authentication with the user passwords saved in db.

The Node.js encryption code is:

    var bcrypt = require('bcrypt');

    bcrypt.genSalt(10, function(err, salt) {
        if(err) return next(err);

        bcrypt.hash(user.password, salt, function(err, hash) {
            if(err) return next(err);
            user.password = hash;
            next();
        });
    });

How to make the same hashed string as Node.js bcrypt with Golang?

解决方案

Using the golang.org/x/crypto/bcrypt package, I believe the equivalent would be:

hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)

Working example:

package main

import (
    "golang.org/x/crypto/bcrypt"
    "fmt"
)

func main() {
    password := []byte("MyDarkSecret")

    // Hashing the password with the default cost of 10
    hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
    if err != nil {
        panic(err)
    }
    fmt.Println(string(hashedPassword))

    // Comparing the password with the hash
    err = bcrypt.CompareHashAndPassword(hashedPassword, password)
    fmt.Println(err) // nil means it is a match
}

这篇关于在Golang中加密密码哈希(与Node.js兼容)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆