I am trying to import a X509 certificate programatically in my client GUI, using the method such as described in this answer Import Certificate Programatically. My code looks like:
char[] password = "changeit".toCharArray();
File file = fc.getSelectedFile();
char SEP = File.separatorChar;
File dir = new File (System.getProperty("java.home") + SEP + "lib" + SEP + "security");
File keystoreFile = new File(dir, "cacerts");
KeyStore trustStore = KeyStore.getInstance(KeyStore.getDefaultType());
InputStream targetStream = new FileInputStream(file);
CertificateFactory cf = CertificateFactory.getInstance("X509");
X509Certificate c = (X509Certificate) cf.generateCertificate(targetStream);
FileInputStream in = new FileInputStream(keystoreFile);
trustStore.load(in, password);
in.close();
trustStore.setCertificateEntry("alias", c);
FileOutputStream out = new FileOutputStream(keystoreFile);
trustStore.store(out, password);
out.close();
But when I run the program and try to import it I get an exception like:
java.io.FileNotFoundException: C:\Program Files\Java\jre1.8.0_51\lib\security\cacerts (Access is denied)
I know the password "changeit" is the default password and it is the right one because I cross checked it using the commandline keytool.
Is there something I am missing here? Thanks in advance!
Solution:
Thanks to the link in Manuel's reply I found the solution for this. Obviously the Java folder in Program Files did not have the right permissions for the OS user (to write). I want to know if this is by default, even in the case of Linux OS? Is there a work around it without changing the permissions manually?