Skip to content

Instantly share code, notes, and snippets.

@jvarho jvarho/HashCodeUtil.java Secret
Last active Aug 29, 2015

Embed
What would you like to do?
MD5 collision test
import java.security.MessageDigest;
import java.util.HashMap;
public class HashCodeUtil {
private static HashMap<String,String> collisionMap ;
public static String getHashcode(String input) {
MessageDigest hasher = null;
try {
hasher = MessageDigest.getInstance("MD5");
//hasher = MessageDigest.getInstance("SHA-256");
} catch (Exception e) {
System.out.println("Could not get MD5 Hasher for calculating hashcodes:" + e.getMessage());
return null;
}
hasher.update(input.getBytes());
byte[] buffer = hasher.digest();
int[] intVal = new int[4];
for (int i=0, j = 0; j < 16; i++, j += 4) {
intVal[i] = ((int) (buffer[j] & 0xff)) +
(((int) (buffer[j + 1] & 0xff)) << 8) +
(((int) (buffer[j + 2] & 0xff)) << 16) +
(((int) (buffer[j + 3] & 0xff)) << 24);
}
int hashInt = intVal[0] ^ intVal[1] ^ intVal[2] ^ intVal[3];
if (hashInt == 0) {
hashInt = 0xFFFFFFFF;
}
return"0x" + Integer.toHexString(hashInt);
}
public static void main(String[] args) {
int sum = 0;
for (int j = 0; j < 100; j++) {
HashMap<String,String> collisionMap = new HashMap<String, String>(70000);
for (int i = 0; i < 100000000; i++) {
String input = "Hello"+i+","+j;
String hash = getHashcode(input);
if(collisionMap.get(hash) == null) {
collisionMap.put(hash,input);
} else {
System.out.println(input + "," +collisionMap.get(hash) + "," + i );
sum += i;
break;
}
}
}
System.out.println(sum / 100. + " iterations on average");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.