Java 从字节 [] 生成 X509Certificate?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3389143/
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
Generate X509Certificate from byte[]?
提问by Alex
Is there a possibility to generate an java.security.cert.X509Certificate from an byte[]?
是否有可能从字节 [] 生成 java.security.cert.X509Certificate?
采纳答案by Andrzej Doyle
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的实例创建- 特别是配置为创建 X509 证书的实例。这可以像这样创建:
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。这可以通过将字节数组包装在ByteArrayInputStream 中来实现:
InputStream in = new ByteArrayInputStream(bytes);
X509Certificate cert = (X509Certificate)certFactory.generateCertificate(in);
回答by user6103982
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();
}
回答by hal9000
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));