How do I programmatically create a new KeyStore?

Καrτhικ picture Καrτhικ · Mar 15, 2011 · Viewed 76.5k times · Source

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.

Answer

Assaf Gamliel picture Assaf Gamliel · Dec 11, 2012

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.