0
是否可以使用Java密钥库存储密码,特别是对于WebServices等? 我发现了有关存储SSL密钥的在线信息,但这对我的需求来说太过于扼杀了。用于密码的Java密钥库
是否可以使用Java密钥库存储密码,特别是对于WebServices等? 我发现了有关存储SSL密钥的在线信息,但这对我的需求来说太过于扼杀了。用于密码的Java密钥库
是的,根据密钥存储的类型,您可以在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块。否则,目标违规中使用的内存刮取器更有可能抓取密钥。
任何教程链接或示例代码片段? –
@DaSh我添加了一些代码来展示如何使用条目。希望您已经理解如何加载和保存密钥存储区,并安全地提示输入主密码并对字符数组中的其他密码进行编码/解码。包含的代码对于这种格式已经很难处理。 – erickson