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
Personally I would do it in the User
model. I have getters for my fields, so in setPassword
method:
this.password = HashHelper.createPassword(password);
The Hashhelper
is just an singleton class for multi purposes hashing stuff.
And in Hashelper I use BCrypt, just add following to Build.scala
org.mindrot" % "jbcrypt" % "0.3m
And the crypting looks like:
/**
* 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());
}
And decrypting looks like:
/**
* 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.