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

zea*_*eal 20 java playframework-2.0

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

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

adi*_*dis 32

我个人会在User模型中做到这一点.我有我的字段的getter,所以在setPassword方法中:

this.password = HashHelper.createPassword(password); 
Run Code Online (Sandbox Code Playgroud)

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

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

org.mindrot" % "jbcrypt" % "0.3m
Run Code Online (Sandbox Code Playgroud)

加密看起来像:

/**
 * 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());
}
Run Code Online (Sandbox Code Playgroud)

解密看起来像:

/**
 * 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);
}
Run Code Online (Sandbox Code Playgroud)

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