Generate X509Certificate from byte[]?

JavaX509certificate

Java Problem Overview


Is there a possibility to generate an java.security.cert.X509Certificate from an byte[]?

Java Solutions


Solution 1 - Java

Sure.

The certificate objects can be created by an instance of CertificateFactory - in particular, one configured to create X509 certificates. This can be created like so:

CertificateFactory certFactory = CertificateFactory.getInstance("X.509");

Then you need to pass it an InputStream containing the bytes of the certificate. This can be achieved by wrapping your byte array in a ByteArrayInputStream:

InputStream in = new ByteArrayInputStream(bytes);
X509Certificate cert = (X509Certificate)certFactory.generateCertificate(in);

Solution 2 - Java

You can do something like:

X509Certificate certificate = signature.getKeyInfo().getX509Datas().get(0).getX509Certificates().get(0);

String lexicalXSDBase64Binary = certificate.getValue();
byte[] decoded = DatatypeConverter.parseBase64Binary(lexicalXSDBase64Binary);

        
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
Certificate cert = certFactory.generateCertificate(new ByteArrayInputStream(decoded));

Solution 3 - Java

InputStream stream = null;
byte[] bencoded = javax.xml.bind.DatatypeConverter.parseBase64Binary(x509CertificateStr);

try {
    CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
    cert = (X509Certificate) certFactory.generateCertificate(stream);

} catch (java.security.cert.CertificateException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAlexView Question on Stackoverflow
Solution 1 - JavaAndrzej DoyleView Answer on Stackoverflow
Solution 2 - Javahal9000View Answer on Stackoverflow
Solution 3 - Javauser6103982View Answer on Stackoverflow