| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227 |
- package utils
- import (
- "bytes"
- "crypto/cipher"
- "crypto/des"
- "crypto/md5"
- "crypto/rand"
- "encoding/base64"
- "encoding/hex"
- "encoding/json"
- "fmt"
- "github.com/gogf/gf/crypto/gmd5"
- "github.com/gogf/gf/encoding/gcharset"
- "github.com/gogf/gf/encoding/gjson"
- "github.com/gogf/gf/frame/g"
- "github.com/gogf/gf/net/ghttp"
- "github.com/gogf/gf/os/glog"
- "github.com/gogf/gf/os/gtime"
- "github.com/gogf/gf/text/gstr"
- "github.com/mojocn/base64Captcha"
- "io"
- "strings"
- "time"
- )
- var (
- Letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" // 52
- Symbols = "!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~" // 32
- Digits = "0123456789" // 10
- Characters = Letters + Digits + Symbols // 94
- LetterDigits = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
- )
- // 密码加密
- func EncryptPassword(password, salt string) string {
- return gmd5.MustEncryptString(gmd5.MustEncryptString(password) + gmd5.MustEncryptString(salt))
- }
- // 随机生成字符串
- func GetRandomString(n int) string {
- const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
- var bytes = make([]byte, n)
- rand.Read(bytes)
- for i, b := range bytes {
- bytes[i] = alphanum[b%byte(len(alphanum))]
- }
- return string(bytes)
- }
- // TripleDesEncrypt 3DES加密
- func TripleDesEncrypt(p string) (string, string, error) {
- //k := "squR7K1XZapjhQgEjOPFyEPp"
- k := GetRandomString(24)
- origData := []byte(p)
- key := []byte(k)
- block, err := des.NewTripleDESCipher(key)
- if err != nil {
- return "", k, err
- }
- origData = PKCS5Padding(origData, block.BlockSize())
- // origData = ZeroPadding(origData, block.BlockSize())
- blockMode := cipher.NewCBCEncrypter(block, key[:8])
- crypted := make([]byte, len(origData))
- blockMode.CryptBlocks(crypted, origData)
- return base64.StdEncoding.EncodeToString(crypted), k, nil
- }
- // TripleDesDecrypt 3DES解密
- func TripleDesDecrypt(p, k string) (string, error) {
- crypted, _ := base64.StdEncoding.DecodeString(p)
- key := []byte(k)
- block, err := des.NewTripleDESCipher(key)
- if err != nil {
- return "", err
- }
- blockMode := cipher.NewCBCDecrypter(block, key[:8])
- origData := make([]byte, len(crypted))
- blockMode.CryptBlocks(origData, crypted)
- origData = PKCS5UnPadding(origData)
- return string(origData), nil
- }
- func PKCS5Padding(ciphertext []byte, blockSize int) []byte {
- padding := blockSize - len(ciphertext)%blockSize
- padtext := bytes.Repeat([]byte{byte(padding)}, padding)
- return append(ciphertext, padtext...)
- }
- func PKCS5UnPadding(origData []byte) []byte {
- length := len(origData)
- // 去掉最后一个字节 unpadding 次
- unpadding := int(origData[length-1])
- return origData[:(length - unpadding)]
- }
- func Md5(str string) string {
- h := md5.New()
- h.Write([]byte(str))
- return hex.EncodeToString(h.Sum(nil))
- }
- func GetGuid() string {
- b := make([]byte, 48)
- if _, err := io.ReadFull(rand.Reader, b); err != nil {
- return ""
- }
- return Md5(base64.URLEncoding.EncodeToString(b))
- }
- // 获取字母数字混合验证码(用于Captcha验证)
- func GetVerifyImgString() (idKeyC string, base64stringC string) {
- driver := &base64Captcha.DriverString{
- Height: 80,
- Width: 240,
- NoiseCount: 50,
- ShowLineOptions: 20,
- Length: 4,
- Source: "abcdefghjkmnpqrstuvwxyz23456789",
- Fonts: []string{"chromohv.ttf"},
- }
- driver = driver.ConvertFonts()
- store := base64Captcha.DefaultMemStore
- c := base64Captcha.NewCaptcha(driver, store)
- idKeyC, base64stringC, err := c.Generate()
- if err != nil {
- glog.Error(err)
- }
- return
- }
- // 验证输入的验证码是否正确(用于Captcha验证)
- func VerifyString(id, answer string) bool {
- driver := new(base64Captcha.DriverString)
- store := base64Captcha.DefaultMemStore
- c := base64Captcha.NewCaptcha(driver, store)
- answer = gstr.ToLower(answer)
- return c.Verify(id, answer, true)
- }
- // 获取ip所属城市
- func GetCityByIp(ip string) string {
- if ip == "" {
- return ""
- }
- if ip == "[::1]" || ip == "127.0.0.1" {
- return "内网IP"
- }
- url := "http://whois.pconline.com.cn/ipJson.jsp?json=true&ip=" + ip
- bytes := ghttp.GetBytes(url)
- src := string(bytes)
- srcCharset := "GBK"
- tmp, _ := gcharset.ToUTF8(srcCharset, src)
- json, err := gjson.DecodeToJson(tmp)
- if err != nil {
- return ""
- }
- if json.GetInt("code") == 0 {
- city := json.GetString("city")
- return city
- } else {
- return ""
- }
- }
- // GetHourDiffer 获取相差时间
- func GetHourDiffer(startTime, endTime string) int64 {
- var hour int64
- t1, err := time.ParseInLocation("2006-01-02 15:04:05", startTime, time.Local)
- t2, err := time.ParseInLocation("2006-01-02 15:04:05", endTime, time.Local)
- if err == nil && t1.Before(t2) {
- diff := t2.Unix() - t1.Unix() //
- hour = diff / 3600
- return hour
- } else {
- return hour
- }
- }
- // StrToTimestamp 日期字符串转时间戳(秒)
- func StrToTimestamp(dateStr string) int64 {
- tm, err := gtime.StrToTime(dateStr)
- if err != nil {
- g.Log().Error(err)
- return 0
- }
- return tm.Timestamp()
- }
- // TimeStampToDateTimeStr 时间戳转 yyyy-MM-dd HH:mm:ss
- func TimeStampToDateTimeStr(timeStamp int64) string {
- tm := gtime.NewFromTimeStamp(timeStamp)
- return tm.Format("Y-m-d H:i:s")
- }
- // TimeStampToDateStr 时间戳转 yyyy-MM-dd
- func TimeStampToDateStr(timeStamp int64) string {
- tm := gtime.NewFromTimeStamp(timeStamp)
- return tm.Format("Y-m-d")
- }
- // FirstUpper 字符串首字母大写
- func FirstUpper(s string) string {
- if s == "" {
- return ""
- }
- return strings.ToUpper(s[:1]) + s[1:]
- }
- // FirstLower 字符串首字母小写
- func FirstLower(s string) string {
- if s == "" {
- return ""
- }
- return strings.ToLower(s[:1]) + s[1:]
- }
- func Bytes2object(data []byte, obj interface{}) error {
- err := json.Unmarshal(data, obj)
- if err != nil {
- fmt.Println(err)
- return err
- }
- return nil
- }
|