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

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

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

我个人会在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); } 

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

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

首先在这个地址下载jbcrypt-xxx.jar。

在build.sbt中的libraryDependencies中,添加:

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

这是创建新用户的function(位于模型类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类中,要进行身份validation的function:

 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; } 

它的工作原理!