I have a large json string in javascript, that I want to convert into a short hash, and this solution seems to work.
String.prototype.hashCode = function(){
var hash = 0;
if (this.length == 0) return hash;
for (i = 0; i < this.length; i++) {
char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
But is there a way I can convert this back into that json string?
I have a large json string in javascript, that I want to convert into a short hash, and this solution seems to work.
String.prototype.hashCode = function(){
var hash = 0;
if (this.length == 0) return hash;
for (i = 0; i < this.length; i++) {
char = this.charCodeAt(i);
hash = ((hash<<5)-hash)+char;
hash = hash & hash; // Convert to 32bit integer
}
return hash;
}
But is there a way I can convert this back into that json string?
Share Improve this question edited Jun 26, 2017 at 20:35 omega asked Jun 26, 2017 at 20:30 omegaomega 44.1k90 gold badges286 silver badges523 bronze badges 2- The short answer is no. Hashes do not contain the information required to reconstruct the input. – smcd Commented Jun 26, 2017 at 20:37
- It may be "possible" but you shouldn't. It's not reliable, hashing is meant to be one way. – Damon Commented Jun 26, 2017 at 20:37
2 Answers
Reset to default 4Hashes are specifically not-reversible. That is one of the main properties of them that make them useful in cryptography.
I think the question is: what are you actually trying to acplish? Because whatever it is, it sounds like a hash is not the answer.
https://en.wikipedia/wiki/Hash_function
A cryptographic hash function allows one to easily verify that some input data maps to a given hash value, but if the input data is unknown, it is deliberately difficult to reconstruct it (or equivalent alternatives) by knowing the stored hash value.
(emphasis mine)
What you want is not hashing but pression. Look for a zip module for javascript. For plain text JSON, you can probably expect pression ratios of ~90% (depending on contents). A quick google search shows that there are a million of them, so you'll have to find one that fits your specific use case.
No, there is no way to convert a hash back to the string it was created from. The purpose of a hash function is to map each long string to a shorter string--it is easy to prove that there are more long strings than short strings that can be created from existing characters.
There are multiple strings that map to each hashed string, and it is not possible to determine which string was used to create the hashed string. It is unlikely that you will ever find two strings that map to the same hash string, which is the basis of hash functions, but at the same time they do exist.
In fact, hash functions are cryptographically secure because it is not possible to determine the string a hash was created from if you only have the hash and the hash function.