go 签名算法crypto.SHA256

package main
 
const MyKey = `MIIEvQIBADANBgkqSkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDj/3+USBaoVSSklSdmnKAEmFIIarRzt/fJXixNUWsCfBCCOO+pURwAlqNvRVQqE2dtcr5uE0DCa。。。。。。。。。`


/*格式化key*/
func FormatPrivateKey(privateKey string) string {

	PEM_BEGIN := "-----BEGIN RSA PRIVATE KEY-----\n"
	PEM_END := "\n-----END RSA PRIVATE KEY-----"

	if !strings.HasPrefix(privateKey, PEM_BEGIN) {
		privateKey = PEM_BEGIN + privateKey
	}
	if !strings.HasSuffix(privateKey, PEM_END) {
		privateKey = privateKey + PEM_END
	}
	//fmt.Println(privateKey)
	return privateKey
}

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

}

/*生成签名*/
func RsaEncrypt(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 main() {
  argus_string :=`{"uid": "100","pid":20}`
  sign := RsaEncrypt(argus_string, MyKey, crypto.SHA256)
  fmt.Println(sign)

}

  

posted @ 2024-08-06 16:34  wsh3166Sir  阅读(29)  评论(0编辑  收藏  举报