3

I am trying to genearte a self signed certificate using the following code I have got from internet

  import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.math.BigInteger;
import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.SecureRandom;
import java.security.Security;
import java.security.SignatureException;
import java.security.cert.CertificateEncodingException;
import java.security.cert.X509Certificate;
import java.util.Date;

import javax.security.auth.x500.X500Principal;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openssl.PEMWriter;
import org.bouncycastle.util.io.pem.PemObject;
import org.bouncycastle.x509.X509V1CertificateGenerator;
//import org.bouncycastle.x509.X509V1CertificateGenerator;

import com.google.common.base.Strings;

/**
 * Demo of a generation of a X509 Self Signed Certificate using <a
 * href="http://www.bouncycastle.org/">Bouncy Castle</a> library.
 *
 * @author <a href="mailto:cyrille@cyrilleleclerc.com">Cyrille Le Clerc</a>
 */
public class SelfSignedX509CertificateGeneratorDemo {

    static {
        // adds the Bouncy castle provider to java security
        Security.addProvider(new BouncyCastleProvider());
    }

    /**
     * <p>
     * Generate a self signed X509 certificate .
     * </p>
     * <p>
     * TODO : do the same with
     * {@link org.bouncycastle.cert.X509v1CertificateBuilder} instead of the
     * deprecated {@link org.bouncycastle.x509.X509V1CertificateGenerator}.
     * </p>
     */
    @SuppressWarnings("deprecation")
    static void generateSelfSignedX509Certificate() throws NoSuchAlgorithmException, NoSuchProviderException, CertificateEncodingException,
            SignatureException, InvalidKeyException, IOException {

        // yesterday
        Date validityBeginDate = new Date(System.currentTimeMillis() - 24 * 60 * 60 * 1000);
        // in 2 years
        Date validityEndDate = new Date(System.currentTimeMillis() + 2 * 365 * 24 * 60 * 60 * 1000);

        // GENERATE THE PUBLIC/PRIVATE RSA KEY PAIR
        KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
        keyPairGenerator.initialize(1024, new SecureRandom());

        KeyPair keyPair = keyPairGenerator.generateKeyPair();

        // GENERATE THE X509 CERTIFICATE
        X509V1CertificateGenerator certGen = new X509V1CertificateGenerator();
        X500Principal dnName = new X500Principal("CN=John Doe");

        certGen.setSerialNumber(BigInteger.valueOf(System.currentTimeMillis()));
        certGen.setSubjectDN(dnName);
        certGen.setIssuerDN(dnName); // use the same
        certGen.setNotBefore(validityBeginDate);
        certGen.setNotAfter(validityEndDate);
        certGen.setPublicKey(keyPair.getPublic());
        certGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

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

        // DUMP CERTIFICATE AND KEY PAIR
        System.out.println(Strings.repeat("=", 80));
        System.out.println("CERTIFICATE TO_STRING");
        System.out.println(Strings.repeat("=", 80));
        System.out.println();
        System.out.println(cert);
        System.out.println();

        System.out.println(Strings.repeat("=", 80));
        System.out.println("CERTIFICATE PEM (to store in a cert-johndoe.pem file)");
        System.out.println(Strings.repeat("=", 80));
        System.out.println();





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





        System.out.println(Strings.repeat("=", 80));
        System.out.println("PRIVATE KEY PEM (to store in a priv-johndoe.pem file)");
        System.out.println(Strings.repeat("=", 80));
        System.out.println();
        pemWriter1.writeObject(keyPair.getPrivate());
        pemWriter1.flush();
        System.out.println();
    }

    public static void main(String[] args) {
        try {
            generateSelfSignedX509Certificate();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

but it is throwing an exception while writing the certificate to pem file like this.

Exception in thread "main" java.lang.VerifyError: (class: org/bouncycastle/openssl/PEMWriter, method: writeObject signature: (Ljava/lang/Object;Ljava/lang/String;[CLjava/security/SecureRandom;)V) Incompatible argument to function
    at cryptool.SelfSignedX509CertificateGeneratorDemo.generateSelfSignedX509Certificate(SelfSignedX509CertificateGeneratorDemo.java:106)
    at cryptool.SelfSignedX509CertificateGeneratorDemo.main(SelfSignedX509CertificateGeneratorDemo.java:151)

which when traced is pointing to

pemWriter = new PEMWriter(new PrintWriter(System.out));

in the code. I understood that the problem is with writing the certificate using pem writer(correct me if I am wrong). I referred to and tried using the code from Write x509 certificate into PEM formatted string in java? but with no succees. Any help is appreciated.

Community
  • 1
  • 1
kirankar
  • 39
  • 1
  • 6
  • Try to make sure you use the same bouncy castle library during compile time and run time, and make sure that you use the correct one for your specific target JVM (also both during compile and run time). – Maarten Bodewes Jan 09 '13 at 22:03
  • Could you either delete this question, or add information about the versions of the libraries used? I'll have to vote to close the question otherwise. – Maarten Bodewes Jan 13 '13 at 13:34
  • thanks for your inputs GregS and owlstead . I am using the following bouncy castle version(bcprov-jdk15on-147.jar). I tried with earlier versions too like jdk14 but nothing has changed. – kirankar Jan 15 '13 at 10:45
  • So its an old question but try adding the bcpkix library... it worked for me – Alan Faz Jun 19 '15 at 21:50

0 Answers0