45 lines
971 B
Go
45 lines
971 B
Go
|
package l_encrypt
|
||
|
|
||
|
import (
|
||
|
"fmt"
|
||
|
"gitea.cdlsxd.cn/self-tools/l_crypt/encrypt_way/sm2"
|
||
|
)
|
||
|
|
||
|
func NewSm2(app *AppEncrypt) ApiCrypt {
|
||
|
return &SM2{
|
||
|
App: app,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (r *SM2) Encrypt(data string) (encryptData []byte, err error) {
|
||
|
|
||
|
if r.App.MerchantPublicKey == "" {
|
||
|
return nil, fmt.Errorf("密钥缺失")
|
||
|
}
|
||
|
|
||
|
encryptDataString, err := sm2.SM2Encrypt(data, r.App.MerchantPublicKey)
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("加密失败")
|
||
|
}
|
||
|
encryptData = []byte(encryptDataString)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
func (r *SM2) Decrypt(encryptData string) (decryptData []byte, err error) {
|
||
|
defer func() {
|
||
|
if e := recover(); e != nil {
|
||
|
err = fmt.Errorf("解密失败")
|
||
|
}
|
||
|
}()
|
||
|
if r.App.PrivateKey == "" || r.App.PublicKey == "" {
|
||
|
return nil, fmt.Errorf("密钥缺失")
|
||
|
}
|
||
|
|
||
|
decryptDataString, err := sm2.SM2Decrypt(encryptData, r.App.PublicKey, r.App.PrivateKey)
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("解密失败")
|
||
|
}
|
||
|
decryptData = []byte(decryptDataString)
|
||
|
return
|
||
|
}
|