1 Star 0 Fork 0

carlmax_my/console-core-go

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
文件
克隆/下载
rsa.go 2.16 KB
一键复制 编辑 原始数据 按行查看 历史
carlmax_my 提交于 2024-12-02 21:32 . init project
package rsa
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/pem"
"gitee.com/carlmax_my/console-core-go/pkg/crypto/base64"
)
var _ Public = (*rsaPub)(nil)
var _ Private = (*rsaPri)(nil)
type Public interface {
i()
// Encrypt 加密
Encrypt(encryptStr string) (string, error)
}
type Private interface {
i()
// Decrypt 解密
Decrypt(decryptStr string) (string, error)
}
type rsaPub struct {
PublicKey string
url bool // base64 url safe format, replace (+/)->(-_) default is true
}
type rsaPri struct {
PrivateKey string
url bool // base64 url safe format, replace (+/)->(-_)
}
func NewPublic(publicKey string) Public {
return &rsaPub{
PublicKey: publicKey,
url: true,
}
}
func NewPublicWithUrl(publicKey string, url bool) Public {
return &rsaPub{
PublicKey: publicKey,
url: url,
}
}
func NewPrivate(privateKey string) Private {
return &rsaPri{
PrivateKey: privateKey,
url: true,
}
}
func NewPrivateWithUrl(privateKey string, url bool) Private {
return &rsaPri{
PrivateKey: privateKey,
url: url,
}
}
func (pub *rsaPub) i() {}
func (pub *rsaPub) Encrypt(encryptStr string) (string, error) {
// pem 解码
block, _ := pem.Decode([]byte(pub.PublicKey))
// x509 解码
publicKeyInterface, err := x509.ParsePKIXPublicKey(block.Bytes)
if err != nil {
return "", err
}
// 类型断言
publicKey := publicKeyInterface.(*rsa.PublicKey)
//对明文进行加密
encryptedStr, err := rsa.EncryptPKCS1v15(rand.Reader, publicKey, []byte(encryptStr))
if err != nil {
return "", err
}
//返回密文
return base64.New(pub.url).Encode(encryptedStr), nil
}
func (pri *rsaPri) i() {}
func (pri *rsaPri) Decrypt(decryptStr string) (string, error) {
// pem 解码
block, _ := pem.Decode([]byte(pri.PrivateKey))
// X509 解码
privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return "", err
}
decryptBytes, err := base64.New(pri.url).Decode(decryptStr)
if err != nil {
return "", err
}
//对密文进行解密
decrypted, err := rsa.DecryptPKCS1v15(rand.Reader, privateKey, decryptBytes)
if err != nil {
return "", err
}
//返回明文
return string(decrypted), nil
}
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
Go
1
https://gitee.com/carlmax_my/console-core-go.git
git@gitee.com:carlmax_my/console-core-go.git
carlmax_my
console-core-go
console-core-go
v0.0.16

搜索帮助

0d507c66 1850385 C8b1a773 1850385