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,它还支持AES、DES、RSA、sha1、Hmac-Sha1、sha256、Hmac-Sha256等常用算法。

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

相关推荐
琳少_1 小时前
java程序设计笔记
java·开发语言·数据库·笔记
考虑考虑1 小时前
记一次@Async生产事故
spring boot·后端·spring
小荷才露尖尖角,早有蜻蜓立上头2 小时前
SpringBoot 定时任务
java·spring boot·后端
ServBay2 小时前
AI 请求去哪了?OpenRouter 路由、供应商回退与数据留存
后端·aigc·ai编程
Moment3 小时前
AI 写代码越来越快,程序员为什么反而更累了
前端·后端·面试
Helix2503 小时前
JDK高频报错速查手册:javac不是内部命令、内存溢出、版本不兼容等12类问题解决方法
java·开发语言·内存溢出·java异常处理·jdk版本兼容·jdk报错·javac报错
apeman3 小时前
git-cherry合并代码工具
前端·后端
郝学胜-神的一滴4 小时前
Effective STL 条款 07:指针容器销毁前先删除
开发语言·c++·vscode·leetcode·rpc·visual studio
CoderYanger4 小时前
A.每日一题:2243. 计算字符串的数字和
java·开发语言·程序人生·leetcode·面试·蓝桥杯·学习方法
行百里er4 小时前
轻量级 Spring 监测工具 Spring Insight 版本进展:Server 2.1.0 + Agent 0.6.0
后端·开源·监控