47 lines
1.2 KiB
Go
47 lines
1.2 KiB
Go
|
package l_encrypt
|
||
|
|
||
|
import (
|
||
|
"encoding/base64"
|
||
|
"fmt"
|
||
|
"gitea.cdlsxd.cn/self-tools/l_crypt/encrypt_way/sm4"
|
||
|
)
|
||
|
|
||
|
func NewSm4(app *AppEncrypt) ApiCrypt {
|
||
|
return &SM4{
|
||
|
App: app,
|
||
|
}
|
||
|
}
|
||
|
|
||
|
func (r *SM4) Encrypt(data string) (encryptData []byte, err error) {
|
||
|
if r.App.MerchantPublicKey == "" || r.App.PrivateKey == "" {
|
||
|
return nil, fmt.Errorf("密钥缺失")
|
||
|
}
|
||
|
encryptDataString, err := sm4.Sm4Encrypt(r.App.UniKEY, r.App.PrivateKey, r.App.MerchantPublicKey, data, "", true)
|
||
|
base64Json := base64.StdEncoding.EncodeToString([]byte(encryptDataString))
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("加密失败")
|
||
|
}
|
||
|
encryptData = []byte(base64Json)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
func (r *SM4) Decrypt(encryptData string) (decryptData []byte, err error) {
|
||
|
defer func() {
|
||
|
if e := recover(); e != nil {
|
||
|
err = fmt.Errorf("解密失败")
|
||
|
}
|
||
|
}()
|
||
|
if r.App.PrivateKey == "" || r.App.MerchantPublicKey == "" {
|
||
|
return nil, fmt.Errorf("密钥缺失")
|
||
|
}
|
||
|
entry, _ := base64.StdEncoding.DecodeString(encryptData)
|
||
|
encryptData = string(entry)
|
||
|
decryptDataString, err := sm4.Sm4Decrypt(r.App.UniKEY, r.App.PrivateKey, r.App.MerchantPublicKey, encryptData, true)
|
||
|
if err != nil {
|
||
|
return nil, fmt.Errorf("解密失败")
|
||
|
}
|
||
|
decryptData = []byte(decryptDataString)
|
||
|
return
|
||
|
|
||
|
}
|