How to initialize the Keystore
Asked Answered
R

1

7

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);

    }   
Ringnecked answered 31/8, 2014 at 10:50 Comment(0)
T
20

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();
...
Terror answered 5/9, 2014 at 12:23 Comment(2)
I had tried ks.load(null) before and that had not worked, but your answer of ks.load(null, null) works great!Ringnecked
When is it initialized with the default cacerts? Thanks.Simaroubaceous

© 2022 - 2024 — McMap. All rights reserved.