在 Java 中将证书字节 [] 转换为 X509Certificate
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11515725/
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
Converting certificate byte[] to X509Certificate in Java
提问by Mike O
I've stored a certificate as a Base64 encoded string in the database. I can read this from the the database and decode it but I'd like to convert the decoded byte[] into a X509Certificate. I am looking for sample code to do this. I have tried:
我已将证书作为 Base64 编码字符串存储在数据库中。我可以从数据库中读取它并对其进行解码,但我想将解码后的 byte[] 转换为 X509Certificate。我正在寻找示例代码来执行此操作。我努力了:
CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
InputStream in = new ByteArrayInputStream(bytes);
X509Certificate cert = (X509Certificate)certFactory.generateCertificate(in);
This leads to an issue with the encoding type. A valid sample String or byte[] that represents a certificate will be good.
这会导致编码类型出现问题。代表证书的有效示例 String 或 byte[] 会很好。
Any pointers will be great! Thanks.
任何指针都会很棒!谢谢。
回答by martijno
Your sample code looks fine. You can generate that byte[]
yourself using openssl:
您的示例代码看起来不错。您可以byte[]
使用 openssl 自己生成:
openssl genrsa -out privkey.pem
openssl req -new -x509 -key privkey.pem -outform DER -out cert.der