Reputation: 13486
I am looking for a way to hash a user id, obtained from a 3rd party service, such that I can use the hash as a primary key.
My understanding is that the usual SHA-512
style algorithms, given an input string that is guaranteed to be unique, are not guaranteed to produce a hash value that is also guaranteed to be unique.
Is there a hashing algorithm that will produce an unique hash?
More specifically is there such an algorithm supported out of the box by NodeJS 10.9 or better
Upvotes: 2
Views: 1928
Reputation: 2918
Length of a SHA-512 hash is 64 bytes(512 bits) long which gives you 10154 combinations of values. So it has a very less (i mean a very very less ) chance of getting same hash.
How much very less it is, think of the weight of the sun from grams (which is weigh million times like the earch). If any other planet weight 10154 of grams, not even a millions of millions suns combined can be equals to that amount.
So by very less, it means never. Even the bitcoin addresses are using this method as the wallet address. If you by any chance can find that one combination, you will be a billionaire. I promise
Upvotes: 2
Reputation: 3247
Most hashing algorithms are doing their best to avoid collisions. SHA 512 ought to be fine for you, if not SHA 256. Note that if you can see collisions in the input data, there will be collisions in the hashes, in which case I recommend appending something else likely unique to two separate accounts - such as the timestamp they were created - before inputting the value into the hash. This will work just fine so long as both inputs are immutable and they never change on the account.
You can use crypto.getHashes()
to view available hashes and pick the one you want. You are asking after uniqueness and not security so faster is better.
This answer is also related: When using SHA-256 hashes as a primary key, is it OK to ignore the possibility of collisions?
Upvotes: 1