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

node.jsGoBcrypt

node.js Problem Overview


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?

node.js Solutions


Solution 1 - node.js

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
}

Solution 2 - node.js

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

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 ;)

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

Solution 3 - node.js

Firstly you need import the bcrypt package

go get golang.org/x/crypto/bcrypt

Then use GenerateFromPassword

bs, err := bcrypt.GenerateFromPassword([]byte(p), bcrypt.MinCost)
	if err != nil {
		http.Error(w, "Internal server error", http.StatusInternalServerError)
		return
	}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCid HuangView Question on Stackoverflow
Solution 1 - node.jsANisusView Answer on Stackoverflow
Solution 2 - node.jsrob74View Answer on Stackoverflow
Solution 3 - node.jsRohanView Answer on Stackoverflow