Go语言实现RSA加解密、签名验证算法

2023-06-0716:28:59编程语言入门到精通Comments1,164 views字数 1227阅读模式

互联网的高速发展,人们对安全的要求也越来越高。密码学中两大经典算法,一个是对称加解密,另一个是非对称加解密,这里就来分享一下非对称加密算法的代表:RSA加解密。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/45486.html

在Go语言中实现RSA加解密还是比较简单的,网上很多教程都是基于Go原生标准库写的,代码量较多。这里分享一个好用的库:https://github.com/forgoer/openssl 。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/45486.html

安装

go get https://github.com/forgoer/openssl

秘钥生成

秘钥可以生成在文件里,也是生成到Buffer里,只要实现了io.Writer即可。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/45486.html

import (
    "io/ioutil"
    "os"

    "github.com/forgoer/openssl"
)

func main() {

    // 创建私钥文件
    priFile, err := os.Create("private.key") // 也可以使用buffer, priBuf := bytes.NewBuffer(nil)
    if err != nil {
        panic(err)
    }
    defer priFile.Close()
    // 生成私钥到文件
    _ = openssl.RSAGenerateKey(1024, priFile)

    // 创建公钥文件
    pubFile, err := os.Create("public.key")
    if err != nil {
        panic(err)
    }
    defer priFile.Close()

    // 通过私钥生成公钥到文件
    priByte, _ := ioutil.ReadFile("private.key")
    _ = openssl.RSAGeneratePublicKey(priByte, pubFile)
}

加解密

使用公钥加密,私钥解密。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/45486.html

    src := []byte("123456")
    pubByte, _ := ioutil.ReadFile("public.key")
    // 公钥加密
    dst, _ := openssl.RSAEncrypt(src, pubByte)


    priByte, _ := ioutil.ReadFile("private.key")
    // 私钥解密
    res, _ := openssl.RSADecrypt(dst, priByte)


    fmt.Println(string(res)) // 123456

签名及验证

使用私钥签名,公钥验证。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/45486.html

    // 私钥签名
    sign, err := openssl.RSASign([]byte("123456"), priByte, crypto.SHA256)
    if err != nil {
        panic(err)
    }

    // 公钥验证签名
    err = openssl.RSAVerify([]byte("123456"), sign, pubByte, crypto.SHA256)
    if err != nil {
        panic(err)
    }

这个加解密库:https://github.com/forgoer/openssl,它还支持AESDESRSAsha1Hmac-Sha1sha256Hmac-Sha256等常用算法。文章源自菜鸟学院-https://www.cainiaoxueyuan.com/ymba/45486.html

  • 本站内容整理自互联网,仅提供信息存储空间服务,以方便学习之用。如对文章、图片、字体等版权有疑问,请在下方留言,管理员看到后,将第一时间进行处理。
  • 转载请务必保留本文链接:https://www.cainiaoxueyuan.com/ymba/45486.html

Comment

匿名网友 填写信息

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定