Implementation of the MD5 Encryption Algorithm

1. Introduction

Most projects today have high security requirements, especially financial systems, which require encrypted data transmission for inter-system interactions to ensure security. Therefore, I revisited some classic encryption algorithms. Today, I will implement a utility class for the MD5 encryption algorithm using the standard library in the Spring Security framework.

2. Overview of the MD5 Algorithm

MD5 is considered a basic encryption algorithm designed by Ronald Rivest in 1991, used to generate a 128-bit (16-byte) hash value, typically represented as a 32-character hexadecimal string. It is mainly used for data integrity verification, but due to security issues, it is no longer recommended for secure encryption scenarios.

Features:

Fixed output length: Regardless of the input length, the output is always 128 bits (32 hexadecimal characters).

For example: md5(“hello”) = 5d41402abc4b2a76b9719d911017c592

  • Irreversibility: It is theoretically impossible to reverse the hash value to obtain the original data.

  • Avalanche effect: A small change in input will result in a completely different output.

  • Compromised: MD5 has collision vulnerabilities (different inputs produce the same hash), making it insecure.

3. Initial Implementation

package com.example.springdemo.demos.a03;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/** * @author zhou * @version 1.0 * @description TODO * @date 2025/8/14 22:23 */
public class Md5 {    public static void main(String[] args) throws NoSuchAlgorithmException {        String input = "hello";        String result = Md(input);        System.out.println(result);    }    public static String Md(String input) throws NoSuchAlgorithmException {        try {            // Create MD5 hash calculator            MessageDigest md5 = MessageDigest.getInstance("Md5");            // Calculate hash value (returns byte array), resulting in a 16-byte binary hash value            byte[] bytes = md5.digest(input.getBytes());            // Convert byte array to hexadecimal string            StringBuilder stringBuilder = new StringBuilder();            for(byte b : bytes){                // Convert each byte to 2-digit hexadecimal                String hex = String.format("%02x", b);                stringBuilder.append(hex);            }            return stringBuilder.toString();        }catch (NoSuchAlgorithmException e){            throw new RuntimeException("MD5 algorithm not found", e);        }    }

Result: 5d41402abc4b2a76b9719d911017c592

4. ImprovementsImplementation (with Salt)

1. Why use Salt?

Enhancing Security

  1. Salt is a random string that is concatenated with the original data before hashing to prevent rainbow table attacks.

  2. When storing, both the salt and the hash value need to be saved, and the same salt must be used for verification.

2. Implementation

package com.example.springdemo.demos.a03;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
/** * @author zhou * @version 1.0 * @description TODO * @date 2025/8/14 22:23 */
public class Md5 {    public static void main(String[] args) throws NoSuchAlgorithmException {        String input = "hello";        String salt = generateSalt();        String result = MdWithSalt(input,salt);        System.out.println("Salt: " + salt);        System.out.println("MD5 hash with salt: " + result);    }    public static String MdWithSalt(String input,String salt) throws NoSuchAlgorithmException {        try {            // Create MD5 hash calculator            MessageDigest md5 = MessageDigest.getInstance("Md5");            md5.update(salt.getBytes());// Add salt            // Calculate hash value (returns byte array), resulting in a 16-byte binary hash value            byte[] bytes = md5.digest(input.getBytes());            // Convert byte array to hexadecimal string            StringBuilder stringBuilder = new StringBuilder();            for(byte b : bytes){                // Convert each byte to 2-digit hexadecimal                String hex = String.format("%02x", b);                stringBuilder.append(hex);            }            return stringBuilder.toString();        }catch (NoSuchAlgorithmException e){            throw new RuntimeException("MD5 algorithm not found", e);        }    }    public static String generateSalt(){        SecureRandom secureRandom = new SecureRandom();        // Create a 16-byte salt        byte[] salt = new byte[16];        secureRandom.nextBytes(salt);// Fill with random bytes        // Convert salt to Base64 string (for easy storage)        return Base64.getEncoder().encodeToString(salt);    }

Result:

Salt: 2J9Vdnrszyf9/7wJ8icYGA==MD5 hash with salt: 8185d5b1145dcc84d4e66b53340822dd

3. Will the MD5 hash results be the same for the same input twice?

Yes, as long as the input is exactly the same, the MD5 hash result will always be the same. MD5 is a deterministic algorithm, which can be verified.

  • Same input → Same output (128-bit hash value).

  • No matter how many times it is calculated, as long as the input data (including salt, encoding method, etc.) is completely consistent, the result will be consistent.

5. Conclusion

  1. Same input → Same MD5 output, this is a fundamental property of hash functions.

  2. To avoid the same input producing the same hash (such as for password storage), it is necessary to add salt.

  3. MD5 is no longer recommended for secure scenarios, and more secure algorithms (such as SHA-256) should be prioritized.

Leave a Comment