luca
luca

Reputation: 3328

Convert x509Certificate into byte[] and reverse

I would to convert X509Certificate into byte[] or String and after obtain an X509Certificate from byte. I have used this code

X509Certificate x509cert=Helper.saveCertificate(workgroupId, serialNumber);


//x509 to byte[]
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutput out = new ObjectOutputStream(bos);   
out.writeObject(x509cert);
CertificateSerialization certificateSerialization=new CertificateSerialization();
certificateSerialization.setCertificateByte(bos.toByteArray()); 
bos.close();
return handleResult(certificateSerialization);

and recover it by this method:

byte[] x509cert=certificateSerialization.getCertificateByte();

//from byte to x509
ByteArrayInputStream bis = new ByteArrayInputStream(x509cert);
ObjectInput in = new ObjectInputStream(bis);
X509Certificate cert = (X509Certificate) in.readObject(); 
bis.close();
response.setResult(cert);

but when i analyze the returned x509 this is differente from the original certificate. You think there are error? thanks in advance

Upvotes: 6

Views: 21045

Answers (2)

Bheeman
Bheeman

Reputation: 209

Use X509Certificate.getEncoded()

byte[] java.security.cert.Certificate.getEncoded() throws CertificateEncodingException

getEncoded() returns the encoded form of this certificate. It is assumed that each certificate type would have only a single form of encoding; for example, X.509 certificates would be encoded as ASN.1 DER.

Upvotes: 7

luca
luca

Reputation: 3328

With String i have resolved my problem, particularly i have used this code: To convert into String my x509Certificate

Base64 encoder = new Base64(64);
String cert_begin = "-----BEGIN CERTIFICATE-----\n";
String end_cert = "-----END CERTIFICATE-----";      
byte[] derCert = x509cert.getEncoded();
String pemCertPre = new String(encoder.encode(derCert));
String pemCert = cert_begin + pemCertPre + end_cert;
return pemCert;

While to convert this string into x509:

Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
String pem=//PEM STRING
X509Certificate cert = null;
StringReader reader = new StringReader(pem);
PEMReader pr = new PEMReader(reader);
cert = (X509Certificate)pr.readObject();
pr.close();

Upvotes: 10

Related Questions