選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

unsalted.go 1.3KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  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. // 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. }
  39. // ComparePasswordString compares a given password string with the given hash.
  40. func ComparePasswordString(hash []byte, password string) error {
  41. return ComparePassword(hash, []byte(password))
  42. }