plugin/alipay/utils/sign.go

108 lines
2.7 KiB
Go

package utils
import (
"crypto"
"crypto/rand"
"crypto/rsa"
"crypto/sha256"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
"fmt"
"gitea.cdlsxd.cn/sdk/plugin/alipay"
"gitea.cdlsxd.cn/sdk/plugin/utils"
"net/url"
"strings"
)
func UrlValues(prk string, req alipay.Req) (url.Values, error) {
if err := req.Validate(); err != nil {
return nil, err
}
var strToBeSigned strings.Builder
uv := url.Values{}
kvRows := utils.SortStructJsonTag(req)
for _, kv := range kvRows {
if kv.Key == "sign" || kv.Value == "" {
continue
}
uv.Set(kv.Key, kv.Value)
strToBeSigned.WriteString(fmt.Sprintf("%s=%s&", kv.Key, kv.Value))
}
s := strings.TrimRight(strToBeSigned.String(), "&")
sign, err := Sign(s, []byte(utils.NewPrivate().Build(prk)))
if err != nil {
return nil, err
}
uv.Set("sign", sign)
return uv, nil
}
func Sign(data string, privateKeyPEM []byte) (string, error) {
block, _ := pem.Decode(privateKeyPEM)
if block == nil {
return "", errors.New("failed to parse PEM block containing the private key")
}
privyKey, err := x509.ParsePKCS8PrivateKey(block.Bytes)
if err != nil {
return "", fmt.Errorf("failed to parse DER encoded private key: %v", err)
}
hashed := sha256.Sum256([]byte(data))
signature, err := rsa.SignPKCS1v15(rand.Reader, privyKey.(*rsa.PrivateKey), crypto.SHA256, hashed[:])
if err != nil {
return "", fmt.Errorf("failed to sign: %v", err)
}
return base64.StdEncoding.EncodeToString(signature), nil
}
func Verify(n *alipay.Notify, publicKeyPEM string) (bool, error) {
var strToBeSigned strings.Builder
uv := url.Values{}
kvRows := utils.SortStructJsonTag(n)
for _, kv := range kvRows {
if kv.Key == "sign" || kv.Key == "sign_type" || kv.Value == "" {
continue
}
uv.Set(kv.Key, kv.Value)
strToBeSigned.WriteString(fmt.Sprintf("%s=%s&", kv.Key, kv.Value))
}
s := strings.TrimRight(strToBeSigned.String(), "&")
return check(s, n.Sign, []byte(publicKeyPEM))
}
func check(data, signature string, publicKeyPEM []byte) (bool, error) {
block, _ := pem.Decode(publicKeyPEM)
if block == nil {
return false, fmt.Errorf("failed to parse DER encoded public key")
}
pubKey, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return false, fmt.Errorf("failed to parse DER encoded public key: %v", err)
}
rsaPubKey, ok := pubKey.(*rsa.PublicKey)
if !ok {
return false, fmt.Errorf("failed to parse DER encoded public key: %v", err)
}
hashed := sha256.Sum256([]byte(data))
sig, err := base64.StdEncoding.DecodeString(signature)
if err != nil {
return false, fmt.Errorf("failed to decode signature: %v", err)
}
err = rsa.VerifyPKCS1v15(rsaPubKey, crypto.SHA256, hashed[:], sig)
if err != nil {
fmt.Println("signature verification error:", err)
return false, nil
}
return true, nil
}