func genPrivKeyFromPKSC8(pkcs8Key string) (privkey *rsa.PrivateKey) { // 解base64 encodedKey, err := base64.StdEncoding.DecodeString(pkcs8Key) if err != nil { log.Fatal(err) } // 使用pkcs8格式 pkcs8, err := x509.ParsePKCS8PrivateKey(encodedKey) var ok bool if privkey, ok = pkcs8.(*rsa.PrivateKey); !ok { log.Fatal(ok) } return }
func genPubKey(key string) (pubKey *rsa.PublicKey) { // 解base64 encodedKey, err := base64.StdEncoding.DecodeString(key) if err != nil { log.Fatal(err) } pkix, err := x509.ParsePKIXPublicKey(encodedKey) if err != nil { log.Fatal("unable to parse pxix key") } ok := false if pubKey, ok = pkix.(*rsa.PublicKey); !ok { log.Fatal("aliPubKey can not be parsed to rsa.PublicKey") } return }
// Verfiy 验签函数 func Verfiy(body, sign, aliPubKey string) error { //解base64 decoded, err := base64.StdEncoding.DecodeString(sign) if err != nil { log.Fatal(err) } //hashed h := sha1.New() h.Write([]byte(body)) //to rsa.publickey pubKey := genPubKey(aliPubKey) //rsa验签 return rsa.VerifyPKCS1v15(pubKey, crypto.SHA1, h.Sum(nil), decoded) }