2014-01-28 116 views

回答

1

是的,根據密鑰存儲的類型,您可以在KeyStore中創建SecretKeyEntry。 SunJCE提供程序實現了一個可容納密鑰條目的「JCEKS」密鑰存儲區。

static byte[] getPassword(KeyStore ks, String alias, char[] master) 
    throws GeneralSecurityException, DestroyFailedException 
{ 
    if (!ks.entryInstanceOf(alias, KeyStore.SecretKeyEntry.class)) 
    throw new IllegalArgumentException(); 
    KeyStore.PasswordProtection pp = new KeyStore.PasswordProtection(master); 
    try { 
    KeyStore.SecretKeyEntry e = (KeyStore.SecretKeyEntry) ks.getEntry(alias, pp); 
    return e.getSecretKey().getEncoded(); 
    } 
    finally { 
    pp.destroy(); 
    } 
} 

static void setPassword(KeyStore ks, String alias, byte[] password, char[] master) 
    throws GeneralSecurityException, DestroyFailedException 
{ 
    SecretKey wrapper = new SecretKeySpec(password, "RAW"); 
    KeyStore.SecretKeyEntry entry = new KeyStore.SecretKeyEntry(wrapper); 
    KeyStore.PasswordProtection pp = new KeyStore.PasswordProtection(master); 
    try { 
    ks.setEntry(alias, entry, pp); 
    } 
    finally { 
    pp.destroy(); 
    } 
} 

你應該儘快小心「零」的密碼,你使用的是他們做的,就像我destroy()PasswordProtection例如在一個try-finally塊。否則,目標違規中使用的內存刮取器更有可能抓取密鑰。

+0

任何教程鏈接或示例代碼片段? –

+0

@DaSh我添加了一些代碼來展示如何使用條目。希望您已經理解如何加載和保存密鑰存儲區,並安全地提示輸入主密碼並對字符數組中的其他密碼進行編碼/解碼。包含的代碼對於這種格式已經很難處理。 – erickson