WxJava icon indicating copy to clipboard operation
WxJava copied to clipboard

Fix PEM format private key and certificate handling in WeChat Pay config

Open Copilot opened this issue 2 months ago • 0 comments

The loadConfigInputStream method in WxPayConfig was incorrectly applying Base64 decoding to all string inputs, causing failures when users provided PEM format private keys or certificates via setPrivateKeyString() or setPrivateCertString().

Problem

When users called:

payConfig.setPrivateKeyString("-----BEGIN PRIVATE KEY-----\nMIIE...\n-----END PRIVATE KEY-----");
payConfig.setPrivateCertString("-----BEGIN CERTIFICATE-----\nMIIC...\n-----END CERTIFICATE-----");

The SDK would throw WxRuntimeException: 无效的密钥格式 (Invalid Key Format) because:

  1. loadConfigInputStream always applied Base64 decoding to string inputs
  2. PEM format strings contain headers (-----BEGIN PRIVATE KEY-----) with characters that are invalid in Base64
  3. This caused IllegalArgumentException: Illegal base64 character 2d (hyphen character)
  4. The corrupted data then failed validation in PemUtils.loadPrivateKey()

Solution

Added intelligent format detection to distinguish between:

  • PEM format (contains -----BEGIN and -----END markers): Pass through as UTF-8 bytes for PemUtils to handle
  • Pure Base64 format: Continue decoding as before for backward compatibility

Changes

  • Modified loadConfigInputStream method with smart format detection
  • Added StandardCharsets import for proper UTF-8 encoding
  • Created comprehensive test coverage for both scenarios
  • Maintained full backward compatibility with existing Base64 usage

Testing

The fix handles all scenarios correctly:

// PEM format (now works)
payConfig.setPrivateKeyString("-----BEGIN PRIVATE KEY-----\n...\n-----END PRIVATE KEY-----");

// Base64 format (continues to work)
payConfig.setPrivateKeyString("MIIEvQIBADANBgkqhkiG9w0BAQE...");

This resolves WeChat Pay v3 API initialization failures in JDK 21 environments while preserving compatibility with existing implementations.

Fixes #3680.


✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.

Copilot avatar Sep 22 '25 16:09 Copilot