Search code examples
javahashcode

Finding a String with the same hashcode() value as given String


I'm trying to find a string that shares the same hash result as a given string.

For Example:

If I have the String 'den' and use Java's hashcode() method the hash result = 99,341

String s = "den";
System.out.println(s.hashCode());
Result = 99,341

Knowing that the hashcode() method computes

s[0]*31^(n-1) + s[1]*31^(n-2) + ... + 2[n-1]

How would I go about taking this result (99,341) and finding a string (of the same length) as 'den' with the equivalent hash value?


Solution

  • You need to solve this equation:

    (x * 31^(3-1)) + (y * 31^(3-2)) + (z * 31^(3-3)) = 99341
    

    It's a plane, every point in that plane is good for you as long as x,y,z are integers and between 0 and 255 (if you are only talking about ASCII).

    One possible solution is x=100, y=101, z=110. To simply find another one, you can just change the order of two of them and see what would be the third one, e.g.:

    x=101
    y=???
    z=110
    
    (101 * 31^(3-1)) + (y * 31^(3-2)) + (110 * 31^(3-3)) = 99341
    

    where y=70 (F) so eFn should have the same hashCode as den using the function in your question.