问题描述
我正在使用此代码将密钥存储到Android应用中的KeyStore中:
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();
但指令 ks.getKey(keyAlias,entryPassword。 toCharArray())
返回null。
我哪里错了?
推荐答案
好的,我终于理解了这个问题...
Ok, I finally understood the problem...
我使用该方法在密钥库中存储了多个密钥。使用代码 ks.load(null,ksPassword.toCharArray());
每次都擦除上一个键(因为加载一个空的密钥库)而只删除了最后一个密钥存储在密钥库中。
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.
所以正确的代码是:
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 块中的代码。而是在下一次调用中,文件存在,新密钥将添加到密钥库。
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.
这篇关于KeyStore getKey()在Android中返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!