Java MD5 example

Java MD5 Overview

MD5 (Message-Digest algorithm 5) is a widely used cryptographic hash function with a 128-bit hash value, specified in RFC 1321, MD5 is one in a series of message digest algorithms designed by Professor Ronald Rivest of MIT (Rivest, 1994). MD5 has been employed in a wide variety of security applications, and is also worldwide used to check the integrity of files.

MD5 is a perfect solution for security thinking. The Java developers usually may take over or code MD5 encryption, the MD5 encryption is complicated, for self-coding it’s hard to implement. Java standard edition has MD5 support built in. in package java.security, class MessageDigest supports functionality of a message digest algorithm, such as MD5 or SHA.

1. Example to Hash a String with MD5 algorithm

This is a Java MD5 example, it passes into a string and returns the MD5 encryption value, we used the method getBytes() that converts a plain text to byte array, the digest is then updated from the bytes from the byte array and a hash computation is conducted upon them(using MessageDigest).

MD5.java
import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {
    public static String getMD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            BigInteger number = new BigInteger(1, messageDigest);
            String hashtext = number.toString(16);
            // Now we need to zero pad it if you actually want the full 32 chars.
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        }
        catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        System.out.println(getMD5("Javarmi.com"));
    }
}

Java MD5 example Output:

0127f712fc008f857e77a2f3f179c710

2. Another way Hashing String with MD5 algorithm

This is another Java MD5 encryption example, it accepts string and returns MD5 encryption value.

import java.io.FileInputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {
    public static String getMD5(String input) {
        byte[] source;
        try {
            //Get byte according by specified coding.
            source = input.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            source = input.getBytes();
        }
        String result = null;
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(source);
            //The result should be one 128 integer
            byte temp[] = md.digest();
            char str[] = new char[16 * 2];
            int k = 0;
            for (int i = 0; i < 16; i++) {
                byte byte0 = temp[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            result = new String(str);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args) throws NoSuchAlgorithmException {
        System.out.println(getMD5("Javarmi.com"));
    }
}

Java MD5 example Output

0127f712fc008f857e77a2f3f179c710

3. File checksum using Java MD5

MD5 algorithm is also widely used for file checksum to ensure that files were not modified by attacker, an example is below that uses Java MD5 hashing algorithm to generate a checksum for file “c:\\apache\\cxf.jar”. you can check whether the printed value matches the original MD5 value which was released by Jar Publisher.

    public static void main(String[] args) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        FileInputStream fis = new FileInputStream("c:\\apache\\cxf.jar");

        byte[] dataBytes = new byte[1024];

        int nread = 0;
        while ((nread = fis.read(dataBytes)) != -1) {
            md.update(dataBytes, 0, nread);
        };
        byte[] mdbytes = md.digest();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < mdbytes.length; i++) {
            sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        System.out.println("Digest(in hex format):: " + sb.toString());
    }

Reference

http://download.oracle.com/javase/1.4.2/docs/api/java/security/MessageDigest.html

Rate article
ASJAVA.COM
Add a comment

Your email address will not be published. Required fields are marked *

*

code

  1. MD5 Example

    Thanks your Java MD5 checksum. I am happy Java support MessageDigest to help to implement MD5 checksum.

    Reply
  2. Viraf Karai

    I feel that instead of writing all this code, it is preferable to use Apache Commons
    Codec and write very little code such as:
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    final String stringForMD5 = “Mary had a little lamb, its fleece was white as snow”;

    final String md5Hex = DigestUtils.md5Hex (stringForMD5);

    final String result = String.format(“MD5 for %s is %s %n”, stringForMD5, md5Hex);

    System.out.println (result);

    Reply
    1. admin author

      You are right, Apache Codec is an alternative approach to implement MD5, but we have to import the 3th library to have this feature included, In Java, we actually don’t need write much code as well, just a little code lines…

      Reply
  3. Ankur parihar

    plz md5 to plaintext in PHP..

    Reply
    1. admin author

      Sorry, I don’t know much about PHP.

      Reply
      1. Muhammad Tahir Qaiser

        In php , it’s simple
        $password=”password”;
        $hash=md5($password);
        echo $hash;

        And Thanks to admin for Java md5 code 🙂

        Reply
    2. vishal

      Description :-

      string md5 ( string $str [, bool $raw_output = false ] )
      Calculates the MD5 hash of str using the » RSA Data Security, Inc. MD5 Message-Digest Algorithm, and returns that hash.

      Parameters:-

      str:The string.

      raw_output:If the optional raw_output is set to TRUE, then the md5 digest is instead returned in raw binary format with a length of 16.

      Return Values:Returns the hash as a 32-character hexadecimal number.

      Examples :

      Reply
  4. vishal

    Sometimes it’s useful to get the actual, binary, md5 digest.
    You can use this function for it:

    <?php

    function md5bin( $target ) {
    $md5 = md5( $target );
    $ret = '';

    for ( $i = 0; $i

    Reply