ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
-RSA 加密解密 数据非明文 -RSA 签名验签 数据明文 校验数据真实性 > RSA(MD5WithRSA 算法)签名和验签方式 - 签名算法为直接把请求数据中的所有元素(除 sign 本身)按照"key 值=value 值"的格式拼接起来,并且把这些拼接以后的元素按首字母升序排列顺序,最后以"&"字符连接起来得到签名串,使用私钥对签名串进行 RSA 签名 - [golang中关于RSA加密、解密、签名、验签的总结](https://blog.csdn.net/xz_studying/article/details/80314111) - [本次使用的密钥生成工具](https://opendocs.alipay.com/open/291/106097) ``` package main import ( "crypto" "crypto/md5" "crypto/rand" "crypto/rsa" "crypto/x509" "encoding/base64" "fmt" "net/url" "strings" "time" ) const ( publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCeRsyfEMUo6PFs7upFQJr15CUveSDVvWAg8KRXz1fU5XwBgc6d2YY7ly3QeuKz7_rd5nlXlUxnMzT2dVhTPfNEI1Q4AnNbFxqhNN3gEeTUlIh1lBXdfoWOsOOb3LHs0124BgTViTRjDW-1CmJk-vqGq-maOaA7BcXRlt8kMecJdwIDAQAB" privateKey = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAJ5GzJ8QxSjo8Wzu6kVAmvXkJS95INW9YCDwpFfPV9TlfAGBzp3ZhjuXLdB64rPv-t3meVeVTGczNPZ1WFM980QjVDgCc1sXGqE03eAR5NSUiHWUFd1-hY6w45vcsezTXbgGBNWJNGMNb7UKYmT6-oar6Zo5oDsFxdGW3yQx5wl3AgMBAAECgYBedfCfKjoQ3V1g3wHQDOuuvtd2irsO9TPO1O-wPF22ALPOjnMKgAz9uY8tMnnkW-AD2Q4oOEFeAhCk2om5PGrXGThggJNKRrqYeeyKDtGdtdnp8Za9nI1jeVz-LeNNQHNPhIuhR5z8ufDaWVCm7sNcGyIbP_qg2SErg3yJpypcIQJBAN3trJ_z-McAmV6o_xJm5mk094tols74Ix59F60i0mB4VWdFY3M9fHjIvCKKavkGb4szl4FAiklsKO5myb64eCcCQQC2k3PV7dPiTs1_HDyP6ZuFTfuPT_r7llj8PSQXQPXCJb5o-oKXTsex06C8J6R0EpXCiBZhmWFe-Hqb1nIAU-YxAkBsQp8tQDShz1cB6GrVrUDFHcOMTC8VM9Ld8qP0H8KEsO7oe97xvpLT0QiFyQQ6CrurKjXEJZnQC2VENvw_f3mNAkAbkwWJp9O6eEBdFDypV5TfezmlGWVEnh5uaiWLRYpYei7Z2AvlIkbSuq2p_Sq_RRdNPBR1RR8JoumRo7-wAPvhAkBCm_ylQbGV8McWqzjnlFKd5Fz5SDrTYAC-xJcQ433jiFxAVseWKTpOYb7XR4AhDXSk7GFLseQMv-IdnR5fh7yx" ) func main() { m := make(map[string]string) m["param1"] = "参数1_/+-" m["param2"] = "参数2" m["param3"] = "参数3" fmt.Println("签名前的数据:", m) if err := signData(m); err != nil { fmt.Println(err.Error()) } 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) sig := url.Values{} for key, value := range m { sig.Add(key, value) } //进行转码使之可以安全的用在URL查询里 quUrl, err := url.QueryUnescape(sig.Encode()) if err != nil { fmt.Println("QueryUnescape", err) return err } if out, err := RsaSignWithMd5(quUrl, privateKey); err != nil { return err } else { m["sig"] = out return nil } } func verifyData(m map[string]string) error { sign := m["sig"] delete(m, "sig") sig := url.Values{} for key, value := range m { sig.Add(key, value) } //进行转码使之可以安全的用在URL查询里 quUrl, _ := url.QueryUnescape(sig.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 } ``` - 要计算签名的话,最好都用字符串来表达,免得麻烦。如果要用浮点数的话,那必须要另外约定小数位数 ``` package main import ( "crypto" "crypto/md5" "crypto/rsa" "crypto/x509" "encoding/base64" "encoding/json" "fmt" "net/url" "reflect" "strconv" "strings" ) const ( publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCvKbAeFgG-0hxLPyVCBEemiXcjbnkJ4Hy971V0AHzDIUwkqessV8EWx3hvgm6bqm48gBApUQwRQGymw7cIuLcnt0eRiCc6gPXI72ZUpRKYEk7C-zeOZYi4zSPXFA_3LmGKT7p0IYmTFEtlEz8kz1EtYZnNxJGbZwIZHjuIMP3G9QIDAQAB" ) func main() { jsonData := `{"connectorId":"YKC-YY13747#3201060000619002","lockStatus":0,"parkStatus":0,"platformCode":"920030401","sig":"Nr93wqjXAT/mWU0uS6sJhDv3oXR8Ygt0NuOUsf76z6Dtsj2AmgpJVojSZqeaLv7jbKSzbcSp5jsFRSyABvMUXcwaczTU9pK3Ml3KvzdqZjmULrgXALoqMtLsV4rPOgAVzkA7wHuhsrUEBAr1ShYXvEWvouvTBj26QNfNEmHYyiU=","status":1}` fmt.Println(verifyResult(jsonData)) } func verifyResult(jsonData string) bool { m := make(map[string]interface{}) if err := json.Unmarshal([]byte(jsonData), &m); err != nil { fmt.Println(err.Error()) } if _, ok := m["chargeDetails"]; ok { delete(m, "chargeDetails") } m2 := make(map[string]string) for k, v := range m { if v == nil || v == "" { delete(m, k) continue } if reflect.TypeOf(v).String() == "float64" { if v != 0 && !InArrayOfString(k, []string{"startChargeSeqStat", "sumPeriod", "connectorStatus", "stopReason", "stayCost", "succStat", "failReason", "lockStatus", "parkStatus", "status"}) { vv := strconv.FormatFloat(v.(float64), 'f', -1, 64) if strings.IndexAny(vv, ".") < 1 { changeV := fmt.Sprintf("%.1f", v) m2[k] = changeV } else { m2[k] = vv } } else { changeV := fmt.Sprintf("%.0f", v) m2[k] = changeV } } else { m2[k] = v.(string) } } if err := verifyData(m2); err != nil { fmt.Println(err.Error()) return false } else { return true } } func verifyData(m map[string]string) error { sign := m["sig"] delete(m, "sig") sig := url.Values{} for key, value := range m { sig.Add(key, value) } //进行转码使之可以安全的用在URL查询里 quUrl, _ := url.QueryUnescape(sig.Encode()) fmt.Println(quUrl) return RsaVerifySignWithMd5(quUrl, sign, publicKey) } // 验签 func RsaVerifySignWithMd5(originalData, signData, pubKey string) error { fmt.Println(signData) fmt.Println(Base64UrlSafeEncode(signData)) sign, err := base64.RawURLEncoding.DecodeString(Base64UrlSafeEncode(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) } 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 } func InArrayOfString(needle string, haystack []string) bool { for _, v := range haystack { if ok := strings.Contains(needle, v); ok == true { return ok } } return false } ```