Click here to Skip to main content
15,881,044 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Java
<pre>
public int hashKey(String str){
		int sum = 0;
		int exp = 1;
		for(int i = 0; i < str.length(); i++){
			int temp = str.charAt(i) * exp;
			sum += temp;
			exp *= 26;
		}
		
		return sum % 10;
}


What I have tried:

I have the code above which gives me the hash key for a word.
<<< I will assume that the ascii code for a=1 , b=2 , c=3 >>>

for example if I inserted the word "abc" the output will be 214%10 = 4

How can I get the first letter of this word "abc" without changing anything in the function
Posted
Updated 11-Apr-20 22:01pm
Comments
Richard MacCutchan 12-Apr-20 4:32am    
It should be obvious that given the number 4, you cannot guess that it is the hash of "abc". It could equally be the hash of many more strings.

You can't reverse hashing functions: they are not a form of encryption.
That's why hashes are always the same length regardless of the input length: they throw away information in order to generate a (hopefully) unique value from the input.

Encryption doesn't do that: so the size of encrypted data is both variable and often larger than the input data - it is not possible to create a fixed size output from an encryption function without padding it out to a specified length - and even then if the input exceeds that length, it will still require more space for the encrypted version.

Think about it: suppose your hash is "add them all together and take the remainder when divided by ten" Since there are only 10 possible results - 0 to 9 inclusive - you cannot tell from the result of 7 if the input was 7, 17, [1, 6], [2, 5], Or a massive set of other possible values.

[edit]
I thought I'd written up something about hash reversing ... and I had: Decrypting MD5 and SHA: Why You Can't Do It[^] - clearly, it's based around more complex hashes than yours, but it still applies and covers the "why" better than my comments above.
[/edit]
 
Share this answer
 
v2
Quote:
How to reverse a hashing function.

Short answer: you can't.
By design, a hash function can not be reversed.
See your code, for any string as input, there is only 10 different output.
Quote:
<<< I will assume that the ascii code for a=1 , b=2 , c=3 >>>

By the way, your code is wrong because a=97 , b=98 , c=99.
Quote:
How can I get the first letter of this word "abc" without changing anything in the function

Java
hashKey("a") == hashKey("k") == hashKey("u") == 7

from 7, how to choose between 'a', 'k' or 'u' ?
 
Share this answer
 
v2
Comments
Patrice T 18-Apr-20 2:02am    
Ok, and what does it means ?

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900