I am developing a client-side GUI that accepts self-signed server certificates and adds them to the trust store, just like any browser. The problem is that my client application requests a certificate every time it is launched, in other words, it does not remember that the certificate is already in the trust store. How to implement this? This is how I write trust storage files:
public void WriteTrustStore(String alias, X509Certificate c){ char[] password = "changeit".toCharArray(); char SEP = File.separatorChar; keystoreFile = new File(System.getProperty("java.home") + SEP + "lib" + SEP + "security" + SEP + "cacerts"); try { setTrustStore(trustStore); 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(); } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) { e.printStackTrace(); } }
Then I have another method when I initialize my SSL context and also create dynamic aliases by doing something like:
string alias = getHostname() + "-" + getPortname();
At the end, I have an alias, for example:
"myhost-5001"
And then I call the WriteTrustStore method (alias, certificate).
But in the next run of the program, if I try to find a certificate with this alias, I always get a Null Pointer Exception.
I know that a trust file has a property like:
trustStore.containsAlias(alias)
I tried,
if(trustStore.containsAlias(alias) == false){ WriteTrustStore(alias, (X509Certificate) cert) } else { System.out.Println("Certificate already in trust store!"); }
But still I get a Null-Pointer exception. And also I know that the certificate with the alias myhost-5001 is in the Java trust store, I crossed myself with keytool and portecle.
Thanks for your help!