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

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

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

安装

复制代码
go get https://github.com/forgoer/openssl

秘钥生成

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

go 复制代码
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)
}

加解密

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

go 复制代码
	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

签名及验证

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

go 复制代码
	// 私钥签名
	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等常用算法。

原文地址:Go语言中实现RSA加解密、签名验证算法

相关推荐
Moment1 小时前
Vibe Coding 时代,到底该选什么样的工具来提升效率❓❓❓
前端·后端·github
Victor3561 小时前
MongoDB(27)什么是文本索引?
后端
可夫小子2 小时前
OpenClaw基础-3-telegram机器人配置与加入群聊
后端
IT_陈寒3 小时前
SpringBoot性能飙升200%?这5个隐藏配置你必须知道!
前端·人工智能·后端
aiopencode4 小时前
使用 Ipa Guard 命令行版本将 IPA 混淆接入自动化流程
后端·ios
掘金者阿豪4 小时前
Kavita+cpolar 打造随身数字书房,让资源不再混乱,通勤 、出差都能随心读。
后端
心之语歌4 小时前
Spring Security api接口 认证放行
后端
用户8356290780514 小时前
Python 实现 PPT 转 HTML
后端·python
0xDevNull4 小时前
MySQL索引进阶用法
后端·mysql
舒一笑5 小时前
程序员效率神器:一文掌握 tmux(服务器开发必备工具)
运维·后端·程序员