2014-10-07 39 views
4

返回null我使用這個代碼來存儲密鑰插入在Android應用程序的密鑰庫中:密鑰庫信息getKey()在Android的

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())返回null。

我在哪裏錯了?

+0

PasswordProtection是什麼意思?它不是一個android類。 – Alboz 2014-10-07 19:07:31

+0

它是java.security.KeyStore.PasswordProtection。它實現了java.security.KeyStore.ProtectionParameter接口。 – 2014-10-08 07:30:55

回答

5

好吧,我終於明白了這個問題...

我用什麼方法來存儲比密鑰庫中的一個關鍵更多。使用代碼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不存在,因此執行在捕獲塊的代碼。相反,在接下來的調用中存在該文件,並將新密鑰添加到密鑰庫。

相關問題