- 要计算签名的话,最好都用字符串来表达,免得麻烦。如果要用浮点数的话,那必须要另外约定小数位数
```
package main
import (
"crypto"
"crypto/md5"
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"fmt"
"net/url"
"strings"
"time"
)
const (
publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDIBgFl4dNiuDeZxjllYnNmk3/UA6eX+GkW8KQ2A2E0eRZCQ4tLsZHVdE58a4UxW+LArTZwSUy8FrXQjYkAQMASy2wVofctjDu4RcO1fiJKc/N8v4Kzx+Ta3nkingQGPZhPzYxLWx2VD1ands2jMem/AIv0oklJBasb57N+7YuFgQIDAQAB"
privateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAMgGAWXh02K4N5nGOWVic2aTf9QDp5f4aRbwpDYDYTR5FkJDi0uxkdV0TnxrhTFb4sCtNnBJTLwWtdCNiQBAwBLLbBWh9y2MO7hFw7V+Ikpz83y/grPH5NreeSKeBAY9mE/NjEtbHZUPVqd2zaMx6b8Ai/SiSUkFqxvns37ti4WBAgMBAAECgYEAp5IgabIe3X1nVzRxsTYhZ7X6SSwmo3JA2C8R4w5BySwIMctUTz2b5y9g8WtCUm+gL7rs+HTwDEMaXnW0aLnWLmu/+12n+SEusVlMBnkC0NRtkkfxMIOP0LgVkrIbv4Um6iRDsbyctD7GBFRB+q3qTk6dVVS8qLBU9o/GBCLSgAECQQD5QvH49Xnvh+75tO3yMJry53OBXXnvLY0V8vpc4zy67Dd3Q+BZCKnT3gkr/H77fDcn6cf9SyAvN2tMIFNgR/vBAkEAzW5M46qSL0K2uJR4Ei+ifUl6Rx5vWh0BR0hMZqkdzry8HOxeBpo693XE2fNaE5CmIXdfB3WcX9gcT/GGTWj5wQJBAMgJzM1Cm6f6zHODm045abC0xMK2NOwY/1f1Fq3DA/LzLZQ+Wea6CCjq0SuGyJWk21Lh0EjbqKmb7TU74A2t10ECQALvGFoIDZ5vLXzlYfGgjImNixmI7b4zu9jwx2aP88UIHQesuIsPmNf/7pfOSfMNldHUip7opxsXUxAxOuHQJgECQQCMyTR+oAFjZOZFJH9SwoDk9Ew125yTLSZAsOKz0dzfOLUGoNkYJ2HeH7ceSdRo3tEkzGaePXAeKCqkhuuOjP1G"
)
func main() {
m := make(map[string]string)
m["param1"] = "参数_/+-"
m["param2"] = "11.00"
m["param3"] = "5.69"
fmt.Println("签名前的数据:", m)
if err := signData(m); err != nil {
fmt.Println("签名错误", err)
return
}
fmt.Println("签名后的数据:", m)
if err := verifyData(m); err != nil {
fmt.Println("验签结果(公钥验签):", "失败", err)
} else {
fmt.Println("验签结果(公钥验签):", "成功")
}
}
func signData(m map[string]string) error {
m["timestamp"] = fmt.Sprintf("%d", time.Now().UnixNano()/1e6)
signUrl := url.Values{}
for key, value := range m {
signUrl.Add(key, value)
}
//进行转码使之可以安全的用在URL查询里
quUrl, err := url.QueryUnescape(signUrl.Encode())
if err != nil {
fmt.Println("QueryUnescape", err)
return err
}
if out, err := RsaSignWithMd5(quUrl, privateKey); err != nil {
return err
} else {
m["sign"] = out
return nil
}
}
func verifyData(m map[string]string) error {
sign := m["sign"]
delete(m, "sign")
signUrl := url.Values{}
for key, value := range m {
signUrl.Add(key, value)
}
//进行转码使之可以安全的用在URL查询里
quUrl, _ := url.QueryUnescape(signUrl.Encode())
return RsaVerifySignWithMd5(quUrl, sign, publicKey)
}
// 签名
func RsaSignWithMd5(data string, prvKey string) (sign string, err error) {
//如果密钥是urlSafeBase64的话需要处理下
prvKey = Base64URLDecode(prvKey)
keyBytes, err := base64.StdEncoding.DecodeString(prvKey)
if err != nil {
fmt.Println("DecodeString:", err)
return "", err
}
privateKey, err := x509.ParsePKCS8PrivateKey(keyBytes)
if err != nil {
fmt.Println("ParsePKCS8PrivateKey", err)
return "", err
}
h := md5.New()
h.Write([]byte(data))
hash := h.Sum(nil)
signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey.(*rsa.PrivateKey), crypto.MD5, hash[:])
if err != nil {
fmt.Println("SignPKCS1v15:", err)
return "", err
}
out := base64.RawURLEncoding.EncodeToString(signature)
return out, nil
}
// 验签
func RsaVerifySignWithMd5(originalData, signData, pubKey string) error {
//TODO : 验证时间
sign, err := base64.RawURLEncoding.DecodeString(signData)
if err != nil {
fmt.Println("DecodeString:", err)
return err
}
pubKey = Base64URLDecode(pubKey)
public, err := base64.StdEncoding.DecodeString(pubKey)
if err != nil {
fmt.Println("DecodeString")
return err
}
pub, err := x509.ParsePKIXPublicKey(public)
if err != nil {
fmt.Println("ParsePKIXPublicKey", err)
return err
}
hash := md5.New()
hash.Write([]byte(originalData))
return rsa.VerifyPKCS1v15(pub.(*rsa.PublicKey), crypto.MD5, hash.Sum(nil), sign)
}
//因为Base64转码后可能包含有+,/,=这些不安全的URL字符串,所以要进行换字符
// '+' -> '-'
// '/' -> '_'
// '=' -> ''
// 字符串长度不足4倍的位补"="
func Base64URLDecode(data string) string {
var missing = (4 - len(data)%4) % 4
data += strings.Repeat("=", missing) //字符串长度不足4倍的位补"="
data = strings.Replace(data, "_", "/", -1)
data = strings.Replace(data, "-", "+", -1)
return data
}
func Base64UrlSafeEncode(data string) string {
safeUrl := strings.Replace(data, "/", "_", -1)
safeUrl = strings.Replace(safeUrl, "+", "-", -1)
safeUrl = strings.Replace(safeUrl, "=", "", -1)
return safeUrl
}
```