111 lines
2.3 KiB
Go
111 lines
2.3 KiB
Go
package wjcrypto
|
|
|
|
import (
|
|
"encoding/json"
|
|
"sandc/pkg/bhttp"
|
|
|
|
"fmt"
|
|
)
|
|
|
|
type WJResData struct {
|
|
Code int `json:"code,omitempty"`
|
|
Data WJData `json:"data,omitempty"`
|
|
Err string `json:"err,omitempty"`
|
|
}
|
|
|
|
type WJData struct {
|
|
Key string `json:"key,omitempty"`
|
|
Val string `json:"val,omitempty"`
|
|
}
|
|
|
|
type WJCrypto struct {
|
|
encryptUrl string
|
|
decryptUrl string
|
|
}
|
|
|
|
// WJSuccessTag wj加解密成功返回标记
|
|
const WJSuccessTag = "success"
|
|
|
|
// NewWJCrypto
|
|
func NewWJCrypto(wjCryptUrl string) *WJCrypto {
|
|
encryptUrl := fmt.Sprintf("%s/encrypt", wjCryptUrl)
|
|
decryptUrl := fmt.Sprintf("%s/decrypt", wjCryptUrl)
|
|
return &WJCrypto{encryptUrl: encryptUrl, decryptUrl: decryptUrl}
|
|
}
|
|
|
|
// Encrypt 对WJ数据进行加密
|
|
func (a *WJCrypto) Encrypt(projectId, key, value string) (*WJData, error) {
|
|
x, err := bhttp.NewBhttpClient(bhttp.WithTimeout(2), bhttp.WithRetry(10))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
x.SetHeader("Content-Type", "multipart/form-data")
|
|
x.SetParam("project_name", projectId)
|
|
x.SetParam("key", key)
|
|
x.SetParam("val", value)
|
|
|
|
if a.encryptUrl == "" {
|
|
return nil, fmt.Errorf("加密url丢失")
|
|
}
|
|
|
|
res, err := x.DoPost(a.encryptUrl)
|
|
|
|
if err != nil {
|
|
return nil, fmt.Errorf("wj超时: %w", err)
|
|
}
|
|
|
|
var info WJResData
|
|
err = json.Unmarshal(res, &info)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if info.Err != WJSuccessTag {
|
|
return nil, fmt.Errorf(info.Err)
|
|
}
|
|
|
|
if info.Data.Key == "" || info.Data.Val == "" {
|
|
return nil, fmt.Errorf("解密失败,数据为空")
|
|
}
|
|
|
|
return &info.Data, nil
|
|
}
|
|
|
|
// Decrypt 对WJ数据进行解密
|
|
func (a *WJCrypto) Decrypt(projectId, key, value string) (*WJData, error) {
|
|
x, err := bhttp.NewBhttpClient(bhttp.WithTimeout(2), bhttp.WithRetry(10))
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
x.SetHeader("Content-Type", "multipart/form-data")
|
|
x.SetParam("project_name", projectId)
|
|
x.SetParam("key", key)
|
|
x.SetParam("val", value)
|
|
|
|
if a.decryptUrl == "" {
|
|
return nil, fmt.Errorf("解密url丢失")
|
|
}
|
|
|
|
res, err := x.DoPost(a.decryptUrl)
|
|
|
|
if err != nil {
|
|
return nil, fmt.Errorf("wj超时: %w", err)
|
|
}
|
|
|
|
var info WJResData
|
|
err = json.Unmarshal(res, &info)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
if info.Err != WJSuccessTag {
|
|
return nil, fmt.Errorf(info.Err)
|
|
}
|
|
|
|
if info.Data.Key == "" || info.Data.Val == "" {
|
|
return nil, fmt.Errorf("解密失败,数据为空")
|
|
}
|
|
|
|
return &info.Data, nil
|
|
}
|