Search code examples
javasecuritycertificatex509certificatedigital-certificate

Signing a X509Certificate with another Self Signed x509Certificate [acting as CA]


I have created a self-signed certificate and encoded it successfully. But I want to sign this certificate with another self signed certificate, which will act as a Certification Authority.

The code is below:

X509Certificate caCert;
KeyStore keyStore = KeyStore.getInstance("PKCS12");
keyStore.load(null, null);
CertAndKeyGen keypair = new CertAndKeyGen("RSA", "SHA1WithRSA", null);
X500Name x500Name = new X500Name(commonName, organizationalUnit, organization, city, state, country);
keypair.generate(keysize);
PrivateKey privKey = keypair.getPrivateKey();

X509Certificate[] chain = new X509Certificate[1];

chain[0] = keypair.getSelfCertificate(x500Name, new Date(), (long) validity * 24 * 60 * 60);
keypair.getCertRequest(x500Name);

keyStore.setKeyEntry(alias, privKey, keyPass, chain);

keyStore.store(new FileOutputStream("test.keystore"), keyPass);
caCert = (X509Certificate) keyStore.getCertificate(alias);
File crtFile = new File("saif.der");
writeCertificate(new FileOutputStream(crtFile), caCert);

Solution

  • Create the user certificate using X509V3CertificateGenerator class of bouncycastle. Then finally use the X509V3CertificateGenerator.generateX509Certificate(privateKey) method to generate the X509Certificate. Here the privateKey will be the self signed certificate's private key from PKCS12. Save the user certificate in PKCS12 format.