// createSignature 生成签名
// @signStr outId
// @DevRsaPrivateKey 私钥
func (s *Service) CreateSignatureWithMd5(signStr string, privateKey string) (string, error) {
//如果密钥是urlSafeBase64的话需要处理下
prvKey := s.base64URLDecode(privateKey)
keyBytes, err := base64.StdEncoding.DecodeString(prvKey)
if err != nil {
fmt.Println("DecodeString:", err)
return "", err
}
privateKey1, err := x509.ParsePKCS8PrivateKey(keyBytes)
if err != nil {
fmt.Println("ParsePKCS8PrivateKey", err)
return "", err
}
h := md5.New()
h.Write([]byte(signStr))
hash := h.Sum(nil)
signature, err := rsa.SignPKCS1v15(rand.Reader, privateKey1.(*rsa.PrivateKey), crypto.MD5, hash[:])
if err != nil {
fmt.Println("SignPKCS1v15:", err)
return "", err
}
out := base64.RawURLEncoding.EncodeToString(signature)
return out, nil
}
// RsaVerifySignWithMd5 验签
// @originalData outID
// @signData 签名
// @rsaPublicKey 公钥
func (s *Service) RsaVerifySignWithMd5(originalData, signData, rsaPublicKey string) error {
sign, err := base64.RawURLEncoding.DecodeString(signData)
if err != nil {
fmt.Println("DecodeString:", err)
return err
}
rsaPublicKey = s.base64URLDecode(rsaPublicKey)
publicString, err := base64.StdEncoding.DecodeString(rsaPublicKey)
if err != nil {
fmt.Println("DecodeString")
return err
}
pub, err := x509.ParsePKIXPublicKey(publicString)
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 (s *Service) 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
}