java 将 x509Certificate 转换为 byte[] 并反转
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28064384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert x509Certificate into byte[] and reverse
提问by luca
I would to convert X509Certificate into byte[] or String and after obtain an X509Certificate from byte. I have used this code
我会将 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);
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
但是当我分析返回的 x509 时,这与原始证书不同。你认为有错误吗?提前致谢
回答by Bheeman
Use X509Certificate.getEncoded()
利用 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.
getEncoded()返回此证书的编码形式。假设每种证书类型只有一种编码形式;例如,X.509 证书将被编码为 ASN.1 DER。
回答by luca
With String i have resolved my problem, particularly i have used this code: To convert into String my x509Certificate
使用 String 我解决了我的问题,特别是我使用了这个代码: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:
将此字符串转换为 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();