【问题标题】:How to avoid several calls to a method by saving its returning value?如何通过保存返回值来避免对方法的多次调用?
【发布时间】:2020-08-12 16:52:36
【问题描述】:

我有这个方法

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 DB,根据其所属帐户的标题检索密码。

有很多方法需要 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;
    }

【问题讨论】:

  • 所以你这样做只是为了好玩,对吧?这不是为了公司生产系统的安全吗?因为如今安全性如此复杂,而向 SO 寻求有关如何设置安全系统的建议并不是您想要做的。更好的选择是在线安全会议
  • 其实是一个clientId和clientSecret,我不处理密码,除了我自己的,而且这还没有达到公司生产,个人使用

标签: java keepass


【解决方案1】:

将它们存储在 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 编码或实际加密来混淆缓存的密码,但这超出了所要求的范围。

【讨论】:

  • 不错的方法,加密也将是一个不错的补充,可能对于 clientId 和 clientSecret 来说有点过头了(对不起,我说的是密码),但你永远不能太安全,谢谢你的帮助
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-11-15
  • 2012-04-07
  • 1970-01-01
  • 2017-08-29
  • 1970-01-01
  • 2015-12-16
  • 2021-10-16
相关资源
最近更新 更多