utils.go 5.6 KB

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