Java MD5 Hashing String
In this Java tutorial, we learn how to hash a String using MD5 algorithm in Java programming language.
How to use MD5 algorithm to hash a String in Java
Firstly, we create a new Java class named MD5Utils.
In this new class, implement a new static method named md5(String inputData), this method use the MD5 algorithm to hash the input text into a byte array and then convert the byte array to a hex String as a return value of method.
MD5Utils.java
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Utils {
/**
* This method to hash a String using MD5 algorithm
* @param inputData input text
* @return hashed text
*/
public static String md5(String inputData) {
try {
MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.update(inputData.getBytes());
byte[] hashedData = messageDigest.digest();
// convert byte array to hex String
BigInteger bigInteger = new BigInteger(1, hashedData);
String hashedText = bigInteger.toString(16);
return hashedText;
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
}
In the following example Java code, we learn how to use the above MD5Utils.md5() method to MD5 hash a String in Java program.
MD5UtilsExample.java
public class MD5UtilsExample {
public static void main(String... args) {
String inputText = "Simple Solution";
// Hash a String using MD5 algorithm
String hashedText = MD5Utils.md5(inputText);
System.out.println("Input text: " + inputText);
System.out.println("MD5 hashed text: " + hashedText);
}
}
Input text: Simple Solution
MD5 hashed text: 6cd04c53878b462e5d7d400a11ac19cf
Happy Coding 😊
Related Articles
Java AES 256 Encryption and Decryption
Java AES Advanced Encryption Standard Encryption and Decryption