Golang for RSA signing (SHA256withRSA)

Recently, I am working on an open platform project. When writing the SDK, I use the signature verification function and use Sha256WithRSA signature. The specific process is to use the private key to generate the signature, and then the public key to verify the signature.

Now share the code signed by the private key.

package common

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/pem"
	"errors"
	"sort"
	"strings"
)

const (
	PEM_BEGIN = "-----BEGIN RSA PRIVATE KEY-----\n"
	PEM_END = "\n-----END RSA PRIVATE KEY-----"
)

func RsaSign(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 {
   
		panic(err)
	}

	signature, err := rsa.SignPKCS1v15(rand.Reader, priKey, hash, hashed)
	if err != nil {
   
		panic(err)
	}
	return base64.StdEncoding.EncodeToString(signature)
}

func ParsePrivateKey(privateKey string)(*rsa.PrivateKey, error) {
   
	privateKey = FormatPrivateKey(privateKey)
	// 2、解码私钥字节,生成加密对象
	block, _ := pem.Decode([]byte(privateKey))
	if block == nil {
   
		return nil, errors.New("私钥信息错误!")
	}
	// 3、解析DER编码的私钥,生成私钥对象
	priKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
	if err != nil {
   
		return nil, err
	}
	return priKey, nil
}

func FormatPrivateKey(privateKey string) string  {
   
	if !strings.HasPrefix(privateKey, PEM_BEGIN) {
   
		privateKey = PEM_BEGIN + privateKey
	}
	if !strings.HasSuffix(privateKey, PEM_END) {
   
		privateKey = privateKey + PEM_END
	}
	return privateKey
}

RsaSign function parameter description:

  • signContent: signature content
  • privateKey: private key string, PKCS#1, removed at the beginning -----BEGIN RSA PRIVATE KEY-----, removed at the end -----END RSA PRIVATE KEY-----
  • hash: hash algorithm

How to use:

sign = RsaSign(signContent, privateKey, crypto.SHA256)

If SHAwithRSA signature is required, replace crypto.SHA256 with crypto.SHA1

{{o.name}}
{{m.name}}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324039043&siteId=291194637