-
-
Save jvarho/5c76dd5e2fc6f6728414 to your computer and use it in GitHub Desktop.
MD5 collision test
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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