×

Hashing Algorithm in Java

The hashing algorithm is a method that maps data to the fixed-length hash. The Java hash-based algorithm employs a cryptographic mathematical operation. A hash technique or hash function is supposed to be yet another function. One approach implies that inverting is not feasible, i.e., obtaining the previous number from the hashed is impossible.

The Hashing Algorithm's Property

must include the following properties in a decent hashing algorithm:

  •  data should be hashed quickly using the hashing method.
  • The method should prevent regenerating the message based on the hashing value obtained (one way).
  • Within no point in time should the two signals utilize the same hash. To put it another way, the hashing method must prevent collisions.
  • Because even when minor changes are made to the text, the hash function must change. The avalanche effect is what it's called.

The characteristics of Hashing Algorithm

A decent hashing algorithm should have the following properties:

Any data must be hashed quickly using the hashing method.

The algorithm should prevent regenerating a message based on its hash function (one way).

At no moment in time should the two signals have the same hash. To put it another way, the hashing method must prevent collisions.

Whenever the message changes even a little, the hash value must update. It's referred to as the avalanche effect.

Kinds of Hashing Algorithms

Some examples of hash functions are shown below.

The MD5 Algorithm

The  Secure Hashing  Method

The PBKDF2withHmacSHA1 Approach

The MD5 Algorithm

The Message-Digest Algorithms (MD5) is a popular hash functions algorithm that gives a hash value of 16 bytes (128 bits). It is really basic and straightforward. The fundamental idea is to translate data sets of varying lengths to large datasets of fixed length.

To do this, the received message is divided into 512-bit chunks. Extra space is attached to the end so it may split its length by 512. The blocks are already digested using the MD5 technique, which works in the 128-bit state, yielding a 128-bit hash value. The hash produced by the MD5 method is typically a 32-digit hexadecimal value.

MD5.java

// this program for MD5 algorithm implementation in java
//importing the packages required
import java.io.*;
import java.util.*;
import java.math.BigInteger;  
import java.security.NoSuchAlgorithmException;  
import java.security.MessageDigest;  
// the class
public class MD5  
{  
public static String getMd5(String inputs)  
{  
try   
{  
 //calling the MessageDigest class's static getInstance() method 
 //Notice the MD5Algoparameter.
MessageDigest msgDsts = MessageDigest.getInstance("MD5");  
//The digest() function is called to generate the digest 
//from such an inputs digest() and produces an array of bytes. 
byte[] msgArrs = msgDsts.digest(inputs.getBytes());  
  
// the signum for the given array 
BigInteger bit = new BigInteger(1, msgArrs);  
  
// the number is then converted to hexadecimal form
String hshtxts = bit.toString(16);  
  
while (hshtxts.length() < 32)   
{  
hshtxts = "0" + hshtxts;  
}  
return hshtxts;  
}  
// for the handling of the exception
catch (NoSuchAlgorithmException abcd)   
{  
throw new RuntimeException(abcd);  
}  
}  
// main section of the program 
public static void main(String s[]) throws NoSuchAlgorithmException  
{  
String string = "Google";  
String hashs = getMd5(string);  
string = "'Google'";  
System.out.println("The Formed HashCode for " + string + " is: " + hashs);  
}  
}  

Output

The Formed HashCode for 'Google' is: 8b36e9207c24c76e6719268e49201d94

MD5 Algorithm Inaccuracies

The MD5 algorithm is a common hashing method. It is because it generates a hash quickly and is simple to implement. The algorithm, unfortunately, contains security vulnerabilities. The hashes produced by this technique are quite weak. This approach is also prone to collisions. As a result, there is a good likelihood that two distinct passwords will yield identical hashes.

It is advised to add salt to make the MD5 algorithm more secure.

MD5 using Salt Algorithm

Salt strengthens and secures the MD5 algorithm. A salt is just some random text that is appended to a string before the MD5 algorithm analyzes it. Should note that salt is not exclusive to the MD5 algorithm. May also use it those other hashing methods. The example shows how to use salt with the MD5 algorithm.

MD5SaltEx.java

// this program for MD5 algorithm implementation in java
//importing the packages required
import java.io.*;
import java.util.*;
import java.math.BigInteger;  
import java.security.NoSuchAlgorithmException;  
import java.security.NoSuchProviderException;  
import java.security.MessageDigest;  
import java.security.SecureRandom;  
public class MD5SaltEx.java
{  
public static byte[] receiveSalt() throws NoSuchAlgorithmException  
{  
SecureRandom secRands = SecureRandom.getInstance("SHA1PRNG");  
// a salt 
byte[] sa = new byte[15];  
// the result of the random values of the salt 
secRands.nextBytes(sa);  
  
// returning the salt value
return sa;  
}  
  
// obtaining the credential hash function using the MD5 algorithm and the salt array
private static String getSecurePswd(String psdToHashs, byte[] saltArrs)  
{  
//  string for storing up the value
String generatedPswds = null;  
try   
{  
//  an object is created for MessageDigest
MessageDigest msgDigests = MessageDigest.getInstance("MD5");  
  
// the password is then added
msgDigests.update(saltArrs);  
  
//  the result of the hash function
byte[] b1 = msgDigests.digest(psdToHashs.getBytes());  
  
// The b[] includes bytes in decimal number
// It is being converted to binary code.
StringBuilder sbObjs = new StringBuilder();  
  
for(int i = 0; i < b1.length ; i++)  
{  
sbObjs.append(Integer.toString((b1[i] & 0xff) + 0x100, 16).substring(1));  
}  
//  the password in the form of hexadecimal
generatedPswds = sbObjs.toString();  
}   
  
//  the condition for the exception
catch (NoSuchAlgorithmException object)   
{  
object.printStackTrace();  
}  
  
return generatedPswds;  
}  
// main section of the program
public static void main(String argvs[]) throws NoSuchProviderException  
{  
String strs = "Google"; //  the string input
byte[] saltArrs = receiveSalt();  
   
String securePsd = getSecurePswd(strs, saltArrs);  
System.out.println("The Converted Hashcode for  " + strs + " is: " + securePsd);  
String regeneratedPswdToVerify = getSecurePswd(strs, saltArrs);  
System.out.println("The Converted Hashcode for " + strs + " is: " + securePsd);  
}  
} 

Output

The Converted Hashcode for  Google is: 9d59edae8facc1ffb2e9d9cf9d12bcc7
The Converted Hashcode for Google is: 9d59edae8facc1ffb2e9d9cf9d12bcc7

Note: Always remember that the salt value must be kept for every single password scrambled. This is because whenever the user logs again into the system, they may use the initial salt to ensure that the hash produced matches the saved hash. If the customer does not utilize the appropriate salt, the resulting hash will not reflect the cached hash, which may result in a login failure.

Algorithm for SHA

The Secure Hash Algorithm (SHA) is a cryptographic algorithm. The method is comparable to MD5. On the other hand, the SHA method generates significantly stronger hashes than the MD5 method. The hashes created by the SHA algorithm are not unique, meaning they may collide. Therefore, the collision rate in SHA is substantially lower than in MD5. The SHA algorithm has four Java interpretations.

SHA-1 is the most basic SHA. It generates 20 bytes (160 bits).

SHA-256 is a far more secure algorithm than SHA-1. It generates a hash using 256 bits.

SHA-384 - SHA-384 becomes much more advanced than SHA-256 and produces a 384-bit hash.

SHA-512 is the most powerful of the SHA algorithms. It creates a 512-bit hash.

As a result, the greater the hash, the harder the hash. It signifies that breaking a hash of a bigger magnitude is difficult.

The construction of SHA - 256 is shown in the given description.

SHAExamples.java

// this program for SHA-256 algorithm implementation in java
//importing the packages required
import java.io.*;
import java.util.*;
import java.security.NoSuchAlgorithmException;  
import java.math.BigInteger;  
import java.security.MessageDigest;  
import java.nio.charset.StandardCharsets;  
public class SHAExamples  
{  
public static byte[] obtainSHA(String s) throws NoSuchAlgorithmException  
{  
// The static getInstance() function is called using the hashing algorithm SHA-256
MessageDigest msgDgsts = MessageDigest.getInstance("SHA-256");  
  
//and the digest() method is called to estimate the message digest of the inputs
//and it outputs an array of bytes.
return msgDgsts.digest(s.getBytes(StandardCharsets.UTF_8));  
}  
  
public static String toHexStr(byte[] hashs)  
{  
// the conversion of the byte array
BigInteger nos = new BigInteger(1, hash);  
  
// the value is converted to hexadecimal
StringBuilder hexStrs = new StringBuilder(nos.toString(16));  
  
// the left padding of the number
while (hexStrs.length() < 32)  
{  
hexStrs.insert(0, '0');  
}  
  
return hexStrs.toString();  
}  
  
// main section of the java program 
public static void main(String argvs[])  
{  
try  
{  
System.out.println("For characters, the HashCode generated by the SHA-256 algorithm is: ");  
  
String strs= "Google";  
String hashs = toHexStr(obtainSHA(strs));  
System.out.println("\n" + str + " : " + hashs);  
  
strs = "Programming Languages.";  
hashs= toHexStr(obtainSHA(strs));  
System.out.println("\n" + strs + " : " + hashs);  
}  
catch (NoSuchAlgorithmException object)   
{  
System.out.println("Error found for the algorithm: " + object);  
}  
}  
} 

Output

For characters, the HashCode generated by the SHA-256 algorithm is: 
Google : ce770667e5f9b0d8f55367bb79419689d90c48451bb33f079f3a9a72ae132de8
Programming Languages. : 2a37d18dfa442debe9c374cd80f77bc7128d4e8fbf55af19d3f6f49f13443949

Algorithm for  PBKDF2WithHmacSHA1

We've learned how to 's protective hashes and sometimes even make them extra secure by using salt. Technology is far faster than any password that can be hacked quickly, even using brute force assault.

A popular solution for this issue is to make the brute-force attack assault slower to minimize harm. The PBKDF2WithHmacSHA1 algorithm is based on the same idea. The goal is to develop a hash algorithm that is slow enough even to postpone the threats. On the other hand time, it must be quick enough to avoid any substantial delay in creating hashes for the user. The algorithm's parameter is an including (also known as a labor factor) or repetition count. The work count value impacts how fast the hashing is. The more valuable this publicly verifiable work factor, the more economical the device.

PBKDF2WithHmacSHA1Ex.java

// this program for SHA-256 algorithm implementation in java
//importing the packages required
import java.io.*;
import java.util.*;
import java.security.*;  
import java.math.BigInteger;  
import java.security.MessageDigest;  
import java.nio.charset.StandardCharsets;  
import javax.crypto.spec.PBEKeySpec;   
import javax.crypto.SecretKeyFactory;  
import java.security.spec.InvalidKeySpecException;  
  
public class PBKDF2WithHmacSHA1Ex   
{  
    // main section of the program  
    public static void main(String argvs[]) throws NoSuchAlgorithmException, InvalidKeySpecException   
    {  
        // password to be hashed  
        String  orgPasswords = "@Google";  
          
        String createdSecuredPasswordHashs = createStrongPasswordHash(orgPasswords);  
        System.out.println(createdSecuredPasswordHashs);  
    }  
      
  
    private static String createStrongPasswordHash(String password) throws NoSuchAlgorithmException, InvalidKeySpecException  
    {  
        // the variable is used for initialing the number of iterations
        int i = 50;  
        char[] charArray = password.toCharArray();  
        byte[] saltArray = obtainSalt();  
           
        PBEKeySpec pbeSpec = new PBEKeySpec(charArray, saltArray, i, 64 * 8);  
          
        // the hashing method  
        SecretKeyFactory secKeyFacts = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");  
        byte[] hashArray = secKeyFacts.generateSecret(pbeSpec).getEncoded();  
        return i + ": " + intoHex(saltArray) + ":" + intoHex(hashArray);  
    }  
       
     // the salt of the program
    private static byte[] obtainSalt() throws NoSuchAlgorithmException  
    {  
        SecureRandom secRands = SecureRandom.getInstance("SHA1PRNG");  
        byte[] saltArray = new byte[16];  
        secRands.nextBytes(saltArray);  
        return saltArray;  
    }  
       
       
     // the method for converting to the hexadecimal form  
    private static String intoHex(byte[] array) throws NoSuchAlgorithmException  
    {  
        BigInteger bInte = new BigInteger(1, array);  
        String hexString = bInte.toString(16);  
        int paddingLens = (array.length * 2) - hexString.length();  
        if(paddingLens > 0)  
        {  
            return String.format("%0"  + paddingLens + "d", 0) + hexString;  
        }  
        else  
        {  
            return hex string;  
        }  
    }  
}  

Output

50: 5a4c513aca61915d6a8b0dc25eb2fdbe
:9c11eb4fb4cd222ca0c7c84193c2f31037369c57628699f359d5c8e6170833b976434e90ead461706cd7b9787d19149954efcd04d7bef018689e220bbe23e0c6

Uses of Hashing

Detecting Duplicates: The basic concept of scrambling is that the same source yields the same password. As a result, if two passwords are the same, it implies that the inputs are similar.

Message Digest: Communication digests are used to keep data safe. For example, if we save our information in the cloud, we must also verify that they are not tampered with by others. To do so, locate and preserve the hash of files saved in the cloud that used a hashing method. Calculate the hash of the file again when it is retrieved from the cloud. If the produced hash equals the previously created hash, the files are not tempered.

Compilation Operation: Keywords (such as while, for, int, if, else, switch, and so on) are dealt with separately from the other variables. The computer distinguishes other variables and keywords by putting them in a collection. A hash table is used to construct the set.

Structures of Data: In database systems, hash tables are widely utilized. Hash tables are used in almost all database systems that enable key-value pairs.


Related Topics

Bucket Sort in Java

Bucket Sort in JavaBucket sort is also called bin sort. Bucket sort first puts the elements of the array or list into different buckets. The first bucket contains elements of the smallest value. The...

11 minutes read.

Java List Node

In Java, List Node is the same as the single linked list, which is the collection of nodes. So, we can say, the list nodes are grouped together to get...

8 minutes read.

XOR of Array Elements Except Itself in Java

A lot of the biggest IT organisations, including The Google, Amazon, TCS, and The Accenture, etc., question about this issue in their interview processes. By addressing the issue, one hopes to assess...

5 minutes read.

Swapping Program in Java

Swapping Program in Java The swapping program in Java is used to interchange the values of the two variables. For example, if X = 12 and Y = 24, then the...

4 minutes read.

Java String

Definition A string is a series of characters. Consider an example, "Welcome" is a 7-character string. In Java, String is an unchangeable object. That is, the String is perpetual and cannot be replaced after it is created. This is the tutorial in which you...

4 minutes read.

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

Java protected vs private

Java : Java is a pure object oriented language. It was introduced by James Gosling in the year 1995. The first public implementation of java was done by sun micro systems...

3 minutes read.

this keyword in Java

The 'this' keyword is an essential notion in Java. We'll go through the 'this' keyword in depth and provide some examples of how it's used in Java. In Java, the term...

5 minutes read.

How to Read CSV Files in Java?

Comma-Separated Values is the acronym for this format. It is a straightforward file format storing textual tabular data in a database or spreadsheet. The CSV files can be imported into...

3 minutes read.

Java Math subtractExact() Method

The subtractExact() method of Java Math class returns mathematical difference of the specified two arguments, throwing an exception if the result overflows int or long. Syntax: public static int subtractExact (int x,...

1 minute read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Mutable class in Java

A language for object-oriented programming is Java. Because this is an object-oriented language of programming, all of its mechanisms and methods are based on objects. Java has a concept of...

6 minutes read.

Dangling Else problem in Java

A language interpretation uncertainty is the hanging other issue. The following two types of condition executed code are both possible in programming: 1. if-then-else form 2. if-then form When dealing with the nested...

3 minutes read.

Java Error Stack Trace

The stack trace in Java is an array of stacks.The stack trace reveals the console's location of an exception or error by gathering data from all program methods. The JVM...

3 minutes read.

Hybrid Inheritance in Java

The most crucial OOPs concept in Java is inheritance, which enables the transfer of a class's properties to another class. It describes the Is-A relationship generally. We can create a...

3 minutes read.

Converting Long to Date in Java

What Long and Date are in Java and how are they implemented in the Java programming language are the topics of this article. Additionally, we'll go into great detail on...

4 minutes read.

Java Math floorMod() Method

The floorMod() method of Math class returns the floor modulus of the specified arguments. It firstly divides the dividend and divisor and then returns an integer that is equal to...

1 minute read.

Bouncy Number in Java

We will define bouncy numbers in this section and write Java programmes to determine whether a specific number is bouncy. Java coding exams and academic assignments usually inquire about the...

3 minutes read.

Rotate matrix by 90 degrees in Java | Rotate matrix in Java clockwise and anti-clockwise

In this article, you will be acknowledged about what is a matrix along with an example. Most importantly you will be equipped knowledge on how to rotate the matrix by...

4 minutes read.

Java Technologies List

Introducing Java technology is not necessary. Everyone across the globe is still in awe of Java's incredible capabilities for developing mobile apps and websites. Of course, you can be persuaded...

8 minutes read.