I was tasked with writing a Java app with client-side authentication, with the ability to save the login information. So I needed to encode the password when saving the configuration to disk and also before sending login credentials through HTTPS. You think getting that information is a simple one line method call to a Java API? Hells no.

I obviously started via Google search, trying one of the first MD5 implementation results using Java’s MessageDigest class. This code is just wrong. I came across a couple strings that weren’t encoded to the same hexadecimal as MySQL’s md5() function. A couple entries down in Google’s search return was a more concise chunk of MD5 code. However, there was still an issue since its returned string wasn’t a 32 character length string that could be used to compare against a MySQL md5() password column. Here’s a proper method, with left zero padding:

public static String getPasswordEncrypted(String password)
    try {
        MessageDigest algorithm = MessageDigest.getInstance("MD5");
        algorithm.update(password.getBytes(), 0, password.length());

        BigInteger encryptedBytes = new BigInteger(1, algorithm.digest());

        // 16 -> hexidecimal notation
        String encryptedPassword = encryptedBytes.toString(16);

        // padding left zeroes for 32 length string
        if (encryptedPassword.length() < 32) {
            for (int i = encryptedPassword.length(); i < 32; i++) {
                encryptedPassword = "0" + encryptedPassword;

        return encryptedPassword;
    } catch (NoSuchAlgorithmException e) {
        return ""; // eh?