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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | public static String getPasswordEncrypted(String password) { try { MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); 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? } } |

Java is horrible. I seem to remember doing MD5 stuff with it in the past and one of the functions, instead of returning the string with the result I expected, returned a string containing “this function is not implemented yet” or something similar.