• Java
    • JAXB Tutorial
      • What is JAXB
      • JAXB Marshalling Example
      • JAXB UnMarshalling Example
  • Spring Tutorial
    • Spring Core Tutorial
    • Spring MVC Tutorial
      • Quick Start
        • Flow Diagram
        • Hello World Example
        • Form Handling Example
      • Handler Mapping
        • BeanNameUrlHandlerMapping
        • ControllerClassNameHandlerMapping
        • SimpleUrlHandlerMapping
      • Validation & Exception Handling
        • Validation+Annotations
        • Validation+ResourceBundle
        • @ExceptionHandler
        • @ControllerAdvice
        • Custom Exception Handling
      • Form Tag Library
        • Textbox Example
        • TextArea Example
        • Password Example
        • Dropdown Box Example
        • Checkboxes Example
        • Radiobuttons Example
        • HiddenValue Example
      • Misc
        • Change Config file name
    • Spring Boot Tutorial
  • Hibernate Tutorial
  • REST Tutorial
    • JAX-RS REST @PathParam Example
    • JAX-RS REST @QueryParam Example
    • JAX-RS REST @DefaultValue Example
    • JAX-RS REST @Context Example
    • JAX-RS REST @MatrixParam Example
    • JAX-RS REST @FormParam Example
    • JAX-RS REST @Produces Example
    • JAX-RS REST @Consumes Example
    • JAX-RS REST @Produces both XML and JSON Example
    • JAX-RS REST @Consumes both XML and JSON Example
  • Miscellaneous
    • JSON Parser
      • Read a JSON file
      • Write JSON object to File
      • Read / Write JSON using GSON
      • Java Object to JSON using JAXB
    • CSV Parser
      • Read / Write CSV file
      • Read/Parse/Write CSV File – OpenCSV
      • Export data into a CSV File
      • CsvToBean and BeanToCsv – OpenCSV

JavaInterviewPoint

Java Development Tutorials

Java Salted Password Hashing

December 17, 2018 by javainterviewpoint 3 Comments

Hashing is a cryptographic function which converts any amount of data into a fixed length hash which cannot be reversed. Hashing enables us to validate if the input has changed even a little bit, if changed then the resulting hash will be different. In this article we will learn the technique of Salted Password Hashing.

Hashing is great for protecting the passwords but has a minor flaw due to its deterministic nature. Let’s say if John and Smith uses the same password ‘secret1234’ then the result hashing will be ‘390d4757bf1b75e305984c99cdedfb1e7c201a2d143a53cfbc35075fa5f9a56f390d

4757bf1b75e305984c99cdedfb1e7c201a2d143a53cfbc35075fa5f9a56f’.

If a hacker was able to break the hash using any one of the technique such as dictionary attack, brute-force attack, Lookup Tables, Reverse Lookup Tables or Rainbow Tables  then he can access all the accounts that uses the same hash.

To mitigate the above issue we could Salt the password, a Salt is a fixed-length secure random string which is added to the password before hashing and hence the hash will be different for the same password.

John’s hash would be de0766b1d4eff33680b2a0d6f408ff6471d6898e83cf2a3f4e647fac5b269eed and

Smith’s has would be 0dfaede04a91ee60d9652be9525af86518cc695dd80c06d9066acca9e009c9fb

Despite using the same password the resulting hash differs. Lets understand how to add Salted Password Hashing.

Java Salted Password Hashing

Java Salted Password Hashing

package com.javainterviewpoint;

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

public class HashExample
{
    public static void main(String[] args)
    {

        String password = "secret1234";

        MessageDigest md;
        try
        {
            // Select the message digest for the hash computation -> SHA-256
            md = MessageDigest.getInstance("SHA-256");

            // Generate the random salt
            SecureRandom random = new SecureRandom();
            byte[] salt = new byte[16];
            random.nextBytes(salt);

            // Passing the salt to the digest for the computation
            md.update(salt);

            // Generate the salted hash
            byte[] hashedPassword = md.digest(password.getBytes(StandardCharsets.UTF_8));

            StringBuilder sb = new StringBuilder();
            for (byte b : hashedPassword)
                sb.append(String.format("%02x", b));

            System.out.println(sb);
        } catch (NoSuchAlgorithmException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
  • The MessageDigest class provides the functionality of a message digest algorithm, we will be getting the MessageDigest instance by passing the algorithm to the getInstance() method. The list of the algorithm which can be passed can be found in this link. In our case we are using SHA-256
MessageDigest md = MessageDigest.getInstance("SHA-256");
  • As per OWASP, Salt should be generated using a Cryptographically Secure Pseudo-Random Number Generator (CSPRNG), for Java the CSPRNG  is java.security.SecureRandom. We will be creating a new instance for SecureRandom class and the nextByte() method generates the random salt.
SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);
  • We will be adding the salt to input using the update() method of MessageDigest
md.update(salt);
  • Once we have added the salt we can generate the hashed password using the digest() method.
byte[] hashedPassword = md.digest(password.getBytes(StandardCharsets.UTF_8));

Output :

Run 1:

5f60d113a45fa44055ce2359c51bda57aaf4217281979db824bc2ecb771b736f

Run 2:

ca1cf58110e43860995df6df8e16c62f466f5967b520155e2c93b57f7ac72e8e

So each time we run the code the output will be different hashes.

Points to Remember

While Storing the password

  • Generate a long random salt using SecureRandom
  • Use the Hash function such as SHA256 to hash both Salt and Password together
  • Save both the Salt and the Hash separately in the database.

While Validating the password

  • Retrieve the Salt and Hash from the database
  • Use the same Hash function (SHA256) which is used while generating the hash
  • Generate a new Hash with new password provided and the Salt retrieved from the database.
  • Now compare the new hash with the hash from the database. If they match, then password provided is correct. Otherwise, the password is incorrect.

Other interesting articles which you may like …

  • Google Tink Example – Google Cryptography
  • AES 256 Encryption and Decryption
  • AES 128 Encryption and Decryption
  • Constructor in Java
  • Private Constructors in Java
  • Java Constructor Chaining with example
  • Java – Constructor in an Interface?
  • Constructor.newInstance() method
  • Parameterized Constructor in Java
  • Java 8 – Lambda Expressions
  • Java 8 – ForEach Example
  • Java 8 Default Methods in Interface
  • Multiple Inheritance in Java 8 through Interface
  • Java 9 – jdeprscan
  • Private Methods in Interfaces Java 9
  • Java Method Overloading Example
  • Java Constructor Overloading Example
  • Java this keyword | Core Java Tutorial
  • Java super keyword
  • Abstract Class in Java
  • Interface in Java and Uses of Interface in Java
  • What is Marker Interface
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • Java Autoboxing and Unboxing Examples
  • Use of Java Transient Keyword – Serailization Example
  • Use of static Keyword in Java
  • What is Method Overriding in Java
  • Encapsulation in Java with Example
  • Final Keyword in Java | Java Tutorial
  • Java Static Import
  • Java – How System.out.println() really work?
  • Java Ternary operator
  • Java newInstance() method

Filed Under: Core Java, Java Tagged With: CSPRNG, hash, hash and salt, Hashing, password hasing, salt, Salted Password Hashing

Comments

  1. MR-OBVIOUS says

    March 25, 2019 at 6:26 am

    So its basically useless if you want to store a password for later comparison or compare files hash because it will give you a different answer each time???

    Reply
  2. Chris says

    April 2, 2019 at 6:14 pm

    For storing hashed with salt passwords in the DB, the salt would also have to be stored in the DB correct?

    Or else when the user tries to log in after creating his account and password, how would the system know his login entered afterwards matches an existing entry if the salt is generated randomly using the code above?

    Reply
    • javainterviewpoint says

      April 5, 2019 at 9:13 pm

      Yes the salt also has to be stored separately. So that it can be used to validate the user.

      Reply

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Java Basics

  • JVM Architecture
  • Object in Java
  • Class in Java
  • How to Set Classpath for Java in Windows
  • Components of JDK
  • Decompiling a class file
  • Use of Class.forName in java
  • Use Class.forName in SQL JDBC

Oops Concepts

  • Inheritance in Java
  • Types of Inheritance in Java
  • Single Inheritance in Java
  • Multiple Inheritance in Java
  • Multilevel Inheritance in Java
  • Hierarchical Inheritance in Java
  • Hybrid Inheritance in Java
  • Polymorphism in Java – Method Overloading and Overriding
  • Types of Polymorphism in java
  • Method Overriding in Java
  • Can we Overload static methods in Java
  • Can we Override static methods in Java
  • Java Constructor Overloading
  • Java Method Overloading Example
  • Encapsulation in Java with Example
  • Constructor in Java
  • Constructor in an Interface?
  • Parameterized Constructor in Java
  • Constructor Chaining with example
  • What is the use of a Private Constructors in Java
  • Interface in Java
  • What is Marker Interface
  • Abstract Class in Java

Java Keywords

  • Java this keyword
  • Java super keyword
  • Final Keyword in Java
  • static Keyword in Java
  • Static Import
  • Transient Keyword

Miscellaneous

  • newInstance() method
  • How does Hashmap works internally in Java
  • Java Ternary operator
  • How System.out.println() really work?
  • Autoboxing and Unboxing Examples
  • Serialization and Deserialization in Java with Example
  • Generate SerialVersionUID in Java
  • How to make a class Immutable in Java
  • Differences betwen HashMap and Hashtable
  • Difference between Enumeration and Iterator ?
  • Difference between fail-fast and fail-safe Iterator
  • Difference Between Interface and Abstract Class in Java
  • Difference between equals() and ==
  • Sort Objects in a ArrayList using Java Comparable Interface
  • Sort Objects in a ArrayList using Java Comparator

Follow

  • Coding Utils

Useful Links

  • Spring 4.1.x Documentation
  • Spring 3.2.x Documentation
  • Spring 2.5.x Documentation
  • Java 6 API
  • Java 7 API
  • Java 8 API
  • Java EE 5 Tutorial
  • Java EE 6 Tutorial
  • Java EE 7 Tutorial
  • Maven Repository
  • Hibernate ORM

About JavaInterviewPoint

javainterviewpoint.com is a tech blog dedicated to all Java/J2EE developers and Web Developers. We publish useful tutorials on Java, J2EE and all latest frameworks.

All examples and tutorials posted here are very well tested in our development environment.

Connect with us on Facebook | Privacy Policy | Sitemap

Copyright ©2023 · Java Interview Point - All Rights Are Reserved ·