2014-01-28 226 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