Play Framework 2存储用户密码哈希的最佳方法 [英] Play Framework 2 best way to store password hash of user

查看:155
本文介绍了Play Framework 2存储用户密码哈希的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've got an add user option in my app. I'd like to store the user pass in hash format in the database. Th password is stored in plain text format in the sample codes included with the framework. After some searching i've found out that there's a Crypto.encryptAES() function implemented in play2 that can be used to secure passwords.

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

My question is what's the best place to use it? And how to use it to create the most maintainable code?

推荐答案

我个人会在中执行此操作用户模型。我有我的字段的getter,所以在 setPassword 方法:

Personally I would do it in the User model. I have getters for my fields, so in setPassword method:

this.password = HashHelper.createPassword(password); 

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

The Hashhelper is just an singleton class for multi purposes hashing stuff.

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

And in Hashelper I use BCrypt, just add following to 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);
}

我喜欢让我的控制器尽可能简单,因为我看到我的控制器只是作为用户操作和业务模型之间的交通控制器(在我的模型中!)。

I love to keep my controllers as simple as possible as I see my controllers just as traffic controllers between the user action and the business model (inside my models!) stuff.

这篇关于Play Framework 2存储用户密码哈希的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆