package tools import ( "crypto" "crypto/rand" "crypto/rsa" "crypto/sha256" "crypto/x509" "encoding/base64" "encoding/pem" "errors" ) // RSA2私钥签名 func Rsa2PriSign(signContent string, privateKey string, hash crypto.Hash) string { shaNew := hash.New() shaNew.Write([]byte(signContent)) hashed := shaNew.Sum(nil) priKey, err := ParsePrivateKey(privateKey) if err != nil { return "" } signature, err := rsa.SignPKCS1v15(rand.Reader, priKey, hash, hashed) if err != nil { return "" } return base64.StdEncoding.EncodeToString(signature) } // 解析私钥 func ParsePrivateKey(privateKey string) (*rsa.PrivateKey, error) { block, _ := pem.Decode([]byte(privateKey)) if block == nil { return nil, errors.New("私钥信息错误!") } priKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return nil, err } return priKey, nil } // RSA2公钥验证签名 func Rsa2PubCheckSign(source, sign, publicKey string, hash crypto.Hash) (bool, error) { hashed := sha256.Sum256([]byte(source)) pubKey, err := ParsePublicKey(publicKey) if err != nil { return false, err } sig, _ := base64.StdEncoding.DecodeString(sign) err = rsa.VerifyPKCS1v15(pubKey, hash, hashed[:], sig) if err != nil { return false, err } return true, nil } // 解析公钥 func ParsePublicKey(publicKey string) (*rsa.PublicKey, error) { block, _ := pem.Decode([]byte(publicKey)) if block == nil { return nil, errors.New("公钥信息错误!") } pubKey, err := x509.ParsePKIXPublicKey(block.Bytes) if err != nil { return nil, err } return pubKey.(*rsa.PublicKey), nil }