网络编程
位置:首页>> 网络编程>> Go语言>> Go语言实现RSA加解密算法详解

Go语言实现RSA加解密算法详解

作者:JonLee  发布时间:2024-02-08 12:20:55 

标签:Go,RSA

随着互联网的高速发展,人们对安全的要求也越来越高。密码学中两大经典算法,一个是对称加解密,另一个是非对称加解密,这里就来分享一下非对称加密算法的代表:RSA加解密。

在Go语言中实现RSA加解密还是比较简单的,网上很多教程都是基于Go原生标准库写的,代码量较多。这里分享一个好用的库:https://github.com/forgoer/openssl 。

安装

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

秘钥生成

秘钥可以生成在文件里,也是生成到Buffer里,只要实现了io.Writer即可。

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)
}

加解密

使用公钥加密,私钥解密。

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

签名及验证

使用私钥签名,公钥验证。

// 私钥签名
   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://segmentfault.com/a/1190000043858840

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com