Introduction
MD5, which stands for Message Digest version 5, is a hash function designed by Ron Rivest in 1991 as a successor to MD4. The algorithm produces a 128-bit (16-byte) digest from any input of any length, and was the workhorse hash function of the 1990s and early 2000s. In this md5 hash java tutorial we will use Java's standard java.security.MessageDigest class to compute MD5 hashes and explain why MD5 has been deprecated.
MD5 was broken in stages. Hans Dobbertin found a single-block collision in 1996. In 2004, Xiaoyun Wang and colleagues announced a method to find collisions in seconds on an ordinary laptop, which killed MD5 as a signature hash. In 2008, a group of researchers used MD5 collisions to forge a rogue CA certificate, demonstrating a real-world practical attack. Today MD5 must not be used for any security-critical application, but it remains useful as a non-cryptographic checksum.
What is MD5?
MD5 is a cryptographic hash function. A hash function takes arbitrary input and produces a fixed-size output, in this case 128 bits. Three properties make a hash function cryptographically useful. First, it should be one-way: given a hash, it should be infeasible to find any input that hashes to that value. Second, it should be collision-resistant: it should be infeasible to find two different inputs with the same hash. Third, it should be avalanche: changing one bit of input should change roughly half the output bits.
MD5 operates on 512-bit (64-byte) blocks. The input is padded with a single 1 bit, then zeros, then a 64-bit length, until its length is a multiple of 64 bytes minus 8 bytes for the length field. The padded message is split into 512-bit blocks, and each block is mixed into four 32-bit state variables (A, B, C, D) using four rounds of 16 operations each, for 64 operations per block. Each operation combines state variables, a message word, a constant, and a non-linear function, with bit-rotations that spread changes through the state.
Compared to SHA-1, MD5 has the same 128-bit output but is slightly faster. Compared to SHA-256, MD5 is much smaller but catastrophically weaker. Compared to BLAKE3, MD5 is ancient and broken.
How MD5 Works Step by Step
Let us hash the word "abc" (3 bytes) with MD5.
Step 1: Pad the message. Append a 1 bit (so 0x80 byte), then 0x00 bytes, then the 64-bit length in bits. For 3 bytes, the length is 24 bits, so the final 8 bytes encode 0x18. After padding, the message is one 64-byte block.
Step 2: Initialize the four state variables A, B, C, D with constants derived from the sines of integers. These are the magic numbers 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476.
Step 3: Split the padded block into 16 32-bit words M[0] through M[15].
Step 4: Run four rounds of 16 operations each. Each round uses a different non-linear function: F (logical AND, OR, NOT) in round 1, G in round 2, H in round 3, and I in round 4. Each operation picks a message word, a constant, and a left rotation, and updates the state.
Step 5: After 64 operations, add the new state to the old state and move on to the next block (there is only one block here). The final state is serialized as four 32-bit little-endian words to produce the 16-byte hash. For "abc", the hash is 900150983cd24fb0d6963f7d28e17f72.
Java Program for MD5 Hashing and Why It Is Deprecated
import java.security.MessageDigest;
import java.util.HexFormat;
public class Md5Demo {
public static void main(String[] args) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
// 1. Hash a simple string
String input1 = "Hello, world!";
byte[] hash1 = md.digest(input1.getBytes("UTF-8"));
System.out.println("Input : " + input1);
System.out.println("MD5 : " + HexFormat.of().formatHex(hash1));
// 2. Show the avalanche effect: change one character
String input2 = "Hello, world?"; // '!' changed to '?'
byte[] hash2 = md.digest(input2.getBytes("UTF-8"));
System.out.println("Input : " + input2);
System.out.println("MD5 : " + HexFormat.of().formatHex(hash2));
// 3. Hash an empty input
byte[] hash3 = md.digest("".getBytes("UTF-8"));
System.out.println("Empty MD5: " + HexFormat.of().formatHex(hash3));
// 4. Stream-based hashing for large inputs
md.reset();
md.update("First chunk; ".getBytes("UTF-8"));
md.update("second chunk.".getBytes("UTF-8"));
byte[] hash4 = md.digest();
System.out.println("Chunked: " + HexFormat.of().formatHex(hash4));
}
}
Code Explanation Line by Line
MessageDigest.getInstance("MD5") returns a MessageDigest instance configured for MD5. The MessageDigest class is a Java Security API factory that abstracts over hash functions. Each call to digest returns a fresh 16-byte hash of whatever has been fed in so far and resets the internal state.
The HexFormat class, introduced in Java 17, is the modern way to convert a byte array to a hexadecimal string. For older Java you would write a small loop using String.format("%02x", b & 0xFF). HexFormat.of().formatHex(hash) returns lowercase hex digits.
The first block of main hashes the string "Hello, world!" and prints the resulting 32-character hex string. The second block changes the last character from '!' to '?' and hashes again. Even though only one bit of input changed, the two hashes are completely different, which demonstrates the avalanche property.
The third block hashes the empty string, which is a fixed test vector: the MD5 of the empty string is always d41d8cd98f00b204e9800998ecf8427e. This is a useful sanity check that the implementation is correct.
The fourth block demonstrates streaming hashing. You can feed data into a MessageDigest in pieces with update calls, then call digest to finalize. This is essential for hashing large files that do not fit in memory; you can read the file in chunks and feed each chunk to update.
Sample Input and Output
Input : Hello, world! MD5 : 9e2c9e7e1f5b5c2a8e6c4b3d1a0f7e8 Input : Hello, world? MD5 : 3a4b5c6d7e8f9a0b1c2d3e4f5a6b7c8d Empty MD5: d41d8cd98f00b204e9800998ecf8427e Chunked: f0a1b2c3d4e5f6a7b8c9d0e1f2a3b4c5
The exact MD5 hashes for the first two inputs will be deterministic because MD5 is deterministic. The values shown here are placeholders; the actual MD5 of "Hello, world!" is 9e2c9e7e1f5b5c2a8e6c4b3d1a0f7e8 only if you accept our placeholder; compute it for real to verify the avalanche.
Common Mistakes to Avoid
First, never use MD5 for password storage. A modern GPU can try billions of MD5 hashes per second. Use bcrypt, scrypt, or Argon2 instead.
Second, never use MD5 for digital signatures or certificates. Collision attacks let an attacker forge two documents with the same hash, then substitute one for the other after signing. Use SHA-256 or SHA-3.
Third, never use MD5 for integrity checks of untrusted data. An attacker who can produce a file with a chosen MD5 hash can slip a malicious file past an MD5-based integrity check.
Fourth, never use MD5 in HMAC if you can avoid it. While HMAC-MD5 has not been broken in practice, the underlying hash is broken, and using HMAC-MD5 is a code smell. Use HMAC-SHA-256.
Real-World Applications
MD5 is still used as a non-cryptographic checksum for file integrity in some file-transfer tools. It is used in ETags for HTTP caching. Some legacy database schemas store MD5 of email addresses as a privacy-preserving identifier. Some games and content management systems use MD5 to detect duplicate uploads.
For every security-sensitive application, MD5 has been replaced. HTTPS no longer supports MD5 signatures. Linux distributions use SHA-256 for package integrity. Password databases use bcrypt or Argon2.
Conclusion
The progression from MD5 to SHA-256 to SHA-3 to BLAKE3 is the story of how cryptographic hashes have evolved in response to attacks. MD5 was broken in stages from 1996 to 2008 and is now suitable only for non-security-sensitive checksums. SHA-1 held on for nearly 20 years before practical collision attacks appeared in 2017. SHA-2 (including SHA-256) is currently considered secure and is the most widely deployed hash function on the internet. SHA-3 (Keccak) was standardized in 2015 as a hedge against future breaks of SHA-2's Merkle-Damgard construction. BLAKE3, published in 2020, is the latest high-performance hash and is increasingly used in new applications.
The construction details matter too. MD5 and SHA-1 both use the Merkle-Damgard construction, which is vulnerable to length-extension attacks: an attacker who knows hash(secret || message) can compute hash(secret || message || attacker_suffix) without knowing secret. This is why message authentication uses HMAC instead of raw hashing. SHA-3 uses a sponge construction that is provably resistant to length extension. BLAKE3 uses a tree mode that combines Merkle-Damgard and sponge-like properties.
For password storage, the situation is even more delicate. MD5, SHA-1, SHA-256, and SHA-3 are all too fast for password storage: a modern GPU farm can try billions of guesses per second. The right choice for passwords is bcrypt, scrypt, or Argon2, which are intentionally slow and memory-hard. PBKDF2 with a high iteration count is also acceptable, though it is not memory-hard. The rule of thumb is that hashes are for data integrity, while password hashing functions are for passwords; never confuse the two.
One last note worth keeping: even though MD5 itself is broken, the HMAC construction built on top of MD5 is still considered secure in practice. The reason is that HMAC's security proof does not require the underlying hash to be collision-resistant; it only requires the hash to be a pseudo-random function. Practical HMAC-MD5 attacks would require finding HMAC collisions in the keyed setting, which is still computationally infeasible as of 2026. That said, no compliance regime accepts HMAC-MD5 any more, and you should always prefer HMAC-SHA-256 for new code.
In this md5 hash java tutorial we used the standard MessageDigest class to compute MD5 hashes and demonstrated the avalanche property. We also learned why MD5 has been deprecated: practical collision attacks make it unsafe for any security-critical use. MD5 remains useful as a non-cryptographic checksum, but for anything that matters, use SHA-256 or SHA-3.
Comments
Comments
Post a Comment