How do I generate MD5 digest from a File or an InputStream object?

In the How do I calculate the MD5 digest of a string? example you can see how to calculate the MD5 digest from a text or a string. We are using the Apache Commons Codec library and use the DigestUtils.md5Hex() method to generate the MD5. I’ve mentioned in that post that we can also generate the MD5 digest of a byte array and InputStream object. In the example below you’ll see an example to generate the MD5 digest of a text data stored in a file.

package org.kodejava.commons.codec;

import org.apache.commons.codec.digest.DigestUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class MD5FileHashDemo {
    public static void main(String[] args) {
        // Define the data file path and create an InputStream object.
        String data = System.getProperty("user.dir") + "/data.txt";
        File file = new File(data);

        try (InputStream is = new FileInputStream(file)) {
            // Calculates the MD5 digest of the given InputStream object.
            // It will generate a 32-character hex string.
            String digest = DigestUtils.md5Hex(is);
            System.out.println("Digest = " + digest);
            System.out.println("Length = " + digest.length());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

The first thing we need to do is to add the import statement to our class to import the org.apache.commons.codec.digest.DigestUtils class. The DigestUtils.md5Hex() method define as a static method so that we don’t have to create an instance of DigestUtils class before we can use it. Before we create the InputStream object we define the path to our data file. Next we create the File object from the defined path followed by creating the InputStream object of the file.

To generate the digest, we can simply pass the instance of the InputStream object into the DigestUtils.md5Hex() method. And if there is no error occurred during the process, we will get a 32 character of hex string as the output. One last thing that you have to do is the catch the possible exception thrown by the method. So we add the try-catch block and print the error stack trace to help us identify any error.

And here is the example output generated by the code snippet above:

Digest = d41d8cd98f00b204e9800998ecf8427e
Length = 32

Maven Dependencies

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.16.0</version>
</dependency>

Maven Central

How do I calculate the MD5 digest of a string?

In this post you will learn how to calculate the MD5 digest of a string. One of the most commonly use for this functionality in an application is to secure a password. For security reasons, you will never want to store user passwords in the application database in a plain text. There are other more secure hash algorithm out there such as the SHA-1 (Secure Hash Algorithm) but the MD5 message digest offer a faster implementation compared to SHA-1.

You can calculate the MD5 digest using the message digest library provided by the Java Standard Edition library, but the Apache Commons Codec library gives you a simple and easy to use API for generating the MD5 hash. On the example below you will see how to generate to hash to secure a password and also to generate the hash for a longer text. The text is what you might want to send to a friend via an email. To make sure that your friend receive your original message without any modification you can send the generated hash in separated email that can be used to verify the message.

package org.kodejava.commons.codec;

import org.apache.commons.codec.digest.DigestUtils;

public class MD5HashDemo {
    public static void main(String[] args) {
        // Calculates the MD5 digest for the password text and returns
        // the value as a 32 character hex string.
        String password = "s3cretw0rd**";
        String digest = DigestUtils.md5Hex(password);

        // Prints the plain text password, the digest and the length of
        // the digest.
        System.out.println("Password        = " + password);
        System.out.println("Password Digest = " + digest);
        System.out.println("Length          = " + digest.length());

        // Calculates the MD5 digest for the long texts.
        String md5 = """
                The MD5 message-digest algorithm is a formerly \
                widely used cryptographic hash function that produces \
                a 128-bit (16-byte) hash value. Specified in RFC 1321, \
                MD5 has been utilized in a wide variety of security \
                applications, and is also commonly used to check data \
                integrity. MD5 was designed by Ron Rivest in 1991 to \
                replace an earlier hash function, MD4. An MD5 hash value \
                is typically expressed as a hexadecimal number, 32 \
                digits long.
                """;
        String fingerprint = DigestUtils.md5Hex(md5);

        // Prints the text, the fingerprint and the length of the
        // digest / fingerprint.
        System.out.println("Text            = " + md5);
        System.out.println("Fingerprint     = " + fingerprint);
        System.out.println("Length          = " + fingerprint.length());
    }
}

As can be seen in the code example above, we use the DigestUtils.md5Hex() method to generate the MD5 digest. This class is part of the Apache Commons Codec under the org.apache.commons.codec.digest package. The method is a static method, so we don’t need to create an instance of the class before we can utilize the method. The md5Hex() method takes a string argument and produce a 32 characters hex string. The length will always 32 characters regardless the length of the processed text / string.

Besides, accepting a string argument, the overload version of the DigestUtils.md5Hex() method can accept an array of byte or a java.io.InputStream object as the argument.

Here is an example of the output produces:

Password        = s3cretw0rd**
Password Digest = 203c603a7330ab3ea032f4b9f140cf95
Length          = 32
Text            = The MD5 message-digest algorithm is a formerly widely used cryptographic hash function that produces a 128-bit (16-byte) hash value. Specified in RFC 1321, MD5 has been utilized in a wide variety of security applications, and is also commonly used to check data integrity. MD5 was designed by Ron Rivest in 1991 to replace an earlier hash function, MD4. An MD5 hash value is typically expressed as a hexadecimal number, 32 digits long.

Fingerprint     = a1e848ba8024fd5e38f567c107f0f4d2
Length          = 32

Maven Dependencies

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.16.0</version>
</dependency>

Maven Central

Calculate elapsed time using Apache Commons Lang StopWatch

You need to calculate the timing or elapsed time of your code execution, so you know how long a particular method or some block of code take to finish its execution. You can do this by capturing the start-time and the end-time using System.currentTimeMillis() and find their differences. Another way is to use the StopWatch class from the Apache Commons Lang library. The StopWatch class can be found in the org.apache.commons.lang3.time package.

The simplest steps to use the StopWatch is to create an instance of the StopWatch class, start the stopwatch by calling the start() method. After the stopwatch is started you can execute the target method or block of code you want to watch and call the stop() method to complete the timing session. To get the time of the stopwatch, you can call the getTime() method.

Now, let’s see the code for the process described above.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.time.StopWatch;

public class StopWatchExample {
    public static void main(String[] args) {
        StopWatchExample demo = new StopWatchExample();
        demo.timingOne();
    }

    private void timingOne() {
        // Create an instance of StopWatch.
        StopWatch stopWatch = new StopWatch();

        // Start the watch, do some task and stop the watch.
        stopWatch.start();
        doSomeTask(5000);
        stopWatch.stop();

        // Print out the total time of the watch
        System.out.println("Time: " + stopWatch.getTime());
    }

    private void doSomeTask(long sleep) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Here is the output of the code above:

Time: 5000

Besides doing a simple timing calculation using the start() and stop() followed by the getTime() methods, the StopWatch class also provides methods for splitting the time, suspend and resuming the stopwatch. You can use the split(), suspend() and resume() method respectively. To get the split time you can call the toSplitString() method.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.time.StopWatch;

public class StopWatchAnotherExample {
    public static void main(String[] args) {
        StopWatchAnotherExample demo = new StopWatchAnotherExample();
        demo.timingTwo();
    }

    private void timingTwo() {
        // Create an instance of StopWatch and start the stopwatch.
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();

        // Do some task and split the stopwatch time.
        doSomeTask(3000);
        stopWatch.split();
        System.out.println("Split 1: " + stopWatch.toSplitString());

        // Suspend the stopwatch and resume the stopwatch.
        stopWatch.suspend();
        doSomeTask(4000);
        stopWatch.resume();

        // Do some task and split the stopwatch time.
        doSomeTask(2500);
        stopWatch.split();
        System.out.println("Split 2: " + stopWatch.toSplitString());

        // Do some task and split the stopwatch time.
        doSomeTask(1000);
        stopWatch.split();
        System.out.println("Split 3: " + stopWatch.toSplitString());

        // Stop the stopwatch and the total execution time.
        stopWatch.stop();
        System.out.println("Time: " + stopWatch.getTime());
    }

    private void doSomeTask(long sleep) {
        try {
            Thread.sleep(sleep);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The code snippet above will output something like this:

Split 1: 00:00:03.004
Split 2: 00:00:05.518
Split 3: 00:00:06.522
Time: 6522

Another method that you can find in the StopWatch class is the getStartTime() which will return the stopwatch start time. The reset() method will reset the stopwatch. To remove a split, you can call the unsplit() method.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I clone an array variable?

You have an array variable, and you want to make a clone of this array into a new array variable. To do this, you can use Apache Commons Lang ArrayUtils.clone() method. The code snippet below demonstrates the cloning of a primitive array that contains some integer elements in it.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class PrimitiveArrayClone {
    public static void main(String[] args) {
        int[] fibonacci = new int[]{1, 1, 2, 3, 5, 8, 13, 21, 34, 55};
        System.out.println("fibonacci = " + ArrayUtils.toString(fibonacci));

        int[] clone = ArrayUtils.clone(fibonacci);
        System.out.println("clone = " + ArrayUtils.toString(clone));
    }
}

The fibonacci array contents were cloned into the clone array, and we print out the content using ArrayUtils.toString() method.

fibonacci = {1,1,2,3,5,8,13,21,34,55}
clone = {1,1,2,3,5,8,13,21,34,55}

In the code snippet above the clone() method create a reference to a new array. The clone() method itself doesn’t change the original array. In addition to clone primitive arrays, the clone() method also work for cloning an array of objects.

As an example we will create an array of String objects and clone it using the ArrayUtils.clone() method. To display the contents of the array, we will again use the ArrayUtils.toString() method.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ObjectArrayClone {
    public static void main(String[] args) {
        String[] colors = new String[]{"Red", "Green", "Blue", "Yellow"};
        System.out.println("colors = " + ArrayUtils.toString(colors));

        String[] clone = ArrayUtils.clone(colors);
        System.out.println("clone = " + ArrayUtils.toString(clone));
    }
}

And here is the result:

colors = {Red,Green,Blue,Yellow}
clone = {Red,Green,Blue,Yellow}

The only different between cloning a primitive array and object array using the ArrayUtils.clone() method is that when cloning an object such as String, Date, etc. we need to cast the result of the clone() method into the targeted object type.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central

How do I print the contents of an array variable?

You need to print the contents of an array variable. The long way to it is to user a loop to print each element of the array. To simplify this, you can use the Apache Commons Lang ArrayUtils.toString() method. This method can take any array as a parameter and print out the contents separated by commas and surrounded by curly brackets. When you need to print a specific string when the array is null, you can provide the second string argument to this method.

package org.kodejava.commons.lang;

import org.apache.commons.lang3.ArrayUtils;

public class ArrayUtilsToString {
    public static void main(String[] args) {
        // Print an int array as string.
        int[] numbers = {1, 2, 3, 5, 8, 13, 21, 34};
        System.out.println("Numbers = " + ArrayUtils.toString(numbers));

        // Print string array as string.
        String[] grades = {"A", "B", "C", "D", "E", "F"};
        System.out.println("Grades = " + ArrayUtils.toString(grades));

        // Print a multidimensional array as string.
        int[][] matrix = {{0, 1, 2}, {1, 2, 3}, {2, 3, 4}};
        System.out.println("Matrix = " + ArrayUtils.toString(matrix));

        // Return "Empty" when the array is null.
        String[] colors = null;
        System.out.println("Colors = " + ArrayUtils.toString(colors, "None"));
    }
}

The output of the code snippet above:

Numbers = {1,2,3,5,8,13,21,34}
Grades = {A,B,C,D,E,F}
Matrix = {{0,1,2},{1,2,3},{2,3,4}}
Colors = None

If you are using the JDK 1.5, or later, you can actually use the java.util.Arrays class to do the same thing as the org.apache.commons.lang.ArrayUtils class does.

Maven Dependencies

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-lang3</artifactId>
    <version>3.13.0</version>
</dependency>

Maven Central