nico.ruti
nico.ruti

Reputation: 625

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

I'd like to call the java keytool during runtime execution providing dynamic arguments. Here's what is working under Windows, but not under Linux (Ubuntu) same Java 1.6.0:

File f = new File("mykey.jks");
StringBuilder command = new StringBuilder();
command.append(System.getProperty("java.home")
            + System.getProperty("file.separator") + "bin"
            + System.getProperty("file.separator") + "keytool");
command.append(" -genkey");
command.append(" -dname \"cn=foo,ou=bar,o=company,c=CH\"");
command.append(" -alias myProduct");
command.append(" -keypass " + "testtest");
command.append(" -keystore " + f.getAbsolutePath());
command.append(" -storepass " + "testtest");
command.append(" -validity " + 3650);
final Process pr = Runtime.getRuntime().exec(command.toString());

BufferedReader input = new BufferedReader(new InputStreamReader(
    pr.getInputStream()));

String line = null;
while ((line = input.readLine()) != null) {
    System.out.println(line);
}

int exitVal = -1;
try {
    exitVal = pr.waitFor();
    System.out.println("Exited with error code " + exitVal);
} catch (InterruptedException e) {
    // handle
}

The Output under Linux is

keytool error: java.io.IOException: Invalid keyword ""CN"

Running the command in the Linux command line (not starting in java), the code works. What am I doing wrong and how would the String[] look like when using

Runtime.getRuntime().exec(String[])

Thanks in advance!

Upvotes: 1

Views: 4137

Answers (1)

jontro
jontro

Reputation: 10628

I recommend using http://docs.oracle.com/javase/6/docs/api/java/lang/Runtime.html#exec(java.lang.String[]) instead

Then you dont have to worry about escaping each argument which you are not doing here

String args [] = {arg1, arg2, "-dname", "dNameArguments"};

Upvotes: 5

Related Questions