Go语言实现RSA加解密算法详解
作者:JonLee 时间:2024-02-08 12:20:55
随着互联网的高速发展,人们对安全的要求也越来越高。密码学中两大经典算法,一个是对称加解密,另一个是非对称加解密,这里就来分享一下非对称加密算法的代表: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,它还支持AES
、DES
、RSA
、sha1
、Hmac-Sha1
、sha256
、Hmac-Sha256
等常用算法。
来源:https://segmentfault.com/a/1190000043858840
标签:Go,RSA
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
python实现opencv+scoket网络实时图传
2023-07-03 16:09:17
一组常用的弹出窗口用法总结
2007-10-08 13:04:00
javascript中的数字与字符串相加实例分析
2024-06-05 09:12:13
如何解决MySQL的客户端不支持鉴定协议
2008-11-27 17:10:00
Python实现的微信好友数据分析功能示例
2023-09-18 06:00:21
![](https://img.aspxhome.com/file/2023/0/101480_0s.png)
web.py 十分钟创建简易博客实现代码
2022-10-23 00:55:38
python 实现提取PPT中所有的文字
2023-05-01 04:21:35
![](https://img.aspxhome.com/file/2023/7/81637_0s.gif)
10分钟带你上手Vue3中新增的API
2024-06-05 10:03:00
100 个 Python 小例子(练习题二)
2021-02-09 10:15:31
asp如何显示已在数据库编码了的相对应的记录?
2010-06-09 18:44:00
Python中对字典的几个处理方法分享
2021-03-13 05:48:57
window.print()局部打印三种方式(小结)
2024-04-28 10:18:57
python自动化之re模块详解
2021-07-01 19:34:16
Python教程之Python多态的深层次理解
2021-07-30 07:50:53
不同浏览器空格的宽度
2007-08-22 08:29:00
![](https://img.aspxhome.com/file/UploadPic/20078/22/200782283622920s.gif)
用python计算文件的MD5值
2023-06-20 21:28:27
python实现简单的购物程序代码实例
2022-09-03 05:29:13
你是真正的用户体验设计者吗? Ⅴ
2008-04-19 18:32:00
![](https://img.aspxhome.com/file/UploadPic/20084/19/2008419215352323s.jpg)
python opencv之SURF算法示例
2021-03-06 13:10:28
![](https://img.aspxhome.com/file/2023/5/110455_0s.png)
对python字典过滤条件的实例详解
2022-01-28 14:02:30