Question

I'd like to create a self-signed certificate by invoking keytool in my java script. Here is a simplified version of my code which includes the problem I have:

    public class Tester {
        public static void main(String[] args) {   
            String[] cmd = {   
                "/bin/sh",  
                "-c",  
                "keytool",  
                "-genkey",   
                "-dname",  
                "\"C=US,CN=CU,L=ABC,O=ABC_Univ,OU=ABC_Pro\"",  
                "-keysize",  
                "1024",  
                "-alias",  
                "testkeypairs",
                "-keyalg",  
                "RSA",  
                "-sigalg",   
                "SHA1withRSA",  
                "-keystore",     
                "testkeystore",  
                "-storepass",  
                "abcdef",  
                "-keypass",  
                "abcdef"  
            }    
            Process testProc = Runtime.getRuntime().exec(cmd);  
}  

There is no error when I ran it. But it did not give me the keystore. My questions are:

  1. The certificate generated by keytool is not considered as the "subprocess's output" which needs to be fed to the parent process using getinputstream(), is it?

  2. If it is, I also tried the getinputstream() thing as discussed in the following post,

Keytool usage with Runtime.getRuntime().exec() under Linux

the program just got stuck and seems to never stop.

  1. Is there any other ways to create self-signed certificate using java program?

I am a newbie in Java and English is not my first language. I hope I have expressed my question clearly.

Was it helpful?

Solution

You could try a different approach again - since keytool is written in Java and it is delivered with the JDK, you can actually instantiate the keytool class directly, like in this answer. This approach will let you generate a self-signed certificate in the JKS file of your choice, but it won't give you programmatic access to the generated certificate.

Just watch out, under Java 7 you will need to do new sun.security.tools.KeyTool(), but under Java 8 the class has been moved and you will need to do new sun.security.tools.keytool.Main. And of course it only works for the Oracle JDK, the APIs are internal and not guaranteed to be present in any future Java version, etc., etc.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top