Ответ 1
Лично я бы сделал это в модели User
. У меня есть получатели для моих полей, поэтому в методе 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);
}
Мне нравится держать мои контроллеры настолько простыми, насколько это возможно, поскольку я вижу мои контроллеры так же, как контроллеры трафика между действием пользователя и бизнес-моделью (внутри моих моделей!).