l_crypt/rsa.go

48 lines
1.1 KiB
Go
Raw Normal View History

2025-02-20 17:49:10 +08:00
package l_encrypt
import (
"encoding/base64"
"fmt"
"gitea.cdlsxd.cn/self-tools/l_crypt/encrypt_way/rsa"
)
func NewRsa(app *AppEncrypt) ApiCrypt {
return &Rsa{
App: app,
}
}
func (r *Rsa) Encrypt(data string) (encryptData []byte, err error) {
if r.App.MerchantPublicKey == "" {
return nil, fmt.Errorf("密钥缺失")
}
publicKeyPEM := `-----BEGIN PUBLIC KEY-----
` + r.App.MerchantPublicKey + `
-----END PUBLIC KEY-----`
encryptByte, err := rsa.Encrypt(publicKeyPEM, data)
if err != nil {
return nil, fmt.Errorf("Rsa加密失败")
}
encryptData = []byte(base64.StdEncoding.EncodeToString(encryptByte))
return
}
func (r *Rsa) Decrypt(encryptData string) (decryptData []byte, err error) {
defer func() {
if e := recover(); e != nil {
err = fmt.Errorf("Rsa解密失败")
}
}()
if r.App.PrivateKey == "" {
return nil, fmt.Errorf("密钥缺失")
}
privateKeyPEM := `-----BEGIN RSA PRIVATE KEY-----
` + r.App.PrivateKey + `
-----END RSA PRIVATE KEY-----`
decryptData, err = rsa.Decrypt(privateKeyPEM, encryptData)
if err != nil || decryptData == nil {
return nil, fmt.Errorf("Rsa解密失败")
}
return
}