I want to import a p12 file into cacert (Java keystore) with keytool. Manually executing import from the command line in actual operation is time-consuming and unrealistic, so I would like to include it as a process of the running Web application.
Since it was set so that only the administrator can rewrite cacerts, the authority is also given to the user who is running the web application. (The certificate could not be imported unless the command prompt was executed with administrator privileges.)
sample1.java
String JRE_PATH = "C:\\Program Files\\Java\\jre1.8.0_144";
String KEYSTORE_PATH = JRE_PATH + "\\lib\\security\\cacerts"; //cacerts path
String CERTFILE_PATH = "cert.p12"; //p12 file path
String ALIAS = "test"; //alias
String KEYSTORE_PASS = "changeit"; //Keystore password
String PRIVATEKEY_PASS = "root"; //Certificate password
//Command to import certificate
ProcessBuilder importCertPb = new ProcessBuilder( "keytool", "-importkeystore", "-keystore",
"\"" + KEYSTORE_PATH + "\"", "-srckeystore",
CERTFILE_PATH, "-srcstoretype", "PKCS12", "-srcstorepass", PRIVATEKEY_PASS, "-deststorepass",
KEYSTORE_PASS );
//Since it is imported with alias "1", give it an alias
// XXXX:Alias (like a name that uniquely identifies a certificate)
ProcessBuilder changeAliasPb = new ProcessBuilder( "keytool", "-changealias", "-alias", "1", "-destalias", XXXX,
"-keystore", "\"" + KEYSTORE_PATH + "\"", "-keypass", PRIVATEKEY_PASS, "-storepass", KEYSTORE_PASS );
//Command to check if the certificate has been imported
ProcessBuilder checkExistCertPb = new ProcessBuilder( "keytool", "-list", "-alias", XXXXX,
"-keystore", "\"" + KEYSTORE_PATH + "\"", "-storepass", KEYSTORE_PASS );
//External process execution
Process importCertPbSt = importCertPb.start();
//Wait until the process ends
importCertPbSt.waitFor();
java::sample2.java
//Alias: Execute command to get certificate matching XXXX
Process checkExistCertPbSt = checkExistCertPb.start();
checkExistCertPbSt.waitFor();
InputStream in = checkExistCertPbSt.getInputStream();
try {
String line = null;
BufferedReader br = new BufferedReader(new InputStreamReader(in));
while ((line = br.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
File path is not recognized when executing an external command from a Java application
Recommended Posts