Golang 中的 Bcrypt 密码哈希(与 Node.js 兼容)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23259586/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 17:12:22  来源:igfitidea点击:

Bcrypt password hashing in Golang (compatible with Node.js)?

node.jsgobcrypt

提问by Cid Huang

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

我使用 Node.js+passport 建立了一个站点以进行用户身份验证。

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

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

The Node.js encryption code is:

Node.js 加密代码是:

    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?

如何使用 Golang 制作与 Node.js bcrypt 相同的散列字符串?

回答by ANisus

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

使用golang.org/x/crypto/bcrypt包,我相信等效的将是:

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
}

回答by rob74

Take a look at the bcrypt packagefrom go.crypto(docs are here).

看看在bcrypt包go.crypto(文档是在这里)。

To install it, use

要安装它,请使用

go get golang.org/x/crypto/bcrypt

A blog entry describing the usage of the bcrypt package can be found here. It's from the guy who wrote the package, so it should work ;)

可以在此处找到描述 bcrypt 包用法的博客条目。它来自编写包的人,所以它应该可以工作;)

One difference to the node.js library you are using is that the go package doesn't have an (exported) genSaltfunction, but it will generate the salt automatically when you call bcrypt.GenerateFromPassword.

与您使用的 node.js 库的一个区别是 go 包没有(导出的)genSalt函数,但是当您调用bcrypt.GenerateFromPassword.