Password Hashing (bcrypt)

This example will show how to hash passwords using bcrypt. For this we have to go get the golang bcrypt library like so:

$ go get golang.org/x/crypto/bcrypt

From now on, every application we write will be able to make use of this library.

  1. // passwords.go
  2. package main
  3. import (
  4. "fmt"
  5. "golang.org/x/crypto/bcrypt"
  6. )
  7. func HashPassword(password string) (string, error) {
  8. bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14)
  9. return string(bytes), err
  10. }
  11. func CheckPasswordHash(password, hash string) bool {
  12. err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password))
  13. return err == nil
  14. }
  15. func main() {
  16. password := "secret"
  17. hash, _ := HashPassword(password) // ignore error for the sake of simplicity
  18. fmt.Println("Password:", password)
  19. fmt.Println("Hash: ", hash)
  20. match := CheckPasswordHash(password, hash)
  21. fmt.Println("Match: ", match)
  22. }
  1. $ go run passwords.go
  2. Password: secret
  3. Hash: $2a$14$ajq8Q7fbtFRQvXpdCq7Jcuy.Rx1h/L4J60Otx.gyNLbAYctGMJ9tK
  4. Match: true