×

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

Deadlock in Java

Deadlock is when two or more processes wait for the state to do their tasks, but none of them can do so. It is a very common problem that one...

6 minutes read.

Tree Implementation in Java

Introduction to Tree A non-linear, hierarchical data structure called a "tree" is made up of a number of nodes, each of which contains a values and a sequence of pointers to...

14 minutes read.

Sorting Algorithms in Java

Sorting Algorithms in Java Sorting is the technique that puts the elements of an array or list either in descending or ascending order. For example, take an array A, whose elements...

3 minutes read.

Advanced Java Viva Questions

One of the more difficult languages available now is Java. Currently, 10 thousand developers worldwide use the programming language, which is rising daily. So, if you're a Java developer, an aspiring...

9 minutes read.

How to Convert Decimal to Octal in Java

How to Convert Decimal to Octal in Java There are two methods to convert Decimal to Octal: Using toOcatlString() method Using user-defined logic Using Integer.toOctalString() method The toOctalString() is astaticmethod of the Integer...

2 minutes read.

How to Create Singleton Class in Java

In this tutorial, we will discuss the singleton class and how to create it. Introduction Java is a purely object-oriented programming language. It consists of classes and objects. But Singleton is one...

4 minutes read.

Moran Numbers in Java

In this article, we will be acknowledged about the moran numbers in Java, how they are formed, what are the approaches to achieve the moran numbers. Moran Number A moran numbers are...

3 minutes read.

Java String copyValueOf() method

copyValueOf() method returns a String that holds the character sequence of the character array. Syntax: copyValueOf(char[] data) Parameters: data : the character array i.e. String Returns: It returns a String that contains the characters of the...

2 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.

Construct the Largest Number from the Given Array in Java

In this section, we will create a Java programme that will enable you to locate the greatest integer in an array. The programme will begin comparing the array's numbers with...

3 minutes read.

How to convert list to String in Java

Sometimes, we need to transform a listing of characters into a string. A string is a chain of characters, so we will make a string from an individual array without...

4 minutes read.

Determine the Upper Bound of a Two-Dimensional Array in Java

Multi-Dimensional Array Multi-faceted exhibits in Java are regular and can be named various clusters. Information in a two-layered bunch in Java is put away in 2D even structure. A two-layered collection...

3 minutes read.

Iterate JSON array in Java

This article is going to equip the knowledge about what JSON array is and how it works and also how is it distinct with the generic array. Json Array Ordered lists of...

4 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

How to Set Environment Variables for Java

Introduction Java is an object-oriented programming language that is based on classes and can be employed mostly to develop web and desktop applications. No matter the computer architecture, Java applications are...

7 minutes read.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Java Read File Line by line

Java provides two options to read files line by line. Each option offers different benefits and has its own set of drawbacks. Following are the ways through which on accomplish...

5 minutes read.

Java Program to Print Permutations of String

A string is given and you need to print all the possible ways for that string. Permutation is arranging the characters of a string to get outputs from the given...

3 minutes read.

Java Interface Keyword

An interface is also known as the blueprint in Java. It has constants of static values and methods of abstraction. The interface is a mechanism used by Java to declare...

3 minutes read.

This Operator Using in Java

this keyword in Java has a wide range of applications. this reference variable in Programming language refers to the object of interest. This keyword is used in Java. this keyword is...

5 minutes read.