Sharifah
Sharifah

Reputation: 361

How to convert byte[] type to Certificate type in java?

I've a byte[] of certificate data and I want to change this byte[] type to Certificate type. How can I achieve this?

Now I used CertificateFactory.generateCertificate(InputStream inStream).

byte[] csr = getCSR(cn, ou, org, loc, state, country,email);
CertificateFactory  cf = CertificateFactory.getInstance("X.509");
ByteArrayInputStream bais = new ByteArrayInputStream(csr);
Certificate certificate = cf.generateCertificate(bais);

But Error occurred Certificate certificate = cf.generateCertificate(bais); at this line.

Error : java.security.cert.CertificateParsingException: java.io.IOException: ObjectIdentifier() -- data isn't an object ID (tag = 49)

Why this error occurred? What wrong in this code? Please explain me. Thanks.

Upvotes: 4

Views: 9732

Answers (2)

Pau Kiat Wee
Pau Kiat Wee

Reputation: 9505

You can use CertificateFactory.generateCertificate(InputStream inStream) to generate a Certificate.

Here is an example which generates an X509 Certificate:

CertificateFactory cf   = CertificateFactory.getInstance("X.509");
Certificate certificate = cf.generateCertificate(new ByteArrayInputStream(buf));

Upvotes: 8

RPorazil
RPorazil

Reputation: 91

I have the same error when I try to use CertificateFactory.generateCertificate on CSR. So I think your problem could be the same; i.e. your byte array does not contain certificate, but certificate signing request. If you really need to read certificate signing request (as I do), use the following code (inspired by http://www.journaldev.com/223/generating-a-certificate-signing-request-using-java-api):

import sun.security.pkcs.PKCS10;
...
PKCS10 csr = new PKCS10(Base64Utils.decode(csrPem1.getBytes()));

Using Base64Utils depends on the format of input data.

Upvotes: 2

Related Questions