How to initialize the Keystore

user3083447 picture user3083447 · Aug 31, 2014 · Viewed 16.5k times · Source

This my code used for usage of key store to save an arbitrary text as a key in the keystore how I am getting the "Keystore is not initialized error", how can I initialise the Keystore?

public void secretKeyGeneration(View view) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException {

    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    byte[]  sek = "eru9tyighw34ilty348934i34uiq34q34ri".getBytes();
    SecretKey sk = new SecretKeySpec(sek, 0, sek.length, "AES");    
    char[] password = "keystorepassword".toCharArray();
    KeyStore.ProtectionParameter protParam = 
    new KeyStore.PasswordProtection(password);

    KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(sk);
    ks.setEntry("secretKeyAlias", skEntry, protParam);

    }   

Answer

Jcs picture Jcs · Sep 5, 2014

Keystores have to be initialized and hence you have to call the Keystore.load(...) method. In your case you can for instance invoke:

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, null);
byte[]  sek = "eru9tyighw34ilty348934i34uiq34q34ri".getBytes();
...