生成RSA证书:#
openssl方式生成#
openssl genrsa -out rsa_private_key.pem 1024
openssl rsa -in rsa_private_key.pem -pubout -out rsa_public_key.pem
Go代码方式生成
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"os"
)
func GenerateRSAKey(bits int) {
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
panic(err)
}
X509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey)
privateFile, err := os.Create("private.pem")
if err != nil {
panic(err)
}
defer privateFile.Close()
privateBlock := pem.Block{Type: "RSA Private Key", Bytes: X509PrivateKey}
pem.Encode(privateFile, &privateBlock)
publicKey := privateKey.PublicKey
X509PublicKey, err := x509.MarshalPKIXPublicKey(&publicKey)
if err != nil {
panic(err)
}
publicFile, err := os.Create("public.pem")
if err != nil {
panic(err)
}
defer publicFile.Close()
publicBlock := pem.Block{Type: "RSA Public Key", Bytes: X509PublicKey}
pem.Encode(publicFile, &publicBlock)
}
func main() {
GenerateRSAKey(2048)
}
RSA数据加/解密
package main
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"fmt"
"os"
)
func RSA_Encrypt(plainText []byte, path string) []byte {
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
info, _ := file.Stat()
buf := make([]byte, info.Size())
file.Read(buf)
block, _ := pem.Decode(buf)
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
panic(err)
}
publicKey := publicKeyInterface.(*rsa.PublicKey)
cipherText, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, plainText)
if err != nil {
panic(err)
}
return cipherText
}
func RSA_Decrypt(cipherText []byte,path string) []byte{
file,err:=os.Open(path)
if err!=nil{
panic(err)
}
defer file.Close()
info, _ := file.Stat()
buf:=make([]byte,info.Size())
file.Read(buf)
block, _ := pem.Decode(buf)
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err!=nil{
panic(err)
}
plainText,_:=rsa.DecryptPKCS1v15(rand.Reader,privateKey,cipherText)
return plainText
}
func main() {
data := []byte("hello world")
encrypt := RSA_Encrypt(data, "public.pem")
fmt.Println(string(encrypt))
decrypt := RSA_Decrypt(encrypt, "private.pem")
fmt.Println(string(decrypt))
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本