0
0

More than 3 years have passed since last update.

All same hash code string in Java

Posted at

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百万回ループ
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();

参考サイト:
https://stackoverflow.com/questions/8669946/application-vulnerability-due-to-non-random-hash-functions

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0