Java MD5 Hashing Example

This Java source code example demonstrates how to secure a password using the MD5 algorithm in Java programming language.
The MD5 (Message-Digest) Algorithm is a widely used cryptographic hash function that produces a 128-bit (16-byte) hash value. It’s very simple and straight forward; the basic idea is to map data sets of variable length to data sets of a fixed length.

Java MD5 Hashing Example



public class SimpleMD5Example {
    public static void main(String[] args) {
        String passwordToHash = "test123";
        String generatedPassword = null;
        try {
            // Create MessageDigest instance for MD5
            MessageDigest md = MessageDigest.getInstance("MD5");
            // Add password bytes to digest
            // Get the hash's bytes
            byte[] bytes = md.digest();
            // This bytes[] has bytes in decimal format;
            // Convert it to hexadecimal format
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < bytes.length; i++) {
                sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
            // Get complete hashed password in hex format
            generatedPassword = sb.toString();
        } catch (NoSuchAlgorithmException e) {
        System.out.println("Generated Password => " + generatedPassword);


Generated Password => cc03e747a6afbbcbf8be7668acfebee5