DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • How to Automatically Detect Multiple Cybersecurity Threats from an Input Text String in Java
  • Build an AI Chatroom With ChatGPT and ZK by Asking It How!
  • How To Build a Google Photos Clone - Part 1
  • Why "Polyglot Programming" or "Do It Yourself Programming Languages" or "Language Oriented Programming" sucks?

Trending

  • Cloud Security and Privacy: Best Practices to Mitigate the Risks
  • Debugging With Confidence in the Age of Observability-First Systems
  • Spring and PersistenceContextType.EXTENDED
  • Docker Model Runner: Streamlining AI Deployment for Developers
  1. DZone
  2. Coding
  3. Java
  4. Storing passwords in Java web application

Storing passwords in Java web application

By 
Veera Sundar user avatar
Veera Sundar
·
Sep. 07, 10 · Interview
Likes (3)
Comment
Save
Tweet
Share
81.4K Views

Join the DZone community and get the full member experience.

Join For Free

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/

Web application Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • How to Automatically Detect Multiple Cybersecurity Threats from an Input Text String in Java
  • Build an AI Chatroom With ChatGPT and ZK by Asking It How!
  • How To Build a Google Photos Clone - Part 1
  • Why "Polyglot Programming" or "Do It Yourself Programming Languages" or "Language Oriented Programming" sucks?

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!