60

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

Alex
  • 4,033
  • 9
  • 37
  • 52

3 Answers3

95

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);
default locale
  • 13,035
  • 13
  • 56
  • 62
Andrzej Doyle
  • 102,507
  • 33
  • 189
  • 228
  • 2
    Thanks for your answer. But I am getting "(java.security.cert.CertificateException) java.security.cert.CertificateException: Could not parse certificate: java.io.IOException: Empty input" on the last line. InputStream is not empty, but it throws Exception – 0bj3ct Jun 12 '15 at 07:22
  • 2
    Same thing happened to me at first because I wasn't thinking carefully about what I was doing. In my case it was because I was trying to do the above with the bytes from a keystore rather than the certificate in the keystore. Extracting the certificate from the keystore, getting the encoded bytes, and then working on those was what made this answer above work for me. – Trevor Brown Nov 13 '15 at 22:12
  • 6
    In my case the problem was that the byte[] was base 64 encoded... The error message was the slightly misleading "Empty input". Maybe it helps somebody sometime... – riskop Jun 09 '16 at 15:17
  • 1
    What about bytes[] from password protected JKS file? How do we generate certificate from it? – Shashank Jun 24 '20 at 20:11
0

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));
Skatox
  • 4,237
  • 12
  • 42
  • 47
hal9000
  • 201
  • 5
  • 25
-1
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();
}
António Ribeiro
  • 4,129
  • 5
  • 32
  • 49
  • The question doesn't mention base-64, and the initialization of `stream` is missing. This code will throw a `NullPointerException`. – user207421 Mar 23 '16 at 11:51