将x509Certificate转换为byte []并反转

时间:2015-01-21 10:05:45

标签: java string certificate bytearray x509certificate

我希望将X509Certificate转换为byte []或String,然后从byte获取X509Certificate。 我使用过这段代码

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);

并通过此方法恢复:

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);

但是当我分析返回的x509时,这与原始证书不同。你认为有错误吗? 提前谢谢

2 个答案:

答案 0 :(得分:1)

使用String我已经解决了我的问题,特别是我使用了这段代码: 要转换为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;

将此字符串转换为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();

答案 1 :(得分:1)

使用X509Certificate.getEncoded()

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

getEncoded()返回此证书的编码形式。假设每种证书类型只有一种形式的编码;例如,X.509证书将编码为ASN.1 DER。