You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

password.go 1.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // released under the MIT license
  3. package irc
  4. import (
  5. "encoding/base64"
  6. "errors"
  7. "golang.org/x/crypto/bcrypt"
  8. )
  9. var (
  10. // ErrEmptyPassword means that an empty password was given.
  11. ErrEmptyPassword = errors.New("empty password")
  12. )
  13. // GenerateEncodedPassword returns an encrypted password, encoded into a string with base64.
  14. func GenerateEncodedPassword(passwd string) (encoded string, err error) {
  15. if passwd == "" {
  16. err = ErrEmptyPassword
  17. return
  18. }
  19. bcrypted, err := bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.MinCost)
  20. if err != nil {
  21. return
  22. }
  23. encoded = base64.StdEncoding.EncodeToString(bcrypted)
  24. return
  25. }
  26. // DecodePasswordHash takes a base64-encoded password hash and returns the appropriate bytes.
  27. func DecodePasswordHash(encoded string) (decoded []byte, err error) {
  28. if encoded == "" {
  29. err = ErrEmptyPassword
  30. return
  31. }
  32. decoded, err = base64.StdEncoding.DecodeString(encoded)
  33. return
  34. }
  35. // ComparePassword compares a given password with the given hash.
  36. func ComparePassword(hash, password []byte) error {
  37. return bcrypt.CompareHashAndPassword(hash, password)
  38. }