我在支付成功回调函数里做验签的时候获取publicKey时失败。下面是我做验签的代码,请帮我看看到底是怎么回事?
ClassPathResource resource = new ClassPathResource(wxPayConfig.getPublicKeyPath().replace("classpath:", ""));
Certificate certificate = CertificateFactory.getInstance("X.509").generateCertificate(new FileInputStream(Paths.get(resource.getUrl().toURI()).toString()));
PublicKey publicKey = certificate.getPublicKey();
在 这行抛出如下错误 PublicKey publicKey = certificate.getPublicKey();
java.security.cert.CertificateException: Unable to initialize, java.io.IOException: Too short
我又用
ClassPathResource resource = new ClassPathResource(wxPayConfig.getPublicKeyPath().replace("classpath:", ""));
String content = IOUtils.toString(
new FileInputStream(Paths.get(resource.getUrl().toURI()).toString()),
StandardCharsets.UTF_8
);
Certificate certificate = loadCertificate(content);
PublicKey publicKey = certificate.getPublicKey();
public X509Certificate loadCertificate(String pem) throws Exception {
// 1. 清理PEM格式(移除标记和空白)
String cleanPem = pem.replace("-----BEGIN PUBLIC KEY-----", "")
.replace("-----END PUBLIC KEY-----", "")
.replaceAll("\\s+", "");
// 2. Base64解码
byte[] certBytes = Base64.getDecoder().decode(cleanPem);
if (certBytes.length < 100) { // 简单长度检查
throw new IllegalArgumentException("证书数据过短");
}
// 3. 加载证书
CertificateFactory factory = CertificateFactory.getInstance("X.509");
try (InputStream in = new ByteArrayInputStream(certBytes)) {
return (X509Certificate) factory.generateCertificate(in);
}
}
替换了证书里的多余字符,还是报错。

v3版本接口的验签需要用平台证书,请检查下获取的证书是否正确。平台证书可以调接口获取,没有实现接口也可以用我们的证书下载工具https://pay.weixin.qq.com/doc/v3/partner/4012715700
https://tools.aifuwu.net/wechat-pay-tools/apiv3-signature-validator 试试能不能校验通过