Search code examples
javax509certificatejava-11

What is the API for generating self-signed certificates in Java 9-19?


We have a code that generates self-signed certificate running Java 8 (the api has been removed in java 9). It seems like there will be a new API for generating self-signed certificates starting from JDK 9: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8165481

Is there any example of doing the same as:

   class Foo{
     public Foo(){
        CertAndKeyGen keyGen = new CertAndKeyGen("RSA", "SHA256withRSA", null);
        keyGen.generate(2048);
        rootPrivateKey = keyGen.getPrivateKey();
        rootCertificate = keyGen.getSelfCertificate(new X500Name("CN=FooBar"), (long) 24 * 60 * 60);
        CertAndKeyGen subKeyGen =new CertAndKeyGen("RSA","SHA256withRSA",null);
        subKeyGen.generate(2048);
        subPrivateKey = subKeyGen.getPrivateKey();
        subCertificate = subKeyGen.getSelfCertificate(new X500Name("CN=FizzBuzz"), (long) 24 * 60 * 60);

        rootCertificate   = signCertificate(rootCertificate, rootCertificate, rootPrivateKey);
        subCertificate = signCertificate(subCertificate, rootCertificate, rootPrivateKey);

        X509Certificate[] certChain = new X509Certificate[]{subCertificate,rootCertificate};

        KeyStore store = KeyStore.getInstance("PKCS12");
        store.load(null, null);
        store.setKeyEntry("FizzBuzz Private Key", subPrivateKey, certificatePassword.toCharArray(), certChain);
}

    public X509Certificate signCertificate (X509Certificate inputCertificate, X509Certificate issuerCertificate, PrivateKey issuerPrivateKey)throws Exception {
            X509CertInfo info = new X509CertInfo(inputCertificate.getTBSCertificate());
            info.set(X509CertInfo.ISSUER, issuerCertificate.getSubjectDN());
            X509CertImpl outCert = new X509CertImpl(info);
            outCert.sign(issuerPrivateKey, issuerCertificate.getSigAlgName());
            return outCert;
    }
}

in Java 11?

===============Update===========

The feature request is here: https://bugs.java.com/bugdatabase/view_bug.do?bug_id=8058778


Solution

  • You can use utility classes from OkHttp to achieve this

    https://github.com/square/okhttp/tree/master/okhttp-tls

    A HeldCertificate is a certificate and its private key. Use the builder to create a self-signed certificate that a test server can use for HTTPS:

    String localhost = InetAddress.getByName("localhost").getCanonicalHostName();
    HeldCertificate localhostCertificate = new HeldCertificate.Builder()
        .addSubjectAlternativeName(localhost)
        .build();