Password Hashing (bcrypt)

这个例子将展示如何使用bcrypt 来hash 密码. 为了使用它,我们需要 go get bcrypt 这个库:

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

接下来,我们所有的应用都将使用这个库..

  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