将 PEM 格式的字符串转换为 java.security.cert.X509Certificate

2022-08-31 20:26:26

如何从 PEM 格式的字符串创建实例?PEM 格式的字符串是 HTTP 请求“SSL_CLIENT_CERT”标头值。java.security.cert.X509Certificate

根据mgaert的答案,这是我在Scala中写的

val cert = factory.generateCertificate(
    new ByteArrayInputStream(
      Base64.decodeBase64(
        cert.stripPrefix("-----BEGIN CERTIFICATE-----").stripSuffix("-----END CERTIFICATE-----")
      )
    ).asInstanceOf[X509Certificate]

答案 1

将 Base64 解码为二进制,并读取一些 InputStream,然后尝试

CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(is);

答案 2

我有一个类似的问题,我也在这里粘贴了对我有用的java代码,以防有人讨厌它:

import java.util.Base64;

public static X509Certificate parseCertificate(String _headerName, HttpServletRequest _request) throws CertificateException {
    String certStr = _request.getHeader("x-clientcert");
    //before decoding we need to get rod off the prefix and suffix
    byte [] decoded = Base64.getDecoder().decode(certStr.replaceAll(X509Factory.BEGIN_CERT, "").replaceAll(X509Factory.END_CERT, ""));

    return (X509Certificate) CertificateFactory.getInstance("X.509").generateCertificate(new ByteArrayInputStream(decoded));
}