I'm currently writing a java program which automates my daily work with Android apps. The main Task of the program is to run serveral external tools via the windows command line and it works fine as long as I don't have to interact with the called cmdline tool. I have Problems with creating a keystore using ''keytool''. During the execution of ''keytool'' the commandline prompts me to type in my name, passwords etc. Is it possible to read this information from a file? I don't know if it helps, but this is the class which handles the execution of my commands.
private static void executeCmd(String command, PrintStream output) throws IOException, InterruptedException {
final Runtime r = Runtime.getRuntime();
final Process p = r.exec(command);
java.util.List<StreamWriter> reader = Arrays.asList(
new StreamWriter(p.getInputStream(), output).startAndGet(),
new StreamWriter(p.getErrorStream(), output).startAndGet()
);
if (output != null)
output.println("waiting for: " + command);
p.waitFor();
reader.forEach(StreamWriter::joinSilent);
if (output != null)
output.println("waiting done");
}
2 Answers 2
check keytool -help. you can pass alias name and password in keytool arguments itself. for example
keytool -list -alias TEST -keystore "C:\java\jdk\jre\lib\security\cacerts" -storepass changeit
Check the link from oracle for more examples
Comments
You may prepare input file for the command and pass it to the standard input. It could be done using ProcessBuilder instead of Runtime.exec:
final Process process = new ProcessBuilder(command)
.redirectInput(new File(standardInputFileName))
.start();
But, actually, you don't need input redirection to use keytool. You may pass all required information as command-line arguments. For example, here is the command line that generates a new RSA key (spitted in lines for clarity):
keytool -genkeypair
-keystore "<key store file>"
-alias "<key alias>"
-keyalg "RSA"
-keypass "<key password>"
-storepass "<store password>"
-dname "<distingushed name>"
Where distinguished name has a form (again, splitted in lines for clarity)
CN=<common name>,
OU=<orgamization unit>,
O=<organization>,
L=<location>,
ST=<state>,
C=<two-letter country code>
Working example that generates a new key without user interaction:
keytool -genkeypair -keystore my.store -alias my.key -keyalg RSA -storepass storage-pass -keypass key-pass -dname "CN=Nobody, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=US"
More information is available on keytool documentation page.
p.getOuputStream()pipe.