Play Framework 2存储用户密码哈希的最佳方法

时间:2013-03-27 10:51:01

标签: java playframework-2.0

我的应用中有一个添加用户选项。我想将哈希格式的用户传递存储在数据库中。密码以纯文本格式存储在框架附带的示例代码中。 经过一些搜索,我发现在play2中实现了一个可用于保护密码的Crypto.encryptAES()函数。

我的问题是什么是最好的使用场所?以及如何使用它来创建最易维护的代码?

2 个答案:

答案 0 :(得分:32)

我个人会在User模型中这样做。我有我的字段的getter,所以在setPassword方法:

this.password = HashHelper.createPassword(password); 

Hashhelper只是一个单例类,用于多种用途哈希的东西。

在Hashelper中我使用BCrypt,只需将以下内容添加到Build.scala

org.mindrot" % "jbcrypt" % "0.3m

加密看起来像:

/**
 * Create an encrypted password from a clear string.
 * 
 * @param clearString
 *            the clear string
 * @return an encrypted password of the clear string
 * @throws AppException
 *             APP Exception, from NoSuchAlgorithmException
 */
public static String createPassword(String clearString) throws AppException {
    if (clearString == null) {
        throw new AppException("empty.password");
    }
    return BCrypt.hashpw(clearString, BCrypt.gensalt());
}

解密看起来像:

/**
 * Method to check if entered user password is the same as the one that is
 * stored (encrypted) in the database.
 * 
 * @param candidate
 *            the clear text
 * @param encryptedPassword
 *            the encrypted password string to check.
 * @return true if the candidate matches, false otherwise.
 */
public static boolean checkPassword(String candidate, String encryptedPassword) {
    if (candidate == null) {
        return false;
    }
    if (encryptedPassword == null) {
        return false;
    }
    return BCrypt.checkpw(candidate, encryptedPassword);
}

我喜欢让我的控制器尽可能简单,因为我看到我的控制器就像用户操作和业务模型(我的模型内部)之间的流量控制器一样。

答案 1 :(得分:4)

我在网上找到了一个更简单的解决方案: http://rny.io/playframework/bcrypt/2013/10/22/better-password-hashing-in-play-2.html

首先在this adress下载jbcrypt-xxx.jar。

在build.sbt的libraryDependencies中,添加:

"org.mindrot" % "jbcrypt" % "0.3m"

这是创建新用户的功能(位于模型类User中):

  public static User create(String userName, String password) {
    User user = new User();
    user.userName = userName;
    user.passwordHash = BCrypt.hashpw(password, BCrypt.gensalt());
    user.save();
    return user;
  }

而且,仍然在User类中,要进行身份验证的功能:

public static User authenticate(String userName, String password) {
    User user = User.find.where().eq("userName", userName).findUnique();
    if (user != null && BCrypt.checkpw(password, user.passwordHash)) {
      return user;
    } else {
      return null;
    }

它有效!