All same hash code string in Java
final String p1 = "AaBB";
final String p2 = "BBAa";
final String p3 = "BBBB";
final String[] pp = new String[] { p1, p2, p3 };
final int ppLength = pp.length;
Random random = new Random();
random.setSeed(System.currentTimeMillis());
final int size = 10;
final int length = size * 4;
final int times = 2_000_000; //n million loops
Map<String, String> map = new HashMap<>(10000);
File file = new File("r:/1.txt");
file.delete();
BufferedWriter bw = new BufferedWriter( //
new OutputStreamWriter( //
new FileOutputStream(file, true) // append
, Charset.forName("UTF-8") // charset
) //
, 1024 // buffer size
);
StringBuffer sb = new StringBuffer(length);
for (int ii = 0; ii < size; ii++) {
sb.append(pp[random.nextInt(ppLength)]);
}
final int hashCode = sb.toString().hashCode();
sb.setLength(0);
for (int count = 0; count < times; count++) {
for (int ii = 0; ii < size; ii++) {
sb.append(pp[random.nextInt(ppLength)]);
}
String ss = sb.toString();
if (!map.containsKey(ss)) {
if (ss.hashCode() != hashCode) {
bw.flush();
bw.close();
throw new RuntimeException("hashCode not equal");
}
map.put(ss, ss);
bw.append(ss);
bw.newLine();
}
sb.setLength(0);
}
System.out.println(map.size());
bw.flush();
bw.close();
Reference site: https://stackoverflow.com/questions/8669946/application-vulnerability-due-to-non-random-hash-functions
Recommended Posts