garrettmac
garrettmac

Reputation: 8585

javascript - generate reproducible hash (5-10 characters) from various sized strings

Take this stackoverflow question:

Generate a Hash from string in Javascript/jQuery

I'd like to do exactly that, however I'd like to generate the same sized hash no matter what size string is used to generate the hash.

For instance take the following

  function genorateHash(string){
       ...do something...
       return hash
 }

  genorateHash("hello")                   output >> "3NCI4KSI"
  genorateHash("THIS IS A LONGER STING")  output >> "4J4IXYEK"
  genorateHash("hello")                   output >> "3NCI4KSI" (Notice "hello" regenerates the same hash every time.)

Notice "hello" regenerates the same hash every time.

How can this be accomplished?

(I understand it's unlikely to generate the same hash, it something like 8^n?)


Also Im working with nodeJS and I haven't seen any npm packages that accomplish this:

https://www.npmjs.com/package/id-generator

https://www.npmjs.com/package/shortid

Thanks

Upvotes: 1

Views: 4692

Answers (2)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34199

You can generate any hash (MD5, SHA) and take its first 8 symbols. It will guarantee that the same input will produce the same 8-symbol string.
Note that whatever hash or algorithm you use, the entropy will be dramatically reduced and the chance of collisions will be pretty high, therefore this hash cannot be used for security purposes anymore.

MD5 / SHA hashes can be generated using different packages:
https://www.npmjs.com/package/crypto-js
https://www.npmjs.com/package/sha1

Upvotes: 1

CynicalBusiness
CynicalBusiness

Reputation: 127

If the length of 8 is not important, the md5 and sha1 algorithms are rather widely used. If you must have that length, I believe crc32 is 8 characters.

Upvotes: 1

Related Questions