×

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

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Java Developer

Who is a Java Developer? A Java developer is a skilled programmer who works on commercial applications, software, and webpages.  Java developers can work in two different areas: Operating system development:...

3 minutes read.

Java Read File to String

There are different ways to deal with forming and examining a text record. This is normal while dealing with various applications. There are different ways to deal with looking at a...

6 minutes read.

Highest precedence in Java

In Java, the operator is the first thing that springs to mind when discussing precedence. The order in which the operators in an expression are evaluated is controlled by a...

3 minutes read.

Array and String with Examples in Java

Array in Java: An array in Java is a group of variables with similar types that have a common name. The arrays used in Java differ from those used in C/C++. Key...

6 minutes read.

Zigzag Array in Java

In this tutorial, we discuss, what is zigzag array and its example. Even we will create the java program. In this program, we convert the simple array into a zigzag...

4 minutes read.

Java Wrapper classes

Java Wrapper classes A wrapper class is a class whose object contains a primitive data type; moreover it provides a way to use primitive data type (int, boolean, etc.) as objects. Wrapper...

2 minutes read.

Palindrome number program in Java

Write java program to check if a number is palindrome in Java? A number that does not change on reversing is called a palindrome number. In other words, when reversing the...

3 minutes read.

Singleton class in Java

What is Singleton class in Java? Singleton means it is one. That means we can create only one instance or object of a class. For example, let us have a class...

3 minutes read.

Reserved Keywords in Java

In Java, a reserved term is used as a code key called a keyword. Because they are predefined, these terms cannot be used for anything else. They cannot serve as...

3 minutes read.

How to check valid date in Java?

Every time we get data for any application, we must first ensure that it is accurate before continuing with any further processing. We might have to confirm the following while dealing...

4 minutes read.

How many ways to create object in Java?

In this article, you will be acknowledged about the different ways to create an object in java. So far you construct an object from a class, as is common knowledge,...

6 minutes read.

Java Control Statements

Control Statements: Control statements in Java can also be referred to as decision-making while dealing with different problems. Control statements are helpful to sort out the flow of the program or...

7 minutes read.

Java Database Connectivity with MySQL

In this tutorial, we will learn how to connect Database with MySQL in Java. 5 Steps to Connect to the Database in Java Load the driver (or) Register the driver classEstablish a...

4 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

How to Import Packages in Java

To know about the importing the packages of Java, we need to understand about how to packages work. Packages The package in Java is a collection of Classes and Interfaces. The packages...

3 minutes read.

Fall through in Java

In this article, you will be acknowledged about the fall through condition in Java along with an example program. Fall through It is a situation where there isn't a break statement in...

3 minutes read.

JRE (Java Runtime Environment)

JRE is an installation package that provides an environment to run the Java program on any Operating System. It does not deal with the development process of any application. It is a part...

2 minutes read.

Sierpinski Number in Java

The Sierpinski triangle—is it a fractal? The Sierpinski Triangle fractals. A self-similar fractal is the Sierpinski triangle. It is made of an equilateral triangle with its residual area successively reduced by...

3 minutes read.

Types of Garbage Collector in Java

Garbage collection is a Java feature that offers automatic memory management. The JVM is in charge of it. The programmer does not have to handle object creation and deallocation. We...

3 minutes read.