89 lines
1.6 KiB
Go
89 lines
1.6 KiB
Go
package util
|
|
|
|
import (
|
|
"crypto/aes"
|
|
"crypto/cipher"
|
|
"crypto/rand"
|
|
"encoding/base64"
|
|
"fmt"
|
|
"io"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
const (
|
|
SECRET_KEY = ")VQbB(vpy=U(wcp)"
|
|
)
|
|
|
|
// 加密字符串
|
|
func Encrypt(plainText, key string) (string, error) {
|
|
block, err := aes.NewCipher([]byte(key))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
cipherText := make([]byte, aes.BlockSize+len(plainText))
|
|
iv := cipherText[:aes.BlockSize]
|
|
if _, err := io.ReadFull(rand.Reader, iv); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
stream := cipher.NewCFBEncrypter(block, iv)
|
|
stream.XORKeyStream(cipherText[aes.BlockSize:], []byte(plainText))
|
|
|
|
return base64.URLEncoding.EncodeToString(cipherText), nil
|
|
}
|
|
|
|
// 解密字符串
|
|
func Decrypt(cipherText, key string) (string, error) {
|
|
cipherTextBytes, err := base64.URLEncoding.DecodeString(cipherText)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
block, err := aes.NewCipher([]byte(key))
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
|
|
if len(cipherTextBytes) < aes.BlockSize {
|
|
return "", fmt.Errorf("cipherText too short")
|
|
}
|
|
|
|
iv := cipherTextBytes[:aes.BlockSize]
|
|
cipherTextBytes = cipherTextBytes[aes.BlockSize:]
|
|
|
|
stream := cipher.NewCFBDecrypter(block, iv)
|
|
stream.XORKeyStream(cipherTextBytes, cipherTextBytes)
|
|
|
|
return string(cipherTextBytes), nil
|
|
}
|
|
|
|
func GetNowTime() int64 {
|
|
T := time.Now()
|
|
return T.Unix()
|
|
}
|
|
|
|
func Int(a interface{}) int {
|
|
if a == nil {
|
|
return 0
|
|
}
|
|
switch v := a.(type) {
|
|
case int:
|
|
return v
|
|
case int32:
|
|
return int(v)
|
|
case int64:
|
|
return int(v)
|
|
case float64:
|
|
return int(v)
|
|
case string:
|
|
r, err := strconv.Atoi(v)
|
|
if err != nil {
|
|
return 0
|
|
}
|
|
return r
|
|
}
|
|
return 0
|
|
}
|