Published on

Java Security - Part 6: Hashing and message digest algorithms in Java (e.g., MD5, SHA-256)

Authors

Yarr mateys! Gather round, as we plunge into the murky depths of Hashing Bay and the Message Digest Caves. Here, we will encounter two of the most elusive and cryptic creatures of the Java Sea - MD5 and SHA-256!

The magic of the hashing spell is its ability to turn any message into a fixed size string of characters, regardless of the message's original size. The output, or digest, is unique to each unique input message. Change one character of the message, and the entire digest changes! Hashing is like a magical spell that turns a treasure chest full of gold into a single precious gemstone.

Here be some examples of our magical spells in action:

import java.security.MessageDigest;
import javax.xml.bind.DatatypeConverter;

public class HashingSample {
    public static void main(String[] args) throws Exception {
        // The secret message
        String message = "Arr, treasure ahead!";

        // Apply the MD5 spell
        MessageDigest md5Digest = MessageDigest.getInstance("MD5");
        byte[] md5Hash = md5Digest.digest(message.getBytes());
        System.out.println("MD5 Hash: " + DatatypeConverter.printHexBinary(md5Hash));

        // Apply the SHA-256 spell
        MessageDigest sha256Digest = MessageDigest.getInstance("SHA-256");
        byte[] sha256Hash = sha256Digest.digest(message.getBytes());
        System.out.println("SHA-256 Hash: " + DatatypeConverter.printHexBinary(sha256Hash));
    }
}

Beware though, mateys, while MD5 is as quick as a gull diving for a fish, it has been broken by nefarious pirates! SHA-256, on the other hand, is as secure as a lock on Davy Jones' Locker, but it takes a bit more time to compute.

Remember, while the hashing spell is irreversible (you can't turn your gemstone back into a chest full of gold), it's not safe from all threats. If a scurvy dog knows the spell you've used, they can still try every possible message until they find one that produces the same hash. This is known as a brute force attack.

Our next adventure awaits, mateys. Next, we be learning about digital signatures, the magical seal that proves the authenticity and integrity of a message! Hoist the anchor and prepare to set sail! Yarr!