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:
- MD5
- SHA-1
- 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:

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