×

Java SHA256

Definition: In cryptography, SHA is a hash function that takes 20 bytes of input and produces an approximate 40-digit hexadecimal integer as the hash result.

Class for Message Digest:

Java's MessageDigest Class, which is part of the java. security package, is used to determine cryptographic hashing values.

To determine the hash value of a text, the MessagDigest Class includes the following cryptographic hash functions:

  1. MD5
  2. SHA-1
  3. SHA-256

The static function getInstance() initialises this algorithm. It calculates the digest value after choosing the algorithm and returns the results in a byte array.

The generated byte array is transformed itself into the sign-magnitude representation using the BigInteger class. To obtain the MessageDigest, this representation is translated to hex format.

Examples:

Input : JavaTpoint

Output : f9142e5ca706378c1c7f9daf6782dcff8197ef1ecfd4075b63dae2f40186afa6

Input : Deekshitha

Output : b9a7b716a303aaf0d9aca444ed2952cab3a0b0b43d280569d125b2f2f9c65a2f

Input : heanchek

Output: dab257e7e013412044748a4279ba69a7df04205c81a33247de9681fb2becac62

Java Program

import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
// SHA hash value calculation in Java
 
class JavaSha256expl {
    public static byte[] getSHA(String input) throws NoSuchAlgorithmException
    {
        // With SHA hashing, the static getInstance function is called.
        MessageDigest m = MessageDigest.getInstance("SHA-256");
 
        // Message digest of such an 
// input is calculated using the 
// digest() method, which returns 
// an array of bytes.
        return m.digest(input.getBytes(StandardCharsets.UTF_8));
    }
     
    public static String toHexString(byte[] hash)
    {
        // Convert byte array into signum representation
        BigInteger n = new BigInteger(1, hash);
 
        // message digest -> hex value conversion
        StringBuilder hexString = new StringBuilder(n.toString(16));
 
        // Add leading zeros to the pad
        while (hexString.length() < 64)
        {
            hexString.insert(0, '0');
        }
 
        return hexString.toString();
    }
 
    // Driver code
    public static void main(String args[])
    {
        try
     { System.out.println(" SHA-256 generated a hash code for: ");
String s0 = "JavaTpoint";
            System.out.println("\n" + s0 + " : " + toHexString(getSHA(s0)));
 
            String s1 = "Deekshitha";
            System.out.println("\n" + s1 + " : " + toHexString(getSHA(s1)));
             
            String s2 = "heanchek"; 
            System.out.println("\n" + s2 + " : " + toHexString(getSHA(s2)));
        }  // due to incorrectly spec'ing message digest algorithms
        catch (NoSuchAlgorithmException e) {
            System.out.println(" An error in the algorithm resulted in an exception: " + e);
        }
    }
}

Output:

Java SHA256

Application:

Data Integrity and Cryptography are the areas where JavaSha256 is majorly used.


Related Topics

JDBC vs ODBC

Difference Between JDBC and ODBC ODBC: ODBC (Open Database Connectivity) is the accepted method for accessing databases among organisations and programmers. A database is linked to other programmes, such as word processors, spreadsheets,...

4 minutes read.

Convert JSON to Map in Java

JACKSON and GSON libraries are two extremely capable JSON-related libraries offered by Java. To efficiently work with the returned JSON data, we frequently need to convert JSON responses into a...

6 minutes read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

How to run Java Program in Eclipse

How to run Java Program in Eclipse In this section, we will learn how to write, save, compile, and execute or run a Java program in Eclipse. Eclipse is one of...

2 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Can we override Private Method in Java

In this article we will learn the concept of override, private method in java and we will now whether we can override private method in java or not. Override in Java Any...

3 minutes read.

Java BLOB

The two data types used in Java to store binary and big-character objects are BLOB and CLOB. In contrast to other types of data like float, int, double, etc., it...

4 minutes read.

DatabaseMetaData in Java

The Data about another data is called Meta data. The DatabaseMetaData interface has the meta data of the database present in the system. It consists of database product name, total...

2 minutes read.

Sum of digits in string in java

To find the sum of all digits in a string, you need to traverse through the string one by one character; if the character is an integer, you need to...

2 minutes read.

How to Assign Static Value to Date in Java?

In this tutorial, we will learn certain ways to assign a static value to a date in java. We will see the limitation of each method that will lead to...

3 minutes read.

&amp;&amp; Operator in Java

“ && ” is the conditional - And operator in Java. In Java, it is an example of a logical operator. In Java, the “ & ” operator has two...

3 minutes read.

Java Subtract Days from Current Date

Dealing with date and time in Java is not a particularly challenging operation because Java has an API for date and time that simplifies duties for developers. There are two...

3 minutes read.

How to add 6 Months to the Current Date in Java?

In this tutorial, we will learn how to add 6 months to the local or current date in Java language. We will begin our topic with basic concepts and would...

3 minutes read.

Fibodiv Number in Java

Before understanding the concept of the fibodiv number, one should realize what the Fibonacci number is. What are Fibonacci Numbers? The Fibonacci sequence of whole numbers is composed of the numbers 0,...

5 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Minimum Window Subsequence in Java

In this article, you will be very well acknowledged about the minimum window subsequence, what is the approach and how it is implemented. The example program is also executed and...

4 minutes read.

Java Image

For all other classes used for representing graphical images, Java's Image class serves as an abstract superclass. For images in Java, a specific form of object known as a BufferedImage...

4 minutes read.

Features of Java

The objective of the Java programming language is to provide portability, security, and simplicity. In spite of this, Java has a number of features that makes it a popular language...

5 minutes read.

Bifunction in java 8

A functional interface in Java is called BiFunction. It first appeared in Java 8. It can serve as the assigning target for a method reference or lambda expression. The java.util.function...

4 minutes read.

How to Reduce Time Complexity in Java

What is time complexity?  The time complexity in java is given as the amount of time a program requires to run or execute it Calculating the time complexity of the program The time...

4 minutes read.