0 Star 1 Fork 0

有点心急 / gotls

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
rsa.go 1.46 KB
一键复制 编辑 原始数据 按行查看 历史
有点心急 提交于 2024-05-04 01:31 . 24.05.04
package encryptT
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"gitee.com/Jiudan0905/go-tools/logT"
)
// 生成Rsa的公钥和私钥
func GenerateRSAKey(bits int) ([]byte, []byte) {
// 私钥
privateKey, err := rsa.GenerateKey(rand.Reader, bits)
if err != nil {
logT.Error(err.Error())
panic(err)
}
X509PrivateKey := x509.MarshalPKCS1PrivateKey(privateKey)
privateBlock := pem.Block{Type: "RSA Private Key", Bytes: X509PrivateKey}
// 公钥
publicKey := privateKey.PublicKey
X509PublicKey, err := x509.MarshalPKIXPublicKey(&publicKey)
if err != nil {
logT.Error(err.Error())
panic(err)
}
publicBlock := pem.Block{Type: "RSA Public Key", Bytes: X509PublicKey}
// 输出
return pem.EncodeToMemory(&publicBlock), pem.EncodeToMemory(&privateBlock)
}
func EncryptRSA(plainText string, buf []byte) []byte {
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, []byte(plainText))
if err != nil {
logT.Error(err.Error())
panic(err)
}
return cipherText
}
func DecryptRSA(cipherText []byte, buf []byte) string {
block, _ := pem.Decode(buf)
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
logT.Error(err.Error())
panic(err)
}
plainText, _ := rsa.DecryptPKCS1v15(rand.Reader, privateKey, cipherText)
return string(plainText)
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/ydxj/gotls.git
git@gitee.com:ydxj/gotls.git
ydxj
gotls
gotls
v0.0.4

搜索帮助

344bd9b3 5694891 D2dac590 5694891