如何使用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版本<17,您还可以只使用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。

对于JDK>=17,这就是使用BouncyCastle的方法。代码示例在Kotlin中,但在Java中的工作方式完全相同:

val keyPair = KeyPairGenerator.getInstance("RSA").genKeyPair()
val subPubKeyInfo = SubjectPublicKeyInfo.getInstance(keyPair.public.encoded)
val now = Instant.now()
val validFrom = Date.from(now)
val validTo = Date.from(now.plusSeconds(60L * 60 * 24 * 365))
val certBuilder = X509v3CertificateBuilder(
    X500Name("CN=My Application,O=My Organisation,L=My City,C=DE"),
    BigInteger.ONE,
    validFrom,
    validTo,
    X500Name("CN=My Application,O=My Organisation,L=My City,C=DE"),
    subPubKeyInfo
)
val signer = JcaContentSignerBuilder("SHA256WithRSA")
    .setProvider(BouncyCastleProvider())
    .build(keyPair.private)
val certificate = certBuilder.build(signer)

这是你需要拉动的分级依赖性:

implementation("org.bouncycastle:bcpkix-jdk18on:1.72")

最新更新