pwd.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. // Copyright (c) 2015 qianqiusoft.com
  2. // Licensed to You under the GNU Affero GPL v3
  3. // See the LICENSE file at git.qianqiusoft.com/qianqiusoft/light-vocation/LICENSE
  4. // http://www.gnu.org/licenses/why-affero-gpl.en.html
  5. package utils
  6. import (
  7. "crypto/md5"
  8. "encoding/base64"
  9. "encoding/hex"
  10. "git.qianqiusoft.com/qianqiusoft/light-apiengine/config"
  11. "git.qianqiusoft.com/qianqiusoft/light-apiengine/logs"
  12. )
  13. type LoginCheck interface {
  14. AddPwdErrNum(string) bool
  15. CheckErrNum(string) bool
  16. }
  17. var globalLoginCheck LoginCheck
  18. func GetGlobalLoginCheck() LoginCheck {
  19. return globalLoginCheck
  20. }
  21. func SetGlobalLoginCheck(loginCheck LoginCheck) {
  22. globalLoginCheck = loginCheck
  23. }
  24. func HashPassword(password, salt string) string {
  25. h := md5.New()
  26. enableDbSalt := config.AppConfig.GetBool("enable_db_salt", true)
  27. customSalt := config.AppConfig.GetKey("password_salt")
  28. enableBase64 := config.AppConfig.GetBool("password_enable_base64", true)
  29. if !enableDbSalt {
  30. h.Write([]byte(password))
  31. if len(customSalt) > 0 {
  32. //fmt.Println(customSalt)
  33. md5Str := base64.StdEncoding.EncodeToString(h.Sum(nil))
  34. h.Reset()
  35. h.Write([]byte(md5Str + customSalt))
  36. }
  37. if enableBase64 {
  38. base64_str := base64.StdEncoding.EncodeToString(h.Sum(nil))
  39. logs.Debug("启用编码:", base64_str)
  40. return base64_str
  41. } else {
  42. str := hex.EncodeToString(h.Sum(nil))
  43. logs.Debug("未启用编码:", str)
  44. return str
  45. }
  46. } else {
  47. h.Write([]byte(password))
  48. md5Str := hex.EncodeToString(h.Sum(nil))
  49. logs.Debug("第一次加密:", md5Str)
  50. if len(salt) > 0 {
  51. h.Reset()
  52. h.Write([]byte(md5Str + salt))
  53. md5Str = hex.EncodeToString(h.Sum(nil))
  54. }
  55. logs.Debug("第二次加密:", md5Str)
  56. return md5Str
  57. }
  58. }