First of all, you have to create an empty keystore before adding a key inside it, and your code wouldn't work because,
To create an empty keystore using the above load method, pass null as the InputStream argument.
See the following example to see how to pass null as argument.
Creating a Keystore,
public static void createStore(String path, String keyStoreName,
String storePassword) throws KeyStoreException,
NoSuchAlgorithmException, CertificateException, IOException {
KeyStore store = KeyStore.getInstance("BKS");
char[] password = storePassword.toCharArray();
store.load(null, password);
FileOutputStream fos = new FileOutputStream(path + keyStoreName);
store.store(fos, password);
System.out.println("New Store Created !");
fos.close();
}
The above code is copied from my repo, aes-256-java-bks
According to its description, it has all the features which you need,
This simple code allows you to encrypt/decrypt any kind of file using
AES-256 standard. It uses Bouncy Castle Keystore for Key Management.
Beside Encryption, the code allows you to manage your keystore, like
Creating a new Keystore, Loading an existing keystore, adding key to
an existing keystore, generating new Key with user Password, deleting
key from a keystore or displaying keys from given keystore, all these
features could be accessed at runtime, all you need to do is execute
the program.
The following codes are from the same repository as mentioned above,
Loading store,
static KeyStore loadStore() throws KeyStoreException,
FileNotFoundException, IOException, NoSuchAlgorithmException,
CertificateException {
KeyStore store = KeyStore.getInstance("BKS");
InputStream keystoreStream = new FileInputStream(keyStoreLocation);
store.load(keystoreStream, storePassword.toCharArray());
System.out.println("Key Store loaded!\n");
return store;
}
For security reasons, you cannot display actual keys from the keystore, but you sure could get the list of all the aliases of keys from the keystore,
Check this code,
private static void getAliases() throws KeyStoreException,
FileNotFoundException, NoSuchAlgorithmException,
CertificateException, IOException {
if (store.size() == 0)
System.out.println("Store is Empty!");
Enumeration<String> enumeration = store.aliases();
while (enumeration.hasMoreElements()) {
String alias = (String) enumeration.nextElement();
System.out.println("Key Alias: " + alias);
}
}
Deleting a Key from keystore,
public static void deleteAlias(String alias) throws KeyStoreException {
store.deleteEntry(alias);
}
keyStoreNamein theFileInputStream()an existing keystore? Or did you try to create a new keystore using that name?