Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java recreate string from hashcode

Is there any way that I can use a hashcode of a string in java, and recreate that string?

e.g. something like this:

String myNewstring = StringUtils.createFromHashCode("Hello World".hashCode());
if (!myNewstring.equals("Hello World"))
    System.out.println("Hmm, something went wrong: " + myNewstring);

I say this, because I must turn a string into an integer value, and reconstruct that string from that integer value.

like image 795
Richard J. Ross III Avatar asked Feb 02 '23 17:02

Richard J. Ross III


2 Answers

This is impossible. The hash code for String is lossy; many String values will result in the same hash code. An integer has 32 bit positions and each position has two values. There's no way to map even just the 32-character strings (for instance) (each character having lots of possibilities) into 32 bits without collisions. They just won't fit.

If you want to use arbitrary precision arithmetic (say, BigInteger), then you can just take each character as an integer and concatenate them all together. Voilà.

like image 160
Ted Hopp Avatar answered Feb 12 '23 03:02

Ted Hopp


No. Multiple Strings can have the same hash code. In theory you could create all the Strings that have have that hash code, but it would be near infinite.

like image 26
JustinKSU Avatar answered Feb 12 '23 03:02

JustinKSU