Password hashing in Java

I was recently asked to provide db based user authentication for a relatively application, which user primarily ldap user authentication. This nearly backdoor-looking feature is only for a handful of users which made it ideal for experimentation. I could have stored user passwords as plain-text and nobody else would ever know, but the one person that would know matters the most, me.

Almost every application uses passwords for user autentization. Although in complex environment, you don't usually want users to have different password for every application, there are situations that needs different approach. And in those times, security shouldn't be taken lightly. Whether you are writing small intranet application, or full scale internet application, you should always protect your user's accounts, because a lot of studies suggest that majority of users use the same password for everything, so for these users, when one application falls, they all fall. That is the reason why have i decided to do a small research how to protect user passwords the right way.

The most commom way to protect passwords from being misused when stolen is hashing. Hashing algoritms are often supplied with random characters alongside with plain-text passwords, this is called salting. Salted hash is better protected against brute-force attack, because of a higher complexity.

I have considered several approaches and picked one that has suited me the most. I am now using hashing utility jBCrypt. It is a powerfull tool with very simple API and very good security.

jBCrypt's API provides two main methods and one support method. Hashing password is done by hashpw method, it takes plain-text and salt as arguments. Returned hash is always 60 characters long, so storing the hash in database is quite simple as CHAR(60) is enough.
BCrypt.hashpw(password, BCrypt.gensalt());
Method gensalt is adjustable by passing optional int argument for complexity. Accepted values are 4 to 31 (default is 10 and higher number means more complex salt).

The second important method is used for password verification. Method checkpw has two parameters, the first is a plain-text password and the second one is the hash created by previous method. Returned value is true, if the password matches the hash or false in other cases.
BCrypt.checkpw(candidate, hashed);
I really like this implementation of BCrypt, as it is only one java class, which makes it easy to incorporate it into any project.


Post a Comment

Popular posts from this blog

Automatic jsp recompile on Jboss AS 7

Running scripts written in Clojure as an executable using Inlein