How to generate strings that share the same hashcode in Java?

前端 未结 6 1298
余生分开走
余生分开走 2020-12-28 10:09

An existing system written in Java uses the hashcode of a string as its routing strategy for load balancing.

Now, I cannot modify the system but ne

6条回答
  •  心在旅途
    2020-12-28 10:32

    I was wondering if there was a "universal" solution; e.g. some constant string XYZ, such that

        s.hashCode() == (s + XYZ).hashCode() 
    

    for any string s. Finding such a string involves solving a fairly complicated equation ... which was beyond my rusty mathematical ability. But then it dawned on me that h == 31*h + ch is always true when h and ch are both zero!

    Based on that insight, the following method should create a different String with the same hashcode as its argument:

        public String collider(String s) { 
            return "\0" + s;
        }
    

    If NUL characters are problematic for you, prepending any string whose hashcode is zero would work too ... albeit that the colliding strings would be longer than if you used zero.

提交回复
热议问题