首页 > 其他分享 >golang实现RSA2的签名与验签函数

golang实现RSA2的签名与验签函数

时间:2022-10-29 13:12:00浏览次数:53  
标签:return nil err crypto golang ----- KEY 与验 RSA2

使用非对称加密算法,实现签名与验签

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(signContent, sign, publicKey string, hash crypto.Hash) bool {
    hashed := sha256.Sum256([]byte(signContent))
    pubKey, err := ParsePublicKey(publicKey)
    if err != nil {
        return false
    }
    sig, _ := base64.StdEncoding.DecodeString(sign)
    err = rsa.VerifyPKCS1v15(pubKey, hash, hashed[:], sig)
    if err != nil {
        return false
    }
    return true
}

// 解析公钥
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
}

测试用例

package tools

import (
    "crypto"
    "log"
    "testing"
)

const (
    // 私钥
    PRIVATE_KEY = `
-----BEGIN RSA PRIVATE KEY-----
MIIEogIBAA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O33rj+b7fOM6jiw
969eXRQJLkWOtfIlKEaC7zMSitaNmgB5PI7b0UJfcv+RNqu9D4BwcXBaNBMUkD6M
/P+unUkI8Ukdy70yHfKPT1N5FfHGN8thqZv+VQ8HQkSS6MY7vcHK06o6H2xpUMvA
5zDuI+eHtytTFd/snsPtbQKBgCFM8TklydqMtTXv9ZG767PtUlJTjzIUVM5kYLP3
tXSzVZwSr8e/m19dmgz4uwDUN9eiHKwWOiilOfAxGBtd+lHIgDiBOWDmDdFgnkjW
qY0+WTjAmp7WhufIM9Ah35IX3v1c1m5fZ1HZRTQBTw4k2A9zI/UpbIbv68+7h/ks
qvCDAoGAF0jwXqwZu0CJB+ojr6dawYXNalEKH7bMPyItdHK4PqWcftHjYXQthnQC
uOeS4tEa3nfahGhp68U9N18L3h3gkkHqIGJvPzAEIjaIeghkQ73RinA/94ZlUBm4
jVGL8OEtfrm3O6ukVFTaiBMXPwAN4e3qfkXuyRepN0DjUthymes=
-----END RSA PRIVATE KEY-----
`
    // 私钥
    PUBLIC_KEY = `
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvSa9KsScy+ZuFTiPLE7Z
wMacmxmA6A8fu0jiPluliLwutgROTTZp3g9HmW1CuYt+ZoQH9t0JzHHNFu9yCetJ
dt5TrpQx9bBovTsh8h/ZQOPsyo0pnKqi5G3x1Azvbzs6yTU8voz6xVT90/DVJcd7
1osTsn+7ajEZccfa35tl5DBdF95thWeyMz5p6ayFMUEU10HBUYmYTUzi4dvXcZUZ
vLOIOPMHoCTXcX98EmGqUvsLWpx8mscaA5llZMg+ZXnT5OH+HW9ncfz7DqXiON3y
o1BrNPdmN+Y4SI9dWrADUzGJO6u58OwncCphUsYqnlG2jd4n0JhjpA2WGD4c6zqJ
JQIDAQAB
-----END PUBLIC KEY-----
`
)

func TestRsa2Rsa2PriSign(t *testing.T) {
    //原内容
    str := "F78691A5-2963-42D2-A0C7-3A4F31CF5EB6"
    //生成签名
    sig := Rsa2PriSign(str, PRIVATE_KEY, crypto.SHA256)
    log.Println(sig)
    //验证原内容与签名是否一致
    res := Rsa2PubCheckSign(str, sig, PUBLIC_KEY, crypto.SHA256)
    log.Println(res)
}

 

 验证成功!

标签:return,nil,err,crypto,golang,-----,KEY,与验,RSA2
From: https://www.cnblogs.com/taoshihan/p/16838536.html

相关文章

  • golang 学习入门项目(超适合新手入门,新手进阶)
    过年的疫情,让我有了时间整理自己的博客。这篇是关于如何学习golang这门语言的。实例代码一分享到github点击获取源码 ​​github学习golang​​本项目是个gogin框架写的......
  • golang---恢复符号
    golang---恢复符号这样编译go程序,可以去除符号,加大逆向人员分析难度gobuild-ohello-ldflags'-s'hello.go不过符号并不是真的删掉了,可以通过一些脚本恢复回来for......
  • Golang基础-流程控制
    流程控制语句是用来控制程序中各语句执行顺序的语句,可以把语句组合成能完成一定功能的小逻辑模块控制语句分为三大类:顺序、选择、循环一、分支结构if分支结构单分支......
  • Golang Vue 后台框架 go-admin 从零开始企业级实战视频教程(33 个视频)
    GolangVue后台框架go-admin从零开始企业级实战视频教程(33个视频)Golang作为后端应该会成为未来几年的主要趋势之一,Vue又是用得最多的框架,go-admin是一个很成熟的后......
  • 快速初始化golang和nodejs
    文档说明:只记录关键地方;试验环境:webIDEvscode网页版code-server目标:webIDE终端里能快速使用golang,nodejs,python3,pip3test!-f/etc/apt/source.list.sa......
  • golang中的锁竞争问题
    索引:https://www.waterflow.link/articles/1666884810643当我们打印错误的时候使用锁可能会带来意想不到的结果。我们看下面的例子:packagemainimport( "fmt" "syn......
  • golang dlv调试
    refer:https://blog.csdn.net/luo2pei4321/article/details/125839250一.本地调试   1.dlvdebugsourcefile      dlvdebugmeng.go      2.dlve......
  • golang获取0点时间戳
    1.获取当地时间0点时间戳funcGetZeroTime()int64{   nowTime:=time.Now()   now:=nowTime.Unix()   _,offsetSeconds:=nowTime.Zone()      ......
  • 编写Golang程序以查找数组中每个元素的出现次数
    http://www.nhooo.com/note/qa5b2a.html解决这个问题的方法  步骤1: 定义一个接受数组的方法。步骤2: 定义一个映射,其中key将是数组的元素,起始值为0。步......
  • 华科云商golang详细示例代码
    packagemainimport("net/url""net/http""bytes""fmt""io/ioutil")constProxyServer="ip.hahado.cn:39......