微信支付v3版本获取商户私钥报错:Illegal base64 character 2e
Exception in thread "main" java.lang.IllegalArgumentException: Illegal base64 character 2e
at java.util.Base64$Decoder.decode0(Base64.java:714)
at java.util.Base64$Decoder.decode(Base64.java:526)
at java.util.Base64$Decoder.decode(Base64.java:549)
at com.wechat.pay.contrib.apache.httpclient.util.PemUtil.loadPrivateKey(PemUtil.java:31)
at com.wechat.pay.contrib.apache.httpclient.util.PemUtil.loadPrivateKey(PemUtil.java:52)
at com.weixin.WxPayUtils.main(WxPayUtils.java:92)
源代码:
/**
* 获取私钥。
*
* @param filename 私钥文件路径 (required)
* @return 私钥对象
*/
public static PrivateKey getPrivateKey(String filename) throws IOException {
String content = new String(Files.readAllBytes(Paths.get(filename)), "utf-8");
System.out.println("content :"+content);
try {
String privateKey = content.replace("-----BEGIN PRIVATE KEY-----", "")
.replace("-----END PRIVATE KEY-----", "")
.replaceAll("\\s+", "");
System.out.println("privateKey :"+privateKey);
KeyFactory kf = KeyFactory.getInstance("RSA");
return kf.generatePrivate(
new PKCS8EncodedKeySpec(Base64.getDecoder().decode(privateKey)));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("当前Java环境不支持RSA", e);
} catch (InvalidKeySpecException e) {
throw new RuntimeException("无效的密钥格式");
}
}
请教是哪里问题?