加密
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

139 lines
2.8 KiB

package crypter
import (
"crypto/md5"
"encoding/base64"
"fmt"
"io"
"strconv"
"strings"
"time"
)
// SSO gxytoken authcode
// btype 加密or解密 bool true:加密 false:解密 默认false
// skey 秘钥
// text 加/解密内容
func AuthCode(text, skey string, btype bool) string {
isEncode := btype
key := skey
expiry := 0
cKeyLen := 4
timestamp := time.Now().Unix()
// md5加密key
mKey := Md5Sum(key)
// 参与加密的
keyA := Md5Sum(mKey[0:16])
// 用于验证数据有效性的
keyB := Md5Sum(mKey[16:])
// 动态部分
var keyC string
if cKeyLen > 0 {
if isEncode {
// 加密的时候,动态获取一个秘钥
keyC = Md5Sum(fmt.Sprint(timestamp))[32-cKeyLen:]
} else {
// 解密的时候从头部获取动态秘钥部分
keyC = text[0:cKeyLen]
}
}
// 加入了动态的秘钥
cryptKey := keyA + Md5Sum(keyA+keyC)
// 秘钥长度
keyLen := len(cryptKey)
if isEncode {
// 加密 前10位是过期验证字符串 10-26位字符串验证
var d int64
if expiry > 0 {
d = timestamp + int64(expiry)
}
text = fmt.Sprintf("%010d%s%s", d, Md5Sum(text + keyB)[0:16], text)
} else {
// 解密
//res, _ := base64.StdEncoding.DecodeString(text[cKeyLen:])
res := Base64Decode(text[cKeyLen:])
text = string(res)
}
// 字符串长度
textLen := len(text)
if textLen <= 0 {
return ""
}
// 密匙簿(0-256)
box := make([]int, 0)
for i := 0; i < 256; i++ {
box = append(box, i)
}
// 对称算法
var rndKey []int
cryptKeyB := []byte(cryptKey)
for i := 0; i < 256; i++ {
pos := i % keyLen
rndKey = append(rndKey, int(cryptKeyB[pos]))
}
j := 0
for i := 0; i < 256; i++ {
j = (j + box[i] + rndKey[i]) % 256
box[i], box[j] = box[j], box[i]
}
textB := []byte(text)
a := 0
j = 0
var result []byte
for i := 0; i < textLen; i++ {
a = (a + 1) % 256
j = (j + box[a]) % 256
box[a], box[j] = box[j], box[a]
result = append(result, byte(int(textB[i])^(box[(box[a]+box[j])%256])))
}
if isEncode {
return keyC + strings.Replace(base64.StdEncoding.EncodeToString(result), "=", "", -1)
}
// 获取前10位,判断过期时间
d, err := strconv.ParseInt(string(result[0:10]), 10, 64)
if err != nil {
d = 0
}
fmt.Println(string(result[10:26]), Md5Sum(string(result[26:]) + keyB)[0:16])
if (d == 0 || d-timestamp > 0) && string(result[10:26]) == Md5Sum(string(result[26:]) + keyB)[0:16] {
return string(result[26:])
}
fmt.Println(string(result[26:]))
return ""
}
//MD5SUm
func Md5Sum(str string) string {
h := md5.New()
io.WriteString(h, str)
return fmt.Sprintf("%x", h.Sum(nil))
}
//Base64Decode
func Base64Decode(str string) []byte {
var sdec []byte
var err error
x := len(str) * 3 % 4
fmt.Println(x)
switch {
case x == 2:
str += "=="
case x == 1:
str += "="
}
if sdec, err = base64.StdEncoding.DecodeString(str); err != nil {
return sdec
}
return sdec
}