如何使用Java创建X509证书?

我想使用Java语言创建X509证书,然后从中提取公钥。

我搜索了互联网,发现了许多代码示例,但是所有代码都有错误(未知变量或未知类型)或者有很多警告,例如:“方法……来自类型……已被弃用”等。

例如,为什么以下代码不起作用:

PublicKey pk; CertificateFactory cf = CertificateFactory.getInstance("X.509"); String PKstr = pk.toString(); InputStream PKstream = new ByteArrayInputStream(PKstr.getBytes()); X509Certificate pkcert = (X509Certificate)cf.generateCertificate(PKstream); 

谁能告诉我如何使用纯Java或Bouncy Castle创建证书,然后从中获取公钥?

谢谢大家。

您还可以仅使用JDK类生成证书。 缺点是您必须使用sun.security.x509包中的两个类。 代码是:

 KeyStore keyStore = ... // your keystore // generate the certificate // first parameter = Algorithm // second parameter = signrature algorithm // third parameter = the provider to use to generate the keys (may be null or // use the constructor without provider) CertAndKeyGen certGen = new CertAndKeyGen("RSA", "SHA256WithRSA", null); // generate it with 2048 bits certGen.generate(2048); // prepare the validity of the certificate long validSecs = (long) 365 * 24 * 60 * 60; // valid for one year // add the certificate information, currently only valid for one year. X509Certificate cert = certGen.getSelfCertificate( // enter your details according to your application new X500Name("CN=My Application,O=My Organisation,L=My City,C=DE"), validSecs); // set the certificate and the key in the keystore keyStore.setKeyEntry(certAlias, certGen.getPrivateKey(), null, new X509Certificate[] { cert }); 

从密钥库中检索私钥以加密或解密数据。 基于代码来自http://www.pixelstech.net/article/1408524957-Generate-cetrificate-in-Java—-3

是的,使用BouncyCastle, 在这里完成从2个公钥(证书的密钥和CA的密钥)创建X509证书。

我在这里将生成的证书转换为PEM。