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

Deplake picture Deplake · Feb 28, 2013 · Viewed 10.3k times · Source

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:

enter image description here

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?

Answer

Deplake picture Deplake · Mar 1, 2013

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.