password.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. package utils
  2. import (
  3. "errors"
  4. "golang.org/x/crypto/bcrypt"
  5. )
  6. // EncryptPassword hashes the input password using bcrypt.
  7. // An error is returned if hashing fails.
  8. func EncryptPassword(password string) (string, error) {
  9. bs, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
  10. if err != nil {
  11. return "", err
  12. }
  13. return string(bs), nil
  14. }
  15. // VerifyPassword checks the input password against the stored hash.
  16. // When a legacy MD5 hash is provided, the password is rehashed with bcrypt
  17. // and the new hash is returned. Any internal bcrypt error is returned.
  18. func VerifyPassword(hash, input string) (bool, string, error) {
  19. err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(input))
  20. if err == nil {
  21. return true, "", nil
  22. }
  23. var invalidPrefixErr bcrypt.InvalidHashPrefixError
  24. if errors.As(err, &invalidPrefixErr) || errors.Is(err, bcrypt.ErrHashTooShort) {
  25. // Try fallback to legacy MD5 hash verification
  26. if hash == Md5(input+"rustdesk-api") {
  27. newHash, err2 := bcrypt.GenerateFromPassword([]byte(input), bcrypt.DefaultCost)
  28. if err2 != nil {
  29. return true, "", err2
  30. }
  31. return true, string(newHash), nil
  32. }
  33. }
  34. if errors.Is(err, bcrypt.ErrMismatchedHashAndPassword) {
  35. return false, "", nil
  36. }
  37. return false, "", err
  38. }