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

a 夏天 提交于 2020-05-25 01:11:34

问题


I have a program in Java which currently uses private JDK classes (CertAndKeyGen and X500Name) to generate self-signed X.509 certificates. There are too many problems with this approach:

  • the internal package(s) keep changing:
    • "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 a JDK 7 update (u111?) recently changed the package listed above
  • Java 9 will hide these classes

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

I have looked at using the ill-named CertificateFactory.generateCertificate() methods, but no luck: they cannot generate any certificate, they are just able to load an existing one.

 

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

 

This is as far as I could go:

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 introduce a dependency on bouncy-castle if at all possible
    • I already know of X509V3CertificateGenerator
  • We do not want either to invoke keytool via a ProcessBuilder :)

回答1:


Ok, then I guess it does not exist.

The RFE I submitted to the JDK has been accepted and there is now an official bug for it: http://bugs.java.com/bugdatabase/view_bug.do?bug_id=JDK-8165481



来源:https://stackoverflow.com/questions/39143858/how-to-generate-a-self-signed-certificate-using-only-jdk-supported-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!