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

后端 未结 3 1722
情深已故
情深已故 2020-12-12 14:22

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. <

3条回答
  •  一生所求
    2020-12-12 14:45

    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
    }
    

提交回复
热议问题