1

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

Community
  • 1
  • 1
garrettmac
  • 8,417
  • 3
  • 41
  • 60
  • Couldn't the code in the linked question do that if you added a line to pad or truncate the result to a fixed number of digits? – nnnnnn Apr 13 '17 at 03:47
  • Use a standard large-base hashing algorithm (e.g. [SHA-1](https://github.com/emn178/js-sha1)) or library and truncate? – Phrogz Apr 13 '17 at 03:48

2 Answers2

1

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.

CynicalBusiness
  • 127
  • 2
  • 12
1

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

Yeldar Kurmangaliyev
  • 33,467
  • 12
  • 59
  • 101