Hi guys, I've been working with some people and they needed a basic md5 encryption of a number (plus a salt) to authenticate our users with their system.
So I quickly Googled md5 encryptions in java and I got the below code
java Code:
String sessionid = valueSentIn + "saltvalue"; byte[] defaultBytes = sessionid.getBytes(); MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(defaultBytes); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i=0;i<messageDigest.length;i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString();
The above code works about 50% of the time. The other 50% of the time, it trims out a random 0 somewhere in the output. The 0 can be anywhere and I wasn't able to find anything on Googling the error.
The representative I talked to (I had assumed the error was on their end, and the information was missing from their system) had mentioned that Java had a flaw with md5 that they knew about. The code they proposed I use is below.
java Code:
String sessionid = valueSentIn + "saltvalue"; MessageDigest md; md = MessageDigest.getInstance("MD5"); md.update(sessionid.getBytes()); return convertToHex(md.digest());
java Code:
public static String convertToHex(byte[] data) { StringBuffer buf = new StringBuffer(); for (int i = 0; i < data.length; i++) { int halfbyte = (data[i] >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) buf.append((char) ('0' + halfbyte)); else buf.append((char) ('a' + (halfbyte - 10))); halfbyte = data[i] & 0x0F; } while(two_halfs++ < 1); } return buf.toString(); }
The only thing I can find that is different is that the 2nd set of code seems to be looking for a "halfbyte."
I was hoping someone here could explain to me, in a little more detail:
#1 why the first code stripped out the random value
and
#2 what the major difference between the code is
Any information at all would be extremely helpful.


Reply With Quote