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

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (425)

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

下面是我在Scala中编写的内容

val cert = factory.generateCertificate(
    new ByteArrayInputStream(
      Base64.decodeBase64(
        cert.stripPrefix("-----BEGIN CERTIFICATE-----").stripSuffix("-----END CERTIFICATE-----")
      )
    ).asInstanceOf[X509Certificate]
提问于
用户回答回答于

将base 64解码为二进制,并由一些InputStream读取它,然后尝试

CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(is);
用户回答回答于

我的代码:

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.decode(certStr.replaceAll(X509Factory.BEGIN_CERT, "").replaceAll(X509Factory.END_CERT, ""));

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

扫码关注云+社区

领取腾讯云代金券

年度创作总结 领取年终奖励