How to create a self-signed certificate using only supported JDK classes?

I have a Java program that currently uses private JDK classes ( CertAndKeyGenand X500Name) to create self-signed X.509 certificates. There are too many problems with this approach:

  • inner package continues to change:
    • "sun.security.x509.CertAndKeyGen", // Oracle / Sun / OpenJDK 6.7
    • "sun.security.tools.keytool.CertAndKeyGen", // Oracle / Sun / OpenJDK 8
    • "com.ibm.security.x509.CertAndKeyGen", // IBM SDK 7
    • "com.ibm.security.tools.CertAndKeyGen" // IBM SDK 8
    • Apparently, the JDK 7 update (u111?) Recently changed the package mentioned above.
  • Java 9 will hide these classes

I would like to convert this code to use the standard supported JDK classes.

I looked at using the brutally named methods CertificateFactory.generateCertificate(), but no luck: they cannot generate any certificate, they just can load the existing one.

 

Does anyone know a standard JDK API that can generate a self-signed certificate?

 

This is as far as I could:

KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
generator.initialize(2048, SecureRandom.getInstance("SHA1WithRSA"));
KeyPair keyPair = generator.generateKeyPair();
PrivateKey privatekey = keyPair.getPrivate();

X500Principal principal = new X500Principal(dn);

CertificateFactory certFactory = CertificateFactory.getInstance("X.509");
// How to generate the self-signed certificate from there?
// certFactory.generate(inputStream) // only able to load an existing certificate

 

Note:

  • We do not want to add dependency on bouncy-castle, if at all possible
    • I already know X509V3CertificateGenerator
  • We do not want to either call keytoolthrough ProcessBuilder:)
+4
source share
1 answer

OK, then I think this does not exist.

The RFE introduced in the JDK has been accepted, and now there is an official error: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8165481

0
source

Source: https://habr.com/ru/post/1652450/


All Articles