Convert a PEM-formatted String to a java.security.cert.X509Certificate
Decode the Base64 to binary, with some InputStream reading it, then try
CertificateFactory cf = CertificateFactory.getInstance("X.509");
Certificate cert = cf.generateCertificate(is);
I have a similar problem, I'm pasting also here the java code that worked for me in case anyone neaded it :
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));
}
Tried to follow @Balaji Boggaram Ramanarayan code but IDE keep on throwing Exception. Instead i convert the string to bytes and it works perfectly.
private X509Certificate convertStringToX509Cert(String certificate) throws Exception{
InputStream targetStream = new ByteArrayInputStream(certificate.getBytes());
return (X509Certificate) CertificateFactory
.getInstance("X509")
.generateCertificate(targetStream);
}
Not to mentions, this method doesn't need to remove .pem header and footer (-----BEGIN PRIVATE KEY----- and -----END PRIVATE KEY-----)