Golang-RSA2 签名及验签
发布时间:2022-02-21 编辑:jiaochengji.com
教程集为您提供Golang-RSA2 签名及验签等资源,欢迎您收藏本站,我们将为您提供最新的Golang-RSA2 签名及验签资源
<h5>Golang RSA2 签名-验签</h5>
<pre><code class="lang-go hljs">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.")
return 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
}
// ParsePublicKey 公钥验证
func ParsePublicKey(publicKey string) (*rsa.PublicKey, error) {
publicKey = FormatPublicKey(publicKey)
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
}
// FormatPublicKey 组装公钥
func FormatPublicKey(publicKey string) string {
if !strings.HasPrefix(publicKey, PUBPEMBEGIN) {
publicKey = PUBPEMBEGIN publicKey
}
if !strings.HasSuffix(publicKey, PUBPEMEND) {
publicKey = publicKey PUBPEMEND
}
return publicKey
}
</code></code></pre>
到此这篇关于“ Golang-RSA2 签名及验签”的文章就介绍到这了,更多文章或继续浏览下面的相关文章,希望大家以后多多支持JQ教程网!
您可能感兴趣的文章:
Golang-RSA2 签名及验签
PHP实现支付宝支付的方法
API常用签名验证方法(PHP实现)
JWT实现用户认证原理与实现(golang)
用PHP实现SHA1withRSA签名、加密、验证
htm5新增的表单元素keygen标签的用法和属性介绍
Golang LicenseServer授权服务器的设计 与 RSA 密钥对的应用
PHP接口开发签名验证原理详解
Google排名经验谈
移动端H5开发遇到的问题及解决方法
[关闭]