KeyStore getKey () returns null in Android

I use this code to store a key in a KeyStore in an Android application:

SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
DESKeySpec keySpec = new DESKeySpec(key); // byte[] key
SecretKey skey = kf.generateSecret(keySpec);

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(null, "ksPassword".toCharArray());

PasswordProtection pass = new PasswordProtection(
        "entryPassword".toCharArray());
KeyStore.SecretKeyEntry skEntry = new KeyStore.SecretKeyEntry(skey);
ks.setEntry("keyAlias", skEntry, pass);

FileOutputStream fos = ctx.getApplicationContext().openFileOutput("bs.keystore",
        Context.MODE_PRIVATE);
ks.store(fos, ksPassword);
fos.close();

Then in another method, I use this code to retrieve the stored key

FileInputStream fis = ctx.getApplicationContext().openFileInput("bs.keystore");
KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
ks.load(fis, "ksPassword".toCharArray());
Key k = (SecretKey) ks.getKey(keyAlias, "entryPassword".toCharArray());
fis.close();

but the command ks.getKey("keyAlias", "entryPassword".toCharArray())returns null.

Where am I mistaken?

+4
source share
1 answer

Ok, I finally understood the problem ...

I used the storage method more than the key in the keystore. Using the code ks.load(null, "ksPassword".toCharArray());, the previous key was erased each time (because an empty keystore was loaded), and only the last store was stored in the keystore.

So the correct code is:

KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
try {
FileInputStream fis = ctx.getApplicationContext().openFileInput("bs.keystore");
ks.load(fis, ksPassword);
} catch(FileNotFoundException e) {
    ks.load(null, ksPassword);
}

bs.keystore , catch. , .

+5

All Articles