Golang-RSA2签名及验签G olang RSA2 签名-验签
const (
// 私钥 PEMBEGIN 开头
PEMBEGIN = "-----BEGIN RSA PRIVATE KEY-----\n"
// 私钥 PEMEND 结尾
PEMEND = "\n-----END RSA PRIVATE KEY-----"
// 公钥 PEMBEGIN 开头
PUBPEMBEGIN = "-----BEGIN PUBLIC KEY-----\n"
// 公钥 PEMEND 结尾
PUBPEMEND = "\n-----END PUBLIC KEY-----"
)
/
/ Rsa2Sign RSA2私钥签名
func Rsa2Sign(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)
}
// ParsePrivateKey 私钥验证
func ParsePrivateKey(privateKey string) (*rsa.PrivateKey, error) {
privateKey = FormatPrivateKey(privateKey)
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
}
// FormatPrivateKey 组装私钥
func FormatPrivateKey(privateKey string) string {
if !strings.HasPrefix(privateKey, PEMBEGIN) {
privateKey = PEMBEGIN + privateKey
}
if !strings.HasSuffix(privateKey, PEMEND) {
privateKey = privateKey + PEMEND
}
return privateKey
}
// Rsa2PubSign RSA2公钥验证签名
func Rsa2PubSign(signContent, sign, publicKey string, hash crypto.Hash) bool {
hashed := sha256.Sum256([]byte(signContent))
pubKey, err := ParsePublicKey(publicKey)
if err != nil {
log.Errorf(err, "rsa2 public check sign failed.")
error parse newreturn false
}
sig, _ := base64.StdEncoding.DecodeString(sign)
err = rsa.VerifyPKCS1v15(pubKey, hash, hashed[:], sig)
if err != nil {
log.Errorf(err, "rsa2 public check sign failed.")
return false
}
return true

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。