Skip to content

Encrypting Passwords

Jim Brucker edited this page Apr 29, 2015 · 3 revisions

Storing Passwords

If you store passwords as plain text in a database table, like this:

username password usertype
harry secret 1
admin admin123 0
guest kyakusan 2

then anyone who (covertly) gets your database (or a back-up) has everyone's password. A better idea is to hash or encrypt the passwords before storing them. Several teams did this.

Team Manat uses the jBCrypt library for this. jBCrypt uses Bruce Schneier's Blowfish hashing algorithm. Here is partial code from their User class:

package models;
import org.mindrot.jbcrypt.BCrypt;
...
@Entity
public class User extends Model {
    /** Create a new user and save to database.
     *  @return User object for this user or null if cannot create.
     */
    public static User create(String username, String password, int type){
        if ( User.find.where().eq("username", username).findUnique() != null) {
           // user already exists
           return null;
        }
        User newUser = new User();
        newUser.username = username;
        newUser.password = BCrypt.hashpw(password, BCrypt.gensalt());
        newUser.idtype = type;
        newUser.save();
        return newUser;
    }

They use BCrypt.hashpw to encrypt the user's password before persisting it. When the user logs in, the application calls this method:

    /**
     * Authenticate a user by username and password.
     * @return User that matches parameters or null if no match.
     */
    public static User authenticate(String username, String passwd) {
        User user = User.find.where().eq("username", username).findUnique();
        if (user == null) return null;
        if ( BCrypt.checkpw(passwd, user.password) ) return user;
        return null;
    }

If someone steals Team Manat's database, they would have to crack passwords by brute force. The Blowfish algorithm is designed to be slow, making it harder to crack in this way.

Resource

There are several libraries that provide encryption (hashing) including jBCrypt and Spring Framework's crypto library.

To use jBCrypt, add this to your application build.sbt file:

libraryDependencies +=  "org.mindrot" % "jbcrypt" % "0.3m"

(jBcrypt 0.4 is available on the http://mindrot.org but not in public repositories yet.)

Intro to Play Framework

ExceedVoting - assignment for 16-23 April.

Clone this wiki locally