JeffreySu/WeiXinMPSDK · error · ArgumentException
品牌 API 密钥必须是有效的 PEM 或 Base64 DER。
Error message
品牌 API 密钥必须是有效的 PEM 或 Base64 DER。
What it means
NormalizeKey strips PEM headers/footers/whitespace and then validates the result is valid Base64 (representing DER key bytes) by calling Convert.FromBase64String; on FormatException it throws ArgumentException stating the brand API key must be a valid PEM or Base64 DER. It prevents constructing credentials with a malformed key that would fail later at signature time.
Solutions
- Verify the key content between the BEGIN/END markers is valid Base64 (test with Convert.FromBase64String or a Base64 validator).
- Re-export the key in PEM format and pass the full file contents, including -----BEGIN/END----- lines.
- Check for JSON/YAML escaping issues that replaced newlines or introduced stray characters.
- Ensure you are passing the key itself, not a passphrase or a certificate.
Example fix
// before
var key = File.ReadAllText("brand_key.txt"); // contains log notes around the PEM
// after
var key = File.ReadAllText("apiclient_key.pem"); // clean PEM file Defensive patterns
Strategy: validation
Validate before calling
bool IsValidBase64Key(string pem)
{
var body = pem.Replace("-----BEGIN PRIVATE KEY-----","").Replace("-----END PRIVATE KEY-----","")
.Replace("\r","").Replace("\n","").Trim();
try { Convert.FromBase64String(body); return body.Length > 0; }
catch (FormatException) { return false; }
} Try / catch
try { creds = new TenPayBrandApiCredentials(mchId, serial, publicKey, privateKey); }
catch (ArgumentException ex) when (ex.Message.Contains("PEM"))
{ logger.LogError(ex, "Brand key is not valid PEM/Base64 DER"); throw; } Prevention
- Store keys as whole PEM files and load with File.ReadAllText, never copy-paste through editors that mangle whitespace.
- Validate keys at startup with a Base64 sanity check.
- Beware JSON/YAML escaping of newlines in embedded keys.
- Ensure you pass the key, not a passphrase or certificate.
When it happens
Trigger: Passing a raw PEM including surrounding text the stripper can't handle, a truncated key, a key in PKCS#1 raw text without valid Base64 payload, a URL-safe Base64 key, or accidentally passing a password/passphrase instead of the key.
Common situations: Pasting the PEM file with '-----BEGIN ...-----' plus extra prose; copying only part of the key from a document; keys converted between formats incorrectly; storing the key with escaped newlines in JSON that weren't unescaped.
Understand the failure class
Background: "Invalid ... format", "must be in format X", "does not look like a ..." — invalid argument format errors across CLI tools and libraries — this error's family across 17 libraries.
Related errors
AI-assisted analysis of JeffreySu/WeiXinMPSDK@be573f6f94 (2026-09-12).
Data as JSON: /api/errors/4abb12e421da2519.
Report an issue: GitHub.
Appendix: source
Thrown at src/Senparc.Weixin.TenPay/Senparc.Weixin.TenPayV3/HttpHandlers/TenPayBrandApiCredentials.cs:126
var trimmedLine = line.Trim();
if (trimmedLine.StartsWith("-----",
StringComparison.Ordinal))
{
continue;
}
builder.Append(trimmedLine);
}
}
var normalized = builder.ToString();
try
{
Convert.FromBase64String(normalized);
}
catch (FormatException exception)
{
throw new ArgumentException(
"品牌 API 密钥必须是有效的 PEM 或 Base64 DER。",
parameterName, exception);
}
return normalized;
}
}
}
View on GitHub (pinned to be573f6f94)