package pay import ( "crypto/rsa" "crypto/x509" "encoding/pem" "errors" "fmt" "os" ) type Config struct { AppID string MchID string CertificateSerialNo string PrivateKeyPath string PlatformCertPath string // 平台证书路径(可选,用于首次验签或离线启动) APIv3Key string // 用于解密支付回调通知及拉取平台证书 NotifyURL string } func loadPrivateKey(path string) (*rsa.PrivateKey, error) { data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("read private key %s: %w", path, err) } block, _ := pem.Decode(data) if block == nil { return nil, fmt.Errorf("invalid private key pem: %s", path) } switch block.Type { case "PRIVATE KEY": key, err := x509.ParsePKCS8PrivateKey(block.Bytes) if err != nil { return nil, fmt.Errorf("parse pkcs8 private key %s: %w", path, err) } privateKey, ok := key.(*rsa.PrivateKey) if !ok { return nil, errors.New("private key is not rsa") } return privateKey, nil case "RSA PRIVATE KEY": privateKey, err := x509.ParsePKCS1PrivateKey(block.Bytes) if err != nil { return nil, fmt.Errorf("parse pkcs1 private key %s: %w", path, err) } return privateKey, nil default: return nil, fmt.Errorf("unsupported private key pem type %q in %s", block.Type, path) } }