utils.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198
  1. package utils
  2. import (
  3. "bytes"
  4. "crypto/cipher"
  5. "crypto/des"
  6. "crypto/md5"
  7. "crypto/rand"
  8. "encoding/base64"
  9. "encoding/hex"
  10. "github.com/gogf/gf/crypto/gmd5"
  11. "github.com/gogf/gf/encoding/gcharset"
  12. "github.com/gogf/gf/encoding/gjson"
  13. "github.com/gogf/gf/frame/g"
  14. "github.com/gogf/gf/net/ghttp"
  15. "github.com/gogf/gf/os/glog"
  16. "github.com/gogf/gf/os/gtime"
  17. "github.com/gogf/gf/text/gstr"
  18. "github.com/mojocn/base64Captcha"
  19. "io"
  20. "time"
  21. )
  22. var (
  23. Letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" // 52
  24. Symbols = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" // 32
  25. Digits = "0123456789" // 10
  26. Characters = Letters + Digits + Symbols // 94
  27. LetterDigits = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
  28. )
  29. // 密码加密
  30. func EncryptPassword(password, salt string) string {
  31. return gmd5.MustEncryptString(gmd5.MustEncryptString(password) + gmd5.MustEncryptString(salt))
  32. }
  33. // 随机生成字符串
  34. func GetRandomString(n int) string {
  35. const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  36. var bytes = make([]byte, n)
  37. rand.Read(bytes)
  38. for i, b := range bytes {
  39. bytes[i] = alphanum[b%byte(len(alphanum))]
  40. }
  41. return string(bytes)
  42. }
  43. // TripleDesEncrypt 3DES加密
  44. func TripleDesEncrypt(p string) (string, string, error) {
  45. //k := "squR7K1XZapjhQgEjOPFyEPp"
  46. k := GetRandomString(24)
  47. origData := []byte(p)
  48. key := []byte(k)
  49. block, err := des.NewTripleDESCipher(key)
  50. if err != nil {
  51. return "", k, err
  52. }
  53. origData = PKCS5Padding(origData, block.BlockSize())
  54. // origData = ZeroPadding(origData, block.BlockSize())
  55. blockMode := cipher.NewCBCEncrypter(block, key[:8])
  56. crypted := make([]byte, len(origData))
  57. blockMode.CryptBlocks(crypted, origData)
  58. return base64.StdEncoding.EncodeToString(crypted), k, nil
  59. }
  60. // TripleDesDecrypt 3DES解密
  61. func TripleDesDecrypt(p, k string) (string, error) {
  62. crypted, _ := base64.StdEncoding.DecodeString(p)
  63. key := []byte(k)
  64. block, err := des.NewTripleDESCipher(key)
  65. if err != nil {
  66. return "", err
  67. }
  68. blockMode := cipher.NewCBCDecrypter(block, key[:8])
  69. origData := make([]byte, len(crypted))
  70. blockMode.CryptBlocks(origData, crypted)
  71. origData = PKCS5UnPadding(origData)
  72. return string(origData), nil
  73. }
  74. func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
  75. padding := blockSize - len(ciphertext)%blockSize
  76. padtext := bytes.Repeat([]byte{byte(padding)}, padding)
  77. return append(ciphertext, padtext...)
  78. }
  79. func PKCS5UnPadding(origData []byte) []byte {
  80. length := len(origData)
  81. // 去掉最后一个字节 unpadding 次
  82. unpadding := int(origData[length-1])
  83. return origData[:(length - unpadding)]
  84. }
  85. func Md5(str string) string {
  86. h := md5.New()
  87. h.Write([]byte(str))
  88. return hex.EncodeToString(h.Sum(nil))
  89. }
  90. func GetGuid() string {
  91. b := make([]byte, 48)
  92. if _, err := io.ReadFull(rand.Reader, b); err != nil {
  93. return ""
  94. }
  95. return Md5(base64.URLEncoding.EncodeToString(b))
  96. }
  97. // 获取字母数字混合验证码(用于Captcha验证)
  98. func GetVerifyImgString() (idKeyC string, base64stringC string) {
  99. driver := &base64Captcha.DriverString{
  100. Height: 80,
  101. Width: 240,
  102. NoiseCount: 50,
  103. ShowLineOptions: 20,
  104. Length: 4,
  105. Source: "abcdefghjkmnpqrstuvwxyz23456789",
  106. Fonts: []string{"chromohv.ttf"},
  107. }
  108. driver = driver.ConvertFonts()
  109. store := base64Captcha.DefaultMemStore
  110. c := base64Captcha.NewCaptcha(driver, store)
  111. idKeyC, base64stringC, err := c.Generate()
  112. if err != nil {
  113. glog.Error(err)
  114. }
  115. return
  116. }
  117. // 验证输入的验证码是否正确(用于Captcha验证)
  118. func VerifyString(id, answer string) bool {
  119. driver := new(base64Captcha.DriverString)
  120. store := base64Captcha.DefaultMemStore
  121. c := base64Captcha.NewCaptcha(driver, store)
  122. answer = gstr.ToLower(answer)
  123. return c.Verify(id, answer, true)
  124. }
  125. // 获取ip所属城市
  126. func GetCityByIp(ip string) string {
  127. if ip == "" {
  128. return ""
  129. }
  130. if ip == "[::1]" || ip == "127.0.0.1" {
  131. return "内网IP"
  132. }
  133. url := "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=" + ip
  134. bytes := ghttp.GetBytes(url)
  135. src := string(bytes)
  136. srcCharset := "GBK"
  137. tmp, _ := gcharset.ToUTF8(srcCharset, src)
  138. json, err := gjson.DecodeToJson(tmp)
  139. if err != nil {
  140. return ""
  141. }
  142. if json.GetInt("code") == 0 {
  143. city := json.GetString("city")
  144. return city
  145. } else {
  146. return ""
  147. }
  148. }
  149. // GetHourDiffer 获取相差时间
  150. func GetHourDiffer(startTime, endTime string) int64 {
  151. var hour int64
  152. t1, err := time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
  153. t2, err := time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
  154. if err == nil && t1.Before(t2) {
  155. diff := t2.Unix() - t1.Unix() //
  156. hour = diff / 3600
  157. return hour
  158. } else {
  159. return hour
  160. }
  161. }
  162. // StrToTimestamp 日期字符串转时间戳(秒)
  163. func StrToTimestamp(dateStr string) int64 {
  164. tm, err := gtime.StrToTime(dateStr)
  165. if err != nil {
  166. g.Log().Error(err)
  167. return 0
  168. }
  169. return tm.Timestamp()
  170. }
  171. // TimeStampToDateTimeStr 时间戳转 yyyy-MM-dd HH:mm:ss
  172. func TimeStampToDateTimeStr(timeStamp int64) string {
  173. tm := gtime.NewFromTimeStamp(timeStamp)
  174. return tm.Format("Y-m-d H:i:s")
  175. }
  176. // TimeStampToDateStr 时间戳转 yyyy-MM-dd
  177. func TimeStampToDateStr(timeStamp int64) string {
  178. tm := gtime.NewFromTimeStamp(timeStamp)
  179. return tm.Format("Y-m-d")
  180. }