Information Security 12 min read

How to Compute an MD5 Hash of a String in Java Using MessageDigest

This article explains how to generate an MD5 hash for a string in Java with the java.security.MessageDigest class, provides a complete example program, details each step of the MD5 algorithm, and describes the core methods and internal workings of MessageDigest for cryptographic hashing.

Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
Rare Earth Juejin Tech Community
How to Compute an MD5 Hash of a String in Java Using MessageDigest

In Java, generating an MD5 hash of a string is straightforward using the java.security.MessageDigest class. The following example demonstrates a complete program that computes the MD5 hash of a given string.

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

public class MD5Example {
    public static String getMD5(String input) {
        try {
            // Obtain a MessageDigest instance for MD5
            MessageDigest md = MessageDigest.getInstance("MD5");
            // Update the digest with the input bytes
            md.update(input.getBytes());
            // Compute the hash
            byte[] digest = md.digest();
            // Convert the byte array to a hexadecimal string
            StringBuilder hexString = new StringBuilder();
            for (byte b : digest) {
                String hex = Integer.toHexString(0xff & b);
                if (hex.length() == 1) {
                    hexString.append('0'); // pad with leading zero
                }
                hexString.append(hex);
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        String text = "Hello, World!";
        String md5Hash = getMD5(text);
        System.out.println("MD5 Hash of " + text + ": " + md5Hash);
    }
}

Code Explanation

MessageDigest instantiation : MessageDigest.getInstance("MD5") returns a MessageDigest object that supports the MD5 algorithm.

Updating data : md.update(input.getBytes()) feeds the input bytes into the digest.

Computing the hash : md.digest() performs the final compression and returns the raw 16‑byte MD5 value.

Byte‑to‑hex conversion : A StringBuilder iterates over each byte, converting it to a two‑character hexadecimal representation.

Exception handling : NoSuchAlgorithmException is unlikely because MD5 is a standard algorithm, but it is caught and re‑thrown as a runtime exception.

Detailed MD5 Process

The MD5 algorithm works as follows:

Initialization : Four 32‑bit buffers (A, B, C, D) are set to predefined constants.

Data input : The message is padded so its length (in bits) is congruent to 448 modulo 512, then the original length is appended as a 64‑bit value.

Processing each 512‑bit block : The block is divided into sixteen 32‑bit words X[0..15]. A 64‑round compression function updates the buffers using non‑linear functions F, G, H, I, a constant table K[i] and shift amounts s[i].

Output : After all blocks are processed, the buffers A, B, C, D are concatenated to produce the final 128‑bit hash, usually rendered as a 32‑character hexadecimal string.

for each 512‑bit block {
    divide block into 16 words X[0..15]
    // Initialize hash values for this chunk
    A = a0; B = b0; C = c0; D = d0;
    // Main loop
    for i from 0 to 63 {
        // Determine function F and index g based on i
        // Perform modular addition and left‑rotate
        B = B + leftrotate(F + A + K[i] + X[g], s[i]);
        // Rotate registers
        A = D; D = C; C = B;
    }
    // Add this chunk's hash to result so far
    a0 += A; b0 += B; c0 += C; d0 += D;
}

Core MessageDigest API

MessageDigest.getInstance(String algorithm) – returns an implementation for the specified algorithm (e.g., MD5, SHA‑256).

update(byte[] input) – feeds data into the digest; can be called multiple times for large inputs.

digest() – finalizes the computation and returns the hash bytes, resetting the internal state.

digest(byte[] input) – convenience method that hashes a single byte array in one call.

reset() – restores the MessageDigest to its initial state for reuse.

clone() – creates a copy of the current MessageDigest instance when the implementation supports it.

Working Mechanism

Initialization and instance acquisition : getInstance looks up a provider that implements the requested algorithm.

Data processing : Calls to update accumulate input bytes; the implementation handles buffering and chunking.

Hash calculation : digest performs the final padding, processes any remaining data, runs the compression function, and produces the fixed‑size output.

State management : reset clears the internal buffers so the same MessageDigest object can be reused.

Digest Method Internals (illustrative)

public byte[] digest() {
    // Calls the engine‑specific implementation
    return engineDigest();
}

In OpenJDK’s SHA‑256 implementation, engineDigest() performs padding, processes the final block, converts the internal state to a byte array, and then resets the state.

protected byte[] engineDigest() {
    padBuffer();
    processLength(currentLength);
    byte[] result = new byte[HASH_SIZE];
    intToBytes(state, result, 0);
    resetState();
    return result;
}

Both MD5 and SHA‑256 share the same overall pattern: initialize buffers, absorb data in 512‑bit blocks, apply a compression loop, and output the final digest.

In summary, the MessageDigest class provides a high‑level API for cryptographic hash functions, handling algorithm selection, data feeding, padding, compression, and state reset, while the underlying implementations perform the low‑level bitwise operations that guarantee the security and correctness of the resulting hash.

Javainformation securityHashingMD5cryptographyMessageDigest
Rare Earth Juejin Tech Community
Written by

Rare Earth Juejin Tech Community

Juejin, a tech community that helps developers grow.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.