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加解密、签名验证算法

相关推荐
阿猿收手吧!39 分钟前
【C++】Ranges:彻底改变STL编程方式
开发语言·c++
云游云记1 小时前
php 随机红包数生成
开发语言·php·随机红包
程序员林北北1 小时前
【前端进阶之旅】JavaScript 一些常用的简写技巧
开发语言·前端·javascript
李慕婉学姐1 小时前
Springboot平安超市商品管理系统6sytj3w6(程序+源码+数据库+调试部署+开发环境)带论文文档1万字以上,文末可获取,系统界面在最后面。
数据库·spring boot·后端
PRINT!1 小时前
RabbitMQ实战项目(含代码仓库地址+视频教程地址)基本篇已更新完结,高级篇持续更新中
java·分布式·后端·微服务·rabbitmq
gAlAxy...2 小时前
MyBatis-Plus 核心 CRUD 操作全解析:BaseMapper 与通用 Service 实战
java·开发语言·mybatis
开开心心就好2 小时前
一键加密隐藏视频,专属格式播放工具
java·linux·开发语言·网络·人工智能·macos
CUC-MenG2 小时前
Codeforces Round 1079 (Div. 2)A,B,C,D,E1,E2,F个人题解
c语言·开发语言·数学·算法
阿里嘎多学长2 小时前
2026-02-07 GitHub 热点项目精选
开发语言·程序员·github·代码托管
小心草里有鬼2 小时前
VMware虚拟机扩容
linux·后端·centos·vim