utils.go 5.7 KB

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