My name is Veera. I'm a full stack web developer. I have founded http://www.timethetask.com and currently working on my next product. Veera is a DZone MVB and is not an employee of DZone and has posted 33 posts at DZone. You can read more from them at their website. View Full User Profile

Storing passwords in Java web application

09.07.2010
| 14412 views |
  • submit to reddit

First of all, you should never store passwords. Then why the heck am I writing this post? Okay, Let me rephrase the first sentence – You should never store passwords as plain text anywhere in your application. of course, for the obvious reasons. If you store passwords as plain text, in a database or in a log file, then even Rajinikanth couldn’t save your application getting **cked.. I mean hacked. (Btw, Rajinikanth is the Chuck Norris of India, if you are not aware of him)

Then what’s the right way to deal with the asterisks? You could use encryption. But if there’s a way to encrypt it, then there should be a way to decrypt it. So, encryption is also vulnerable to hacker’s attack.

Isn’t there a better solution to this? It’s there and it's known as Password Hashing.

How password hashing works?

In hashing, you take a input string (in our case, a password), add a salt to the string, generate the hash value (using SHA-1 algorithm for example), and store the hash value in DB. For matching passwords while login, you do the same hashing process again and match the hash value instead of matching plain passwords and authenticate users.

Hashing is different from encryption. Because, encryption is two way, means that you can always decrypt the encrypted text to get the original text. But Hashing is one way, you can never get the original text from the hash value. Thus it gives more security than encryption.

To generate hash, you can make use of any hashing algorithms out there – MD5, SHA-1, etc. Before generating a hash, adding a salt to the password will give added security. Salt is nothing but a simple text that is known only to you/your application. It can be “zebra” or “I’mGod” or anything you wish.

Below, I’m giving a Java example of how to do password hashing in an login module.

Password hashing example in Java

This is simple example containing two methods – signup() and login(). As their names suggest, signup would store username and password in DB and login would check the credentials entered by user against the DB. Let’s dive into the code.

package com.sandbox;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class PasswordHashingDemo {

	Map<String, String> DB = new HashMap<String, String>();
	public static final String SALT = "my-salt-text";

	public static void main(String args[]) {
		PasswordHashingDemo demo = new PasswordHashingDemo();
		demo.signup("john", "dummy123");

		// login should succeed.
		if (demo.login("john", "dummy123"))
			System.out.println("user login successfull.");

		// login should fail because of wrong password.
		if (demo.login("john", "blahblah"))
			System.out.println("User login successfull.");
		else
			System.out.println("user login failed.");
	}

	public void signup(String username, String password) {
		String saltedPassword = SALT + password;
		String hashedPassword = generateHash(saltedPassword);
		DB.put(username, hashedPassword);
	}

	public Boolean login(String username, String password) {
		Boolean isAuthenticated = false;

		// remember to use the same SALT value use used while storing password
		// for the first time.
		String saltedPassword = SALT + password;
		String hashedPassword = generateHash(saltedPassword);

		String storedPasswordHash = DB.get(username);
		if(hashedPassword.equals(storedPasswordHash)){
			isAuthenticated = true;
		}else{
			isAuthenticated = false;
		}
		return isAuthenticated;
	}

	public static String generateHash(String input) {
		StringBuilder hash = new StringBuilder();

		try {
			MessageDigest sha = MessageDigest.getInstance("SHA-1");
			byte[] hashedBytes = sha.digest(input.getBytes());
			char[] digits = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
					'a', 'b', 'c', 'd', 'e', 'f' };
			for (int idx = 0; idx < hashedBytes.length; ++idx) {
				byte b = hashedBytes[idx];
				hash.append(digits[(b & 0xf0) >> 4]);
				hash.append(digits[b & 0x0f]);
			}
		} catch (NoSuchAlgorithmException e) {
			// handle error here.
		}

		return hash.toString();
	}

}

So, that’s it. I guess the above code is self explanatory. Do let me know in case you have any doubts.

 

From http://veerasundar.com/blog/2010/09/storing-passwords-in-java-web-application/

Published at DZone with permission of Veera Sundar, author and DZone MVB.

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)

Tags:

Comments

Sam Lewis replied on Tue, 2010/09/07 - 8:52am

You could use org.apache.commons.codec.digest.DigestUtils.shaHex() instead of writing your own generateHash() method.

Arnaud Des_vosges replied on Tue, 2010/09/07 - 7:27am

input.getBytes() makes your hash dependant on the default charset.

Use input.getBytes("UTF-8") for example.

Jonathan Fisher replied on Tue, 2010/09/07 - 9:36am

Hashing is no better than plaintext: http://tools.benramsey.com/md5/ You must XOR or concat a random salt to the password before hashing. Store passwords as char[], not Strings. After you are done, use Arrays.fill to immediately erase the memory.

John J. Franey replied on Tue, 2010/09/07 - 1:40pm

jasypt.org contains a relevant tutorial: How to encrypt user passwords

Niel Eyde replied on Tue, 2010/09/07 - 8:16pm

For what it's worth, here's a recent blog post I did on the topic: Using password encryption in Spring MVC login page

Juergen Schumacher replied on Wed, 2010/09/08 - 5:34am

Please see here http://www.mindrot.org/files/jBCrypt/jBCrypt-0.2-doc/BCrypt.html . The BCrypt is a hashing with blowfish cipher. BCrypt provides a hashpw and a checkpw method to handle the hasjing of password. The complexity of hashing is controlled by BCrypt.gensalt() method. Its very easy to handle. Juergen

Nils Kilden-pedersen replied on Wed, 2010/09/08 - 11:58am

The Scuff package for Scala has a Password class to support this.

King Sam replied on Fri, 2012/02/24 - 9:42am

this is an informative article indeed.
Just to add there are still many types of security implementation possible and you have listed many of them & its a design decision to see which one needs to be used.. By any chance do u have plans to post on them?

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.