简体   繁体   中英

Create x.509 certificate using bouncycastle with certificate path (cert chain)

Hy Guys! I'm trying to create x.509 certificate using bouncycastle, which should be signed by another certificate and store it PEM base 64 format.

I've already have self-signed certificate (public and private key). Now I want to create new one and sign it with existing self-signed certificate.

KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
keyPairGenerator.initialize(1024, new SecureRandom());
KeyPair keyPair = keyPairGenerator.generateKeyPair();

X509V3CertificateGenerator certGen = new X509V3CertificateGenerator();
X500Principal dnName = new X500Principal("CN=Sergey");
certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
certGen.setSubjectDN(dnName);
certGen.setIssuerDN(caCert.getSubjectX500Principal());
certGen.setNotBefore(validityBeginDate);
certGen.setNotAfter(validityEndDate);
certGen.setPublicKey(keyPair.getPublic());
certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

certGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
certGen.addExtension(X509Extensions.SubjectKeyIdentifier, false, new SubjectKeyIdentifierStructure(keyPair.getPublic()));

X509Certificate cert = certGen.generate(caCertPrivateKey, "BC");

Verification passed without exceptions, which means from my point of view that it was successfully signed by caCert:

cert.verify(caCert.getPublicKey());

Then I decode it to the PEM base 64:

PEMWriter pemWriter = new PEMWriter(new PrintWriter(System.out));
pemWriter.writeObject(cert);
pemWriter.flush();

I get something like this in the output:

-----BEGIN CERTIFICATE-----

MIIDDjCCAnegAwIBAgIBFDAN........

-----END CERTIFICATE-----

When I open it, I see the next:

在此输入图像描述

Why there is no certification chain if it was successfully signed by caCert?

What need to be changed in my code to see certification chain as I expected?

I was able to find solution. Actually code works as expected. I didn't see chain of certificates because my caRoot certificate wasn't added to the trusted store. After I add my sel-signed certificate to the trusted root certified centers I see the whole certification chain as I expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM