You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
1.5 KiB

package secure
import (
"crypto/rand"
"crypto/rsa"
"crypto/x509"
"encoding/base64"
"encoding/pem"
"errors"
jsoniter "github.com/json-iterator/go"
"github.com/nanjishidu/gomini/gocrypto"
"live/app/lib/config"
)
type NetPackage struct {
Body string `json:"body"`
Key string `json:"key"`
}
func Decrypt(text []byte) ([]byte, error) {
np := NetPackage{}
err := jsoniter.Unmarshal(text, &np)
if err != nil {
return nil, err
}
originalKey, _ := base64.StdEncoding.DecodeString(np.Key)
key, err := RSADecrypt(originalKey, config.Config.Section("recook").Key("private_key").String())
if err != nil {
return nil, err
}
err = gocrypto.SetAesKey(string(key))
if err != nil {
return nil, err
}
originalBody, err := base64.StdEncoding.DecodeString(np.Body)
if err != nil {
return nil, err
}
body, err := gocrypto.AesECBDecrypt(originalBody)
if err != nil {
return nil, err
}
return body, nil
}
func RSADecrypt(data []byte, privateStr string) ([]byte, error) {
privateKey := "-----BEGIN RSA PRIVATE KEY-----\n"
lenPrivate := len(privateStr)
for i := 0; i < lenPrivate; i += 64 {
if i+64 <= lenPrivate {
privateKey += privateStr[i:i+64] + "\n"
} else {
privateKey += privateStr[i:] + "\n"
}
}
privateKey += "-----END RSA PRIVATE KEY-----"
block, _ := pem.Decode([]byte(privateKey))
if block == nil {
return nil, errors.New("private key error")
}
priv, err := x509.ParsePKCS1PrivateKey(block.Bytes)
if err != nil {
return nil, err
}
return rsa.DecryptPKCS1v15(rand.Reader, priv, data)
}