To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security.
MessageDigest Class provides following cryptographic hash function to find hash value of a text, they are:
- MD5
- SHA-1
- SHA-256
This Algorithms are initialize in static method called getInstance(). After selecting the algorithm it calculate the digest value and return the results in byte array.
BigInteger class is used, which converts the resultant byte array into its sign-magnitude representation.
This representation converts into hex format to get the MessageDigest
Examples:
Input : hello world
Output : 5eb63bbbe01eeed093cb22bb8f5acdc3
Input : GeeksForGeeks
Output : e39b9c178b2c9be4e99b141d956c6ff6
Implementation:
Java
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5 {
public static String getMd5(String input)
{
try {
MessageDigest md = MessageDigest.getInstance( "MD5" );
byte [] messageDigest = md.digest(input.getBytes());
BigInteger no = new BigInteger( 1 , messageDigest);
String hashtext = no.toString( 16 );
while (hashtext.length() < 32 ) {
hashtext = "0" + hashtext;
}
return hashtext;
}
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public static void main(String args[]) throws NoSuchAlgorithmException
{
String s = "GeeksForGeeks" ;
System.out.println( "Your HashCode Generated by MD5 is: " + getMd5(s));
}
}
|
OutputYour HashCode Generated by MD5 is: e39b9c178b2c9be4e99b141d956c6ff6