风险监控Go语言SDK
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.
risk-sdk-go/sign.go

72 lines
1.2 KiB

2 years ago
package risk
import (
"crypto/md5"
"encoding/hex"
"encoding/json"
"strings"
"time"
"github.com/google/uuid"
"github.com/spf13/cast"
)
func CheckSign(appID, appKey, random, sign string, ts int, data interface{}) bool {
if int(time.Now().Unix())-ts > 120 {
return false
}
v, _ := json.Marshal(data)
m := md5.New()
sb := strings.Builder{}
sb.WriteString(appID)
sb.WriteByte('-')
sb.WriteString(cast.ToString(ts))
sb.WriteByte('-')
sb.Write(v)
sb.WriteByte('-')
sb.WriteString(random)
sb.WriteByte('-')
sb.WriteString(appKey)
m.Write([]byte(sb.String()))
md5str1 := hex.EncodeToString(m.Sum(nil))
return md5str1 == sign
}
func Sign(appID, appKey string, data interface{}) (sign string, random string, ts int) {
random = newRandom()
ts = int(time.Now().Unix())
v, _ := json.Marshal(data)
m := md5.New()
sb := strings.Builder{}
sb.WriteString(appID)
sb.WriteByte('-')
sb.WriteString(cast.ToString(ts))
sb.WriteByte('-')
sb.Write(v)
sb.WriteByte('-')
sb.WriteString(random)
sb.WriteByte('-')
sb.WriteString(appKey)
m.Write([]byte(sb.String()))
sign = hex.EncodeToString(m.Sum(nil))
return
}
func newRandom() string {
uuid := uuid.Must(uuid.NewRandom())
random := uuid.String()
return strings.ReplaceAll(random, "-", "")
}