Java MD5 hash example, one way hash

The Java program below demonstrates the usage of MD5 hash. MD5 hash converts a string to MD5 hashed values, it is a one way encoding, which means MD5 doesn’t provide method to decode the hashed values. Once the string is hashed, there is no going back from hashed values to the original values. It is still possible to get the original values, but there is no handy way to do it. MD5 hash can be used to store passwords. It stores the password in hashed value, the password verification would be the user enters the password, the program hashes the entered password and then compare this hashed value against the stored hash value. For a better security, it is recommended to add salt the string before hash it. For example, add some random string to the string you want to hash, and then hashes it.

import java.math.BigInteger;
public class MD5Hash {
	private final static String salt="DGE$5SGr@3VsHYUMas2323E4d57vfBfFSTRU@!DSH(*%FDSdfg13sgfsg";
    public static void main(String[] args) {
            String password = "thisismypassword";
            String empty =  null;
            String msg = "This is a text message.";
            System.out.println(password+" MD5 hashed to>>>>>>> " + md5Hash(password));
            System.out.println(empty+" MD5 hashed to>>>>>>> " + md5Hash(null));
            System.out.println(msg+" MD5 hashed to>>>>>>> " + md5Hash(msg));

    //Takes a string, and converts it to md5 hashed string.
    public static String md5Hash(String message) {
        String md5 = "";
        if(null == message) 
        	return null;
        message = message+salt;//adding a salt to the string before it gets hashed.
        try {
	        MessageDigest digest = MessageDigest.getInstance("MD5");//Create MessageDigest object for MD5
	        digest.update(message.getBytes(), 0, message.length());//Update input string in message digest
	        md5 = new BigInteger(1, digest.digest()).toString(16);//Converts message digest value in base 16 (hex)
        } catch (NoSuchAlgorithmException e) {
        return md5;

Search within Codexpedia

Custom Search

Search the entire web

Custom Search