我使用此代码将密钥存储到 Android 应用程序的 KeyStore 中:
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();
然后,在另一种方法中,我使用此代码来检索我存储的密钥,
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())
返回空值。
我哪里错了?
好吧,我终于明白问题所在了……
我使用该方法在密钥库中存储了多个密钥。使用代码ks.load(null, "ksPassword".toCharArray());
每次都会删除前一个密钥(因为加载空密钥库),并且只有最后一个密钥存储在密钥库中。
所以正确的代码是:
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块被执行。相反,在接下来的调用中,文件存在并且新密钥被添加到密钥库中。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)