Java provides a command line tool to access and operate different keystore which store keys and certificates. This tool is named keytool and is located at \bin.
On command line, you can issue below command to generate a keystore named mytest.jks which contains a private key and certificate chain.
keytool -genkeypair -alias mykey -keyalg RSA -sigalg SHA256withRSA -dname CN=Java -storetype JKS -keypass password -keystore mytest.jks -storepass password
Sometimes, in testing purpose, we may want to issue these command in our applications instead of start a command line terminal. This is doable since keytool itself is just a wrapper to some Java classes which do the actual keystore operations. The keytool will inetrnally invoke sun.security.tools.keytool.Main.main() method.
Hence in Java code, we can directly call this method to run the keytool, for example, to generate a keypair in keystore and list the keystore, we can write following code.
public class KeyToolTest { public static void main(String[] args){ generateKeyPair(); list(); } // List keystore public static void list(){ String command = " -list "+ " -v "+ " -keystore mytest.jks "+ " -storepass password"; execute(command); } // Generate keypair public static void generateKeyPair(){ String command = " -genkeypair "+ " -alias mykey "+ " -keyalg RSA "+ " -sigalg SHA256withRSA "+ " -dname CN=Java "+ " -storetype JKS "+ " -keypass password "+ " -keystore mytest.jks "+ " -storepass password"; execute(command); } // Execute the commands public static void execute(String command){ try{ printCommand(command); sun.security.tools.keytool.Main.main(parse(command)); } catch (Exception ex){ ex.printStackTrace(); } } // Parse command private static String[] parse(String command){ String[] options = command.trim().split("\\s+"); return options; } // Print the command private static void printCommand(String command){ System.out.println(command); } }
The only thing needs to be taken care of is that sun.security.tools.keytool.Main.main() receives a set of options of the command instead of taking a string command. You can issue other commands as well with above logic.
Unfortunately in Java 8
is not API ..