我有我的应用程序的加载用户选择。 我想在散列格式的用户密码存储在数据库中。 个密码被存储在纯文本格式中的示例代码包含在框架。 经过一番搜索我已经发现,有一个在可用于保护密码play2实施Crypto.encryptAES()函数。
我的问题是什么是使用它最好的地方? 以及如何使用它来创建最易于维护的代码?
我有我的应用程序的加载用户选择。 我想在散列格式的用户密码存储在数据库中。 个密码被存储在纯文本格式中的示例代码包含在框架。 经过一番搜索我已经发现,有一个在可用于保护密码play2实施Crypto.encryptAES()函数。
我的问题是什么是使用它最好的地方? 以及如何使用它来创建最易于维护的代码?
我个人会做在User
模式。 我有我的领域干将,所以在setPassword
方法:
this.password = HashHelper.createPassword(password);
该Hashhelper
只是为了多目的散列东西一个单例类。
而在Hashelper我用BCrypt,只需添加以下到Build.scala
org.mindrot" % "jbcrypt" % "0.3m
而crypting的样子:
/**
* 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);
}
我喜欢让我的控制器尽可能简单,因为我看到我的控制器就像用户操作和商业模式的东西(在我的模型!)之间的交通管制。
我发现在这个ADRESS在网络上更简单的解决方案: http://rny.io/playframework/bcrypt/2013/10/22/better-password-hashing-in-play-2.html
首先下载jbcrypt-xxx.jar在此ADRESS 。
在build.sbt的libraryDependencies,添加:
"org.mindrot" % "jbcrypt" % "0.3m"
这是创建一个新用户(位于模型类用户)的功能:
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;
}
而它的工作!