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

相关推荐
Chester_19993 小时前
CSP202203C.计算资源调度器
开发语言·数据结构·c++·蓝桥杯
2601_962055974 小时前
跟据spring boot版本,查看对应的tomcat,并查看可支持的tomcat的版本范围
spring boot·后端·tomcat
EXI-小洲4 小时前
Java 操作 Word:字符串替换、图片插入、动态生成表格与API接口下载
java·开发语言·spring boot·word
会周易的程序员4 小时前
给 PLC 写一个字节码虚拟机:STVM 虚拟机架构设计
开发语言·c++·虚拟机·软plc·iec61131·stvm
机器视觉知识推荐、就业指导4 小时前
为什么老说“纯 Qt 没啥就业市场”?
开发语言·qt
telepan4 小时前
Qt 开发避坑与性能指南:如何优雅、安全地定义全局常量字符串?
开发语言·qt
m0_695251495 小时前
Qt MaintenanceTool 使用国内镜像加速下载(超详细教程)
开发语言·qt
Lost of 程序猿5 小时前
ASP.NET Core API 幂等性设计深度实战:从一次重复申领事故说起
后端·asp.net
大衛說6 小时前
《Python 从入门到精通》系列总览与学习路线
开发语言·python·学习
QQ_21696290966 小时前
【源码编号:project79475】SpringBoot校内二手交易平台:商品发布、分类检索、留言交流、订单管理全流程实战
java·spring boot·后端