50

In versions prior to r146 it was possible to create X509Certificate objects directly. Now that API is deprecated and the new one only deliveres a X509CertificateHolder object.

I cannot find a way to transform a X509CertificateHolder to X509Certificate.

How can this be done?

Steffen Heil
  • 4,286
  • 3
  • 32
  • 35

3 Answers3

98

I will answer to my own questions, but not delete it, in case someone else got the same problems:

return new JcaX509CertificateConverter().getCertificate(certificateHolder);

And for attribute certificates:

return new X509V2AttributeCertificate(attributeCertificateHolder.getEncoded());

Not nice, as it is encoding and decoding, but it works.

OrangeDog
  • 36,653
  • 12
  • 122
  • 207
Steffen Heil
  • 4,286
  • 3
  • 32
  • 35
  • Excelent reference. Thanks. – HMM Dec 11 '12 at 15:08
  • 1
    X509V2AttributeCertificate is now deprecated. I'm not sure what to use or how to parse. X509AttrCertParser is not deprecated, but engineRead() returns an X509V2AttributeCertificate which is deprecated. – Stealth Rabbi Feb 24 '16 at 12:14
  • I like this becausue it uses pure java methods. Steffen Heil's solution uses BC again and the class names are looking so that it could be changed in future. – Maik Apr 07 '23 at 04:43
5

Another option is this one :)

CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
InputStream in = new ByteArrayInputStream(certificateHolder.getEncoded());
X509Certificate cert = (X509Certificate) certFactory.generateCertificate(in);
Diego Palomar
  • 6,958
  • 2
  • 31
  • 42
-1

This is an possibility to get the X509CertificateHolder to X509Certificate and toString. (first sentence of the code is irrelevant)

X509CertificateHolder selfSignedCertificate = CertificateUtils.selfSignCertificate(certificationRequest, keyPair.getPrivate());
byte[] content = selfSignedCertificate.getEncoded();
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(new ByteArrayInputStream(content));
logger.debug("cert: {}", cert.toString());

........

Paul
  • 1
  • 3