KeyStore getKey() returning null in Android

你说的曾经没有我的故事 提交于 2019-12-22 08:14:19

问题


I'm using this code to store a key into a KeyStore in an Android App:

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 key I stored,

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 instruction ks.getKey("keyAlias", "entryPassword".toCharArray()) returns null.

Where am I wrong?


回答1:


Ok, I finally understood the problem...

I used the method to store more than a key in the keystore. Using the code ks.load(null, "ksPassword".toCharArray()); the previous key was erased each time (because loading an empty keystore) and only the last one was stored on 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);
}

The first time that the method is executed the file bs.keystore does not exist, so the code in the catch block is executed. Instead in the next calls the file exists and the new key is added to the keystore.



来源:https://stackoverflow.com/questions/26239474/keystore-getkey-returning-null-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!