Implementation of MD5 Algorithm in Java


Levels of difficulty: / perform operation:

Java Program to implement MD5(Message Digest-5) Algorithm. Generate Hash of the given message using MD5 Algorithm. Here, we have given md5 method to generate hash of the message, just pass a string in md5 method and get result.

java Program

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class JavaMD5Hash {
	public static void main(String[] args) {
		System.out.println("For null " + md5(""));
		System.out.println("For simple text "+ md5("This is my text"));
		System.out.println("For simple numbers " + md5("12345"));
	}
	public static String md5(String input) {
		String md5 = null;
		if(null == input) return null;
		try {
			//Create MessageDigest object for MD5
			MessageDigest digest = MessageDigest.getInstance("MD5");
			//Update input string in message digest
			digest.update(input.getBytes(), 0, input.length());
			//Converts message digest value in base 16 (hex) 
			md5 = new BigInteger(1, digest.digest()).toString(16);
		}
		catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return md5;
	}
}





Quantitative Aptitude
Reasoning
Programming
Interview