我有这个方法
public String getCredentials(String entry) throws IOException {
KeePassFile database = KeePassDatabase
.getInstance(config.getProperty("keyPassDataBasePath"))
.openDatabase(new File(config.getProperty("keyPassKeyPath")));
Entry sampleEntry = database.getEntryByTitle(entry);
return sampleEntry.getPassword();
}
它基本上是去一个KeePass数据库,根据其所属帐户的标题检索密码。
有很多方法需要2个密码,所以使用了2个条目。我不想每次都调用那个方法,因为我认为这是浪费资源。如何保存返回的值,并在方法需要这些值的其他类中使用它?
这行得通吗?我觉得它无论如何都会让方法调用几次
private static String pwd1;
private static String pwd2;
public void setValues() throws IOException {
pwd1 = getCredentials("accountName1");
pwd2 = getCredentials("accountName2");
}
public String getPwd1(){
return pwd1;
}
public String getPwd2(){
return pwd2;
}
将它们存储在HasMap中,密钥为条目,密码为值:
class CachedCredentials {
private Map<String, String> storedPasswords = new HashMap<>();
private Properties config;
public CachedCredentials(Properties config) {
this.config = config;
}
public String getCredentials(String entry) {
if (!storedPasswords.containsKey(entry)) {
KeePassFile database = KeePassDatabase
.getInstance(config.getProperty("keyPassDataBasePath"))
.openDatabase(new File(config.getProperty("keyPassKeyPath")));
Entry sampleEntry = database.getEntryByTitle(entry);
storedPasswords.put(entry, sampleEntry.getPassword());
}
return storedPasswords.get(entry);
}
然后在您的setValues方法中,您可以执行以下操作:
private cachedCreds; //initialize this in your constructor
public void setValues() throws IOException {
pwd1 = cachedCreds.getCredentials("accountName1");
pwd2 = cachedCreds.getCredentials("accountName2");
}
如果有人在程序运行时进行内存窥探,则此解决方案可能不安全。可能想办法通过base64编码或实际加密来混淆缓存的密码,但这超出了要求。