Bcrypt Password Hashing Compatibility between Go and Node.js
In migrating from Node.js to Go, it is essential to maintain backward compatibility with user passwords stored in the database. This requires replicating Node.js's bcrypt password hashing functionality in Go.
In Node.js, the bcrypt encryption code utilizes the bcrypt library to generate a salted hash from a user's password. The equivalent code in Go, using the golang.org/x/crypto/bcrypt package, is:
hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost)
This function produces a hashed password string compatible with the output generated by the Node.js code.
The following working Go example demonstrates the bcrypt password hashing process:
package main import ( "golang.org/x/crypto/bcrypt" "fmt" ) func main() { password := []byte("SomeSecretPassword") hashedPassword, err := bcrypt.GenerateFromPassword(password, bcrypt.DefaultCost) if err != nil { panic(err) } fmt.Println(string(hashedPassword)) err = bcrypt.CompareHashAndPassword(hashedPassword, password) if err == nil { fmt.Println("Password matches hash.") } else { fmt.Println("Password does not match hash.") } }
The above is the detailed content of How Can I Ensure Bcrypt Password Hashing Compatibility Between Go and Node.js?. For more information, please follow other related articles on the PHP Chinese website!