MD5 hash in Java
To calculate cryptographic hashing value in Java, MessageDigest Class is used, under the package java.security.
MessagDigest Class provides following cryptographic hash function to find hash value of a text, they are:
1. MD5
2. SHA-1
3. 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
import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; // Java program to calculate MD5 hash value public class MD5 { public static String getMd5(String input) { try { // Static getInstance method is called with hashing MD5 MessageDigest md = MessageDigest.getInstance("MD5"); // digest() method is called to calculate message digest // of an input digest() return array of byte byte[] messageDigest = md.digest(input.getBytes()); // Convert byte array into signum representation BigInteger no = new BigInteger(1, messageDigest); // Convert message digest into hex value String hashtext = no.toString(16); while (hashtext.length() < 32) { hashtext = "0" + hashtext; } return hashtext; } // For specifying wrong message digest algorithms catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } // Driver code public static void main(String args[]) throws NoSuchAlgorithmException { String s = "GeeksForGeeks"; System.out.println("Your HashCode Generated by MD5 is: " + getMd5(s)); } } |
Output:
Your HashCode Generated by MD5 is: e39b9c178b2c9be4e99b141d956c6ff6
References:
Java Docs for MessageDigest
Recommended Posts:
- SHA-512 Hash In Java
- SHA-384 Hash In Java
- SHA-224 Hash In Java
- MD2 Hash In Java
- Implementing our Own Hash Table with Separate Chaining in Java
- SHA-1 Hash
- Hash Table vs STL Map
- Advantages of BST over Hash Table
- Graph representations using set and hash
- Hash Functions in System Security
- Hash Function for String data in C#
- Sorting using trivial hash function
- Sort elements by frequency | Set 4 (Efficient approach using hash)
- Overview of Data Structures | Set 2 (Binary Tree, BST, Heap and Hash)
- Implementing own Hash Table with Open Addressing Linear Probing in C++
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



