WxJava
WxJava copied to clipboard
Fix PEM format private key and certificate handling in WeChat Pay config
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:
loadConfigInputStreamalways applied Base64 decoding to string inputs- PEM format strings contain headers (
-----BEGIN PRIVATE KEY-----) with characters that are invalid in Base64 - This caused
IllegalArgumentException: Illegal base64 character 2d(hyphen character) - The corrupted data then failed validation in
PemUtils.loadPrivateKey()
Solution
Added intelligent format detection to distinguish between:
- PEM format (contains
-----BEGINand-----ENDmarkers): Pass through as UTF-8 bytes forPemUtilsto handle - Pure Base64 format: Continue decoding as before for backward compatibility
Changes
- Modified
loadConfigInputStreammethod with smart format detection - Added
StandardCharsetsimport 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.