×

MessageDigest in Java

The compression of mathematical numbers is accomplished using hash functions. In almost every data security application, hash functions are employed. The hashing, often called has values, returns a value called MessageDigest. While the user-provided input for hashes can be any length, the result always has a set length.

When transforming a communication of any length to a hash algorithm, Java. The security module has a class called MessageDigest that implements techniques like SHA-1, SHA 256, and MD5, among others.

MessageDigest in Java

The steps below are used to transform a message together into MessageDigest:

1. The getInstance() function of the MessageDigest class returns an instance performing the provided algorithm. In the initial step, you will use the MessageDigest's getInstance() function to construct an example of MessageDigest. This algo argument, which specifies the method used, is accepted by the getInstance() function. 

Syntax:

MessageDigest object = MessageDigest.getInstance("SHA-1"); 

2. In the subsequent step, we will provide the information to newly generated MessageDigest instances. We employ the MessageDigest subclass' update() function to send the information. Information that takes the form of a bytes array is accepted by that the update() function.

Syntax:

object.update(msg.getBytes);

3.  The message digest will be created using the digest() function of a MessageDigest class during the following step. The digest() function returns the decoder as a bytes array. The present object's    

 hashing function is determined using the digest() procedure.

Syntax:

byte[] digest = object.digest();  

The program can understand the methods.

Example: MessageDigestEx.java

// this program is for message digesting in java
//importing the packages required
import java.io.*;
import java.util.*;
import java.security.MessageDigest;  
import java.util.Scanner;  
// a class is created MessageDigestEx for using the MessageDigest Class
public class MessageDigestEx {  
    // the main method of the program
    public static void main(String args[]) throws Exception{  
        //  an object was created for the scanner class
        Scanner sca = new Scanner(System.in);  
        System.out.println("Please enter the data (message) :");  
        String msgs = sca.nextLine();  
        // closing up the scanner class
        sca.close();  
        //utilising the getInstance() function and the SHA-256 method, build a new example of a MessageDigest class.  
        MessageDigest object = MessageDigest.getInstance("SHA-256");  
    //To send data to the newly generated MessageDigest Object have used the update() function.
        object.update(msgs.getBytes());  
        //the message digest should be calculated using the digest() technique.
        byte[] byteArrays = object.digest();  
        System.out.println(byteArrays);    
        // the byte array is converted to hexadecimal format
        StringBuffer hexDatas = new StringBuffer();  
        for (int i = 0; i < byteArrays.length; i++) {  
            hexDatas.append(Integer.toHexString(0xFF & byteArrays[i]));  
        }  
        System.out.println(" The data in the Hexadecimal format : " + hexDatas.toString());       
    }  
}  

Output

Please enter the data (message) :
Java Programming Language
[B@6193b845
The data in the Hexadecimal format : adf087da7e732888517370c125734b97fd8a6b39942b982f3ac67e68bb13535

If no provider offers that message digest client applications for the proposed methodology, the getInstance() function of both the MessageDigest classes may raise the NoSuchAlgorithmException.

Example: MessageDigestExceptionExa.java

// this program is for message digesting in java
//importing the packages required
import java.io.*;
import java.util.*;
import java.security.MessageDigest;  
import java.util.Scanner;  
// a class is created for throwing up the Exception
public class MessageDigestExceptionExa {  
    // main section of the program  
    public static void main(String args[]){  
        // an object is created for the scanner class
        Scanner sca = new Scanner(System.in);  
        System.out.println("Enter the data of any length: ");  
        String msgs = sca.nextLine();  
        //end of the scanner class
        sca.close();  
        try {  
            //utilizing the JTP technique and the getInstance() function, build a new instance of such MessageDigest. 
            MessageDigest objs = MessageDigest.getInstance("Programming");   // the error is thrown
//To send data to the newly generated MessageDigest instance have used the update() function.
            objs.update(msgs.getBytes());  
            //To determine the message digest, utilize the digest() function. 
            byte[] byteArrays = objs.digest();  
            System.out.println(byteArrays);    
            //the byte array is converted to hexadecimal format
            StringBuffer hexDatas = new StringBuffer();  
            for (int i = 0; i < byteArrays.length; i++) {  
            hexDatas.append(Integer.toHexString(0xFF & byteArrays[i]));  
            }  
            System.out.println("The data in the Hexadecimal format : " + hexDatas.toString());   
        }catch(Exception e) {  
            System.out.println(e);  
        }      
    }  
}  

Output

Enter the data of any length: 
Programming is good
java.security.NoSuchAlgorithmException: Programming MessageDigest not available

Related Topics

What is advance Java?

The definition of advance inside the dictionary refers to a forward motion, development, or progress, and the definition of enhancing is something that improves things. To become experts in that...

3 minutes read.

Java Boolean toValue() Method

The valueOf() method of Java Boolean class returns a Boolean object representing the given Boolean or String value. It returns true, if the specified Boolean or string object is true...

2 minutes read.

How to Convert long to String in Java

How to Convert long to String in java It is used if we have to display a long number in the text field because everything is displayed as a String. A...

3 minutes read.

Interchange Diagonal elements in Java

In this article, you will be very well acknowledged about what is a matrix with an example. You will also be acknowledged about how to interchange the diagonal elements in...

4 minutes read.

Java Math copySign() Method

The copySign() method of Math class returns the first floating-point argument with the sign of the second argument. Syntax: public static float copySign(float magnitude, float sign)public static double copySign(double magnitude, double sign) Parameters: The...

1 minute read.

Equilibrium Index of an Array in Java

An array's equilibrium index is the condition where the sum of items with lower and higher indices equals. For example, an array A=[-4,5 2,6,-5] where: a[0]=-4, a[1]=5, a[2]=2, a[3]=6, a[4]=-5 Now according...

4 minutes read.

Exception Handling Program in Java

Exception Handling Program in Java Exception means something that is abnormal. In Java, an exception is treated as a problem that disrupts the normal flow of the program. An exception leads...

7 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

How to Convert Hexadecimal to Decimal in Java

How to Convert Hexadecimal to Decimal in Java There are two methods to convert Hexadecimal to Decimal: Using parseInt() method Using user-defined logic Using Integer.parseInt() method It is a static method of...

2 minutes read.

Sliding Window Problem in Java

A sliding window is used in computer science and data science to process large datasets. It involves breaking the dataset into smaller chunks or windows and then processing it in...

6 minutes read.

Java Thread Creation

Java provides the two ways to create a Thread: Implementing the Runnable interface.Extending the Thread class. Implementing Runnable interface The easiest way of creating a thread is to make a class that implements...

5 minutes read.

Java Math rint() Method

The rint() method of Java Math class returns the double value which is close to the specified argument and is equal to mathematical integer. Syntax: public static double rint(double a) Parameters: The parameter ‘a’...

1 minute read.

ArrayDeque in Java

ArrayDeque The ArrayDeque is one of the essential concepts in java to implement the deque interface. It will allow us to apply a resizable array to implement the Deque interface. This...

8 minutes read.

How to make Java Projects

Ant and Maven are both offered by NetBeans for the development of Java applications. When using Ant, the IDE creates an Ant build script depending on the settings you select...

6 minutes read.

Empty Statement in Java

The three sorts of statements in Java are control, expression, and declaration statements. Additionally, another statement is referred to as an empty statement. In this section, we will discuss about...

4 minutes read.

Java String toCharArray() method

Java String toCharArray() method converts current String into character array. Syntax: public char[] toCharArray() Returns: It returns a character array Java String toCharArray() method example 1 import java.util.Arrays; public class JavaStringToCharArrayEx1 {           public static...

2 minutes read.

Zygodromes in Java

Zygodrome is a positive number created by the same digits running non-trivially. A number is called a zygodrome if identical digits constantly occur together (in pairs). The Greek word "zyg"...

4 minutes read.

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Encapsulation Program in Java

Encapsulation Program in Java Encapsulation program in Java demonstrates the technique to bind methods and fields in a single unit. The term encapsulation is inspired by the word ‘capsule’, which is...

3 minutes read.

Hollow Diamond Pattern in Java

Why are patterns important? Programmers frequently create Java pattern programs to practice coding and ace interviews. Interviewers frequently test candidates' logical reasoning and implementation by asking about pattern programs. Hollow Diamond Pattern The...

7 minutes read.