如何使用Java创建X509证书?

ley*_*ami 12 java certificate x509certificate public-key

我想使用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);
Run Code Online (Sandbox Code Playgroud)


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

谢谢大家.

iwa*_*n.z 26

您还可以仅使用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 });
Run Code Online (Sandbox Code Playgroud)

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

  • 不幸的是,这不再适用于 Java 17:无法访问类 sun.security.tools.keytool.CertAndKeyGen (在模块 java.base 中),因为模块 java.base 不会将 sun.security.tools.keytool 导出到未命名模块 @0x1a5b6f42 (2认同)

Pie*_*ier 5

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

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