代码拉取完成,页面将自动刷新
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
}
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。