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.

unsalted.go 1.5KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. // Copyright (c) 2012-2014 Jeremy Latt
  2. // released under the MIT license
  3. package passwd
  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. // GenerateEncodedPasswordBytes returns an encrypted password, returning the bytes directly.
  14. func GenerateEncodedPasswordBytes(passwd string) (encoded []byte, err error) {
  15. if passwd == "" {
  16. err = ErrEmptyPassword
  17. return
  18. }
  19. encoded, err = bcrypt.GenerateFromPassword([]byte(passwd), bcrypt.MinCost)
  20. return
  21. }
  22. // GenerateEncodedPassword returns an encrypted password, encoded into a string with base64.
  23. func GenerateEncodedPassword(passwd string) (encoded string, err error) {
  24. bcrypted, err := GenerateEncodedPasswordBytes(passwd)
  25. encoded = base64.StdEncoding.EncodeToString(bcrypted)
  26. return
  27. }
  28. // DecodePasswordHash takes a base64-encoded password hash and returns the appropriate bytes.
  29. func DecodePasswordHash(encoded string) (decoded []byte, err error) {
  30. if encoded == "" {
  31. err = ErrEmptyPassword
  32. return
  33. }
  34. decoded, err = base64.StdEncoding.DecodeString(encoded)
  35. return
  36. }
  37. // ComparePassword compares a given password with the given hash.
  38. func ComparePassword(hash, password []byte) error {
  39. return bcrypt.CompareHashAndPassword(hash, password)
  40. }
  41. // ComparePasswordString compares a given password string with the given hash.
  42. func ComparePasswordString(hash []byte, password string) error {
  43. return ComparePassword(hash, []byte(password))
  44. }