package payment import ( "crypto/aes" "crypto/cipher" "crypto/rand" "crypto/sha256" "encoding/base64" "errors" "io" "strings" beego "github.com/beego/beego/v2/server/web" ) const configCipherPrefix = "YZP1:" const fallbackSecretKey = "yunzer_payment_default_secret_key_v1" func configKey() []byte { raw, _ := beego.AppConfig.String("payment_secret_key") if strings.TrimSpace(raw) == "" { raw = fallbackSecretKey } sum := sha256.Sum256([]byte(raw)) return sum[:] } func EncryptConfig(plain string) (string, error) { if plain == "" { return "", nil } block, err := aes.NewCipher(configKey()) if err != nil { return "", err } gcm, err := cipher.NewGCM(block) if err != nil { return "", err } nonce := make([]byte, gcm.NonceSize()) if _, err = io.ReadFull(rand.Reader, nonce); err != nil { return "", err } ciphertext := gcm.Seal(nil, nonce, []byte(plain), nil) buf := append([]byte(configCipherPrefix), nonce...) buf = append(buf, ciphertext...) return base64.StdEncoding.EncodeToString(buf), nil } func DecryptConfig(encoded string) (string, error) { if encoded == "" { return "", nil } raw, err := base64.StdEncoding.DecodeString(encoded) if err != nil { return "", errors.New("渠道参数不是有效的 base64") } if len(raw) < len(configCipherPrefix) || string(raw[:len(configCipherPrefix)]) != configCipherPrefix { return "", errors.New("渠道参数格式不正确(缺少加密前缀)") } block, err := aes.NewCipher(configKey()) if err != nil { return "", err } gcm, err := cipher.NewGCM(block) if err != nil { return "", err } nonce := raw[len(configCipherPrefix) : len(configCipherPrefix)+gcm.NonceSize()] ciphertext := raw[len(configCipherPrefix)+gcm.NonceSize():] plain, err := gcm.Open(nil, nonce, ciphertext, nil) if err != nil { return "", errors.New("渠道参数解密失败(payment_secret_key 是否被更换过?)") } return string(plain), nil } func MaskSecret(v string) string { if v == "" { return "" } if len(v) <= 4 { return "******" } return "******" + v[len(v)-4:] } func IsMasked(v string) bool { return strings.HasPrefix(v, "******") }