收藏
回答

在支付成功回调函数里做验签的时候 ,总是出错,请问是为什么?

我在支付成功回调函数里做验签的时候获取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);
    }
}

替换了证书里的多余字符,还是报错。




回答关注问题邀请回答
收藏

2 个回答

登录 后发表内容