patternjavascriptCritical
Bcrypt password hashing in Golang (compatible with Node.js)?
Viewed 0 times
withhashingpasswordbcryptgolangnodecompatible
Problem
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:
How to make the same hashed string as Node.js bcrypt with Golang?
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?
Solution
Using the golang.org/x/crypto/bcrypt package, I believe the equivalent would be:
Working example:
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
}Code Snippets
hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)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
}Context
Stack Overflow Q#23259586, score: 166
Revisions (0)
No revisions yet.