In this tutorial, I am going to show you how to use Java MD5 Encryption.

Java MD5 Encryption :

The below example generate a MD5 encryption (generating hash value) for a given password (String).

JavaMD5Example.java
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class JavaMD5Example {

    public static String getMD5EncryptedValue(String password) {
        final byte[] defaultBytes = password.getBytes();
        try {
            final MessageDigest md5MsgDigest = MessageDigest.getInstance("MD5");
            md5MsgDigest.reset();
            md5MsgDigest.update(defaultBytes);
            final byte messageDigest[] = md5MsgDigest.digest();

            final StringBuffer hexString = new StringBuffer();
            for (final byte element : messageDigest) {
                final String hex = Integer.toHexString(0xFF & element);
                if (hex.length() == 1) {
                    hexString.append('0');
                }
                hexString.append(hex);
            }
            password = hexString + "";
        } catch (final NoSuchAlgorithmException nsae) {
            nsae.printStackTrace();
        }
        return password;
    }

    public static void main(String[] args) {
        System.out.println(getMD5EncryptedValue("chandra123"));
        System.out.println(getMD5EncryptedValue("chandra123"));
    }

}

Output :

Terminal
b4a3f7314b7b5096b920a3a8c1ef0ac2
b4a3f7314b7b5096b920a3a8c1ef0ac2

Reference :

MD5 wiki

Java MessageDigest

About the Author:

Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

2 Comments

  1. VRadhe February 21, 2019 at 4:04 pm - Reply

    have you any tutorial for MD5 decryption ?

  2. Meepa August 9, 2021 at 10:14 am - Reply

    Any chance to get the rainbow table generation by doing a reduction formula into the generated-hash say 4 times, and then adding the word and the last hash to a table of some sort?
    Preferably a table that can print to a file in the sorted by hash value and the word it came from?

    There is very little clear examples of this on the internet so you’ll be the first!

Leave A Comment