plugins/plugins/zltx/internal/util.go

86 lines
1.9 KiB
Go

package internal
import (
"crypto/aes"
"crypto/cipher"
"crypto/md5"
"encoding/base64"
"encoding/hex"
"fmt"
"gitea.cdlsxd.cn/sdk/plugin/utils"
"net/url"
"plugins/zltx/internal/po"
"strings"
)
func sign(values []byte) string {
hash := md5.Sum(values)
return strings.ToUpper(hex.EncodeToString(hash[:]))
}
func urlValues(req po.Req, appKey string) url.Values {
uv := url.Values{}
var kvStr []string
kvRows := utils.SortStruct(req)
for _, kv := range kvRows {
if kv.Key == "sign" {
continue
}
uv.Set(kv.Key, kv.Value)
if kv.Key != "version" {
kvStr = append(kvStr, kv.Key+"="+kv.Value)
}
}
kvStr = append(kvStr, "key="+appKey)
signStr := strings.Join(kvStr, "&")
uv.Set("sign", sign([]byte(signStr)))
return uv
}
func req(req po.Req, appKey string) (url.Values, error) {
if err := req.Validate(); err != nil {
return nil, err
}
return urlValues(req, appKey), nil
}
func verify(notify *po.Notify, appKey string) bool {
kvRows := utils.SortStruct(notify)
var kvStr []string
for _, kv := range kvRows {
if kv.Key != "sign" && kv.Key != "version" {
kvStr = append(kvStr, kv.Key+"="+kv.Value)
}
}
kvStr = append(kvStr, "key="+appKey)
signStr := strings.Join(kvStr, "&")
return sign([]byte(signStr)) == notify.Sign
}
func cardCodeDecode(code string, key []byte) (string, error) {
decoded, err := base64.StdEncoding.DecodeString(code)
if err != nil {
return "", fmt.Errorf("base64 decode error: %v", err)
}
block, err := aes.NewCipher(key)
if err != nil {
return "", fmt.Errorf("aes new cipher error: %v", err)
}
if len(decoded) < aes.BlockSize {
return "", fmt.Errorf("ciphertext too short")
}
decrypted := make([]byte, len(decoded))
mode := cipher.NewCBCDecrypter(block, make([]byte, aes.BlockSize))
mode.CryptBlocks(decrypted, decoded)
padding := decrypted[len(decrypted)-1]
decrypted = decrypted[:len(decrypted)-int(padding)]
return string(decrypted), nil
}