• Home
  • About
  • Doom II
  • Flog
  • Inspiration

Java MD5

Posted in Computing. on Tuesday, March 11th, 2008 by Derek
Mar 11

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?
	}
}
  • Now Playing: Agalloch - The White EP - 02 - Birch Black

1 Comment

  1. fraggle on March 12th, 2008

    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.



Leave a Reply

CAPTCHA Image
Refresh Image
*

Derek MacDonald


  • Photo Stream
  • Categories
    • Australia
    • Computing
    • Film & TV
    • Food
    • Gaming
    • General
    • Music
    • Sports
    • Visual Art
  • Search






  • Home
  • About
  • Doom II
  • Flog
  • Inspiration

© Copyright Derek MacDonald. All rights reserved.
Designed by FTL Wordpress Themes brought to you by Smashing Magazine

Back to Top