How do I programmatically create a new KeyStore?
I'm trying to programmatically create a new keystore in Java. The following code:
KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
keyStore.setCertificateEntry("alias", cert);
throws a Uninitialized KeyStore exception.
Solution 1:
To create a new KeyStore in Java you first need to create the KeyStore file and then store it using the store(FileOutputStream, char[])
method:
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
char[] password = "some password".toCharArray();
ks.load(null, password);
// Store away the keystore.
FileOutputStream fos = new FileOutputStream("newKeyStoreFileName");
ks.store(fos, password);
fos.close();
I hope this helps, you can see more info here.
Solution 2:
The KeyStore needs to be loaded after it has been created. The load method asks for a FileInputStream to read from but if you supply a null one, an empty KeyStore is loaded.
See this link