<p>What is a good Hash function? I saw a lot of hash function and applications in my data structures courses in college, but I mostly got that it's pretty hard to make a good hash function. As a rule of thumb to avoid collisions my professor said that:</p>

<pre><code>function Hash(key)
  return key mod PrimeNumber
end
</code></pre>

<p>(mod is the % operator in C and similar languages)</p>

<p>with the prime number to be the size of the hash table. I get that is a somewhat good function to avoid collisions and a fast one, but how can I make a better one? Is there better hash functions for string keys against numeric keys?</p>

[{'answer_id': 34606, 'author': 'Einar', 'author_id': 2964, 'author_profile': 'https://Stackoverflow.com/users/2964', 'pm_score': 2, 'selected': False, 'text': "<p>I'd say that the main rule of thumb is not to roll your own. Try to use something that has been thoroughly tested, e.g., SHA-1 or something along those lines.</p>\n"}, {'answer_id': 34652, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 6, 'selected': False, 'text': '<p>There\'s no such thing as a “good hash function” for universal hashes (ed. yes, I know there\'s such a thing as “universal hashing” but that\'s not what I meant). Depending on the context different criteria determine the quality of a hash. Two people already mentioned SHA. This is a cryptographic hash and it isn\'t at all good for hash tables which you probably mean.</p>\n\n<p>Hash tables have very different requirements. But still, finding a good hash function universally is hard because different data types expose different information that can be hashed. As a rule of thumb it is good to consider <em>all</em> information a type holds equally. This is not always easy or even possible. For reasons of statistics (and hence collision), it is also important to generate a good spread over the problem space, i.e. all possible objects. This means that when hashing numbers between 100 and 1050 it\'s no good to let the most significant digit play a big part in the hash because for ~ 90% of the objects, this digit will be 0. It\'s far more important to let the last three digits determine the hash.</p>\n\n<p>Similarly, when hashing strings it\'s important to consider all characters – except when it\'s known in advance that the first three characters of all strings will be the same; considering these then is a waste.</p>\n\n<p>This is actually one of the cases where I advise to read what Knuth has to say in <em>The Art of Computer Programming</em>, vol. 3. Another good read is Julienne Walker\'s <a href="http://eternallyconfuzzled.com/tuts/algorithms/jsw_tut_hashing.aspx" rel="noreferrer">The Art of Hashing</a>.</p>\n'}, {'answer_id': 34681, 'author': 'Simon Johnson', 'author_id': 854, 'author_profile': 'https://Stackoverflow.com/users/854', 'pm_score': 1, 'selected': False, 'text': '<p>A good hash function has the following properties:</p>\n\n<ol>\n<li><p>Given a hash of a message it is computationally infeasible for an attacker to find another message such that their hashes are identical.</p></li>\n<li><p>Given a pair of message, m\' and m, it is computationally infeasible to find two such that that h(m) = h(m\')</p></li>\n</ol>\n\n<p>The two cases are <em>not</em> the same. In the first case, there is a pre-existing hash that you\'re trying to find a collision for. In the second case, you\'re trying to find <em>any</em> two messages that collide. The second task is significantly easier due to the birthday "paradox."</p>\n\n<p>Where performance is not that great an issue, you should always use a secure hash function. There are very clever attacks that can be performed by forcing collisions in a hash. If you use something strong from the outset, you\'ll secure yourself against these.</p>\n\n<p>Don\'t use MD5 or SHA-1 in new designs. Most cryptographers, me included, would consider them broken. The principle source of weakness in both of these designs is that the second property, which I outlined above, does not hold for these constructions. If an attacker can generate two messages, m and m\', that both hash to the same value they can use these messages against you. SHA-1 and MD5 also suffer from message extension attacks, which can fatally weaken your application if you\'re not careful.</p>\n\n<p>A more modern hash such as Whirpool is a better choice. It does not suffer from these message extension attacks and uses the same mathematics as AES uses to prove security against a variety of attacks. </p>\n\n<p>Hope that helps!</p>\n'}, {'answer_id': 236471, 'author': 'Myrddin Emrys', 'author_id': 9084, 'author_profile': 'https://Stackoverflow.com/users/9084', 'pm_score': 3, 'selected': False, 'text': '<p>There are two major purposes of hashing functions:</p>\n\n<ul>\n<li>to disperse data points uniformly into n bits.</li>\n<li>to securely identify the input data.</li>\n</ul>\n\n<p>It\'s impossible to recommend a hash without knowing what you\'re using it for.</p>\n\n<p>If you\'re just making a hash table in a program, then you don\'t need to worry about how reversible or hackable the algorithm is... SHA-1 or AES is completely unnecessary for this, you\'d be better off using a <a href="http://isthe.com/chongo/tech/comp/fnv/" rel="noreferrer">variation of FNV</a>. FNV achieves better dispersion (and thus fewer collisions) than a simple prime mod like you mentioned, and it\'s more adaptable to varying input sizes.</p>\n\n<p>If you\'re using the hashes to hide and authenticate public information (such as hashing a password, or a document), then you should use one of the major hashing algorithms vetted by public scrutiny. <a href="http://www.larc.usp.br/~pbarreto/hflounge.html" rel="noreferrer">The Hash Function Lounge</a> is a good place to start.</p>\n'}, {'answer_id': 626599, 'author': 'Nick Van Brunt', 'author_id': 30470, 'author_profile': 'https://Stackoverflow.com/users/30470', 'pm_score': 3, 'selected': False, 'text': '<p>This is an example of a good one and also an example of why you would never want to write one.\nIt is a Fowler / Noll / Vo (FNV) Hash which is equal parts computer science genius and pure voodoo:</p>\n\n<pre><code>unsigned fnv_hash_1a_32 ( void *key, int len ) {\n    unsigned char *p = key;\n    unsigned h = 0x811c9dc5;\n    int i;\n\n    for ( i = 0; i &lt; len; i++ )\n      h = ( h ^ p[i] ) * 0x01000193;\n\n   return h;\n}\n\nunsigned long long fnv_hash_1a_64 ( void *key, int len ) {\n    unsigned char *p = key;\n    unsigned long long h = 0xcbf29ce484222325ULL;\n    int i;\n\n    for ( i = 0; i &lt; len; i++ )\n      h = ( h ^ p[i] ) * 0x100000001b3ULL;\n\n   return h;\n}\n</code></pre>\n\n<p>Edit: </p>\n\n<ul>\n<li>Landon Curt Noll recommends on <a href="http://www.isthe.com/chongo/tech/comp/fnv/" rel="noreferrer">his site</a> the FVN-1A algorithm over the original FVN-1 algorithm: The improved algorithm better disperses the last byte in the hash. I adjusted the algorithm accordingly.</li>\n</ul>\n'}, {'answer_id': 746727, 'author': 'Chris Harris', 'author_id': 90577, 'author_profile': 'https://Stackoverflow.com/users/90577', 'pm_score': 6, 'selected': True, 'text': '<p>For doing "normal" hash table lookups on basically any kind of data - this one by Paul Hsieh is the best I\'ve ever used.</p>\n\n<p><a href="http://www.azillionmonkeys.com/qed/hash.html" rel="noreferrer">http://www.azillionmonkeys.com/qed/hash.html</a></p>\n\n<p>If you care about cryptographically secure or anything else more advanced, then YMMV.  If you just want a kick ass general purpose hash function for a hash table lookup, then this is what you\'re looking for.</p>\n'}, {'answer_id': 16390594, 'author': 'Gavriel Feria', 'author_id': 1928927, 'author_profile': 'https://Stackoverflow.com/users/1928927', 'pm_score': 1, 'selected': False, 'text': "<p>What you're saying here is you want to have one that uses has collision resistance. Try using SHA-2. Or try using a (good) block cipher in a one way compression function (never tried that before), like AES in Miyaguchi-Preenel mode. The problem with that is that you need to:\n<br>\n<br>\n1) have an IV. Try using the first 256 bits of the fractional parts of Khinchin's constant or something like that.\n2) have a padding scheme. Easy. Barrow it from a hash like MD5 or SHA-3 (Keccak [pronounced 'ket-chak']).\nIf you don't care about the security (a few others said this), look at FNV or lookup2 by Bob Jenkins (actually I'm the first one who reccomends lookup2) Also try MurmurHash, it's fast (check this: .16 cpb).</p>\n"}, {'answer_id': 63927109, 'author': 'Wolfgang Brehm', 'author_id': 2119377, 'author_profile': 'https://Stackoverflow.com/users/2119377', 'pm_score': 1, 'selected': False, 'text': '<p>A good hash function should</p>\n<ol>\n<li>be bijective to not loose information, where possible, and have the least collisions</li>\n<li>cascade as much and as evenly as possible, i.e. each input bit should flip every output bit with probability 0.5 and without obvious patterns.</li>\n<li>if used in a cryptographic context there should not exist an efficient way to invert it.</li>\n</ol>\n<p>A prime number modulus does not satisfy any of these points. It is simply insufficient. It is often better than nothing, but it\'s not even fast. Multiplying with an unsigned integer and taking a power-of-two modulus distributes the values just as well, that is not well at all, but with only about 2 cpu cycles it is much faster than the 15 to 40 a prime modulus will take (yes integer division really is that slow).</p>\n<p>To create a hash function that is fast and distributes the values well the best option is to compose it from fast permutations with lesser qualities like they did with <a href="https://www.pcg-random.org/pdf/hmc-cs-2014-0905.pdf" rel="nofollow noreferrer">PCG</a> for random number generation.</p>\n<p>Useful permutations, among others, are:</p>\n<ul>\n<li>multiplication with an uneven integer</li>\n<li>binary rotations</li>\n<li>xorshift</li>\n</ul>\n<p>Following this recipe we can create our own <a href="https://stackoverflow.com/a/57556517/2119377">hash function</a> or we take <a href="https://stackoverflow.com/a/12996028/2119377">splitmix</a> which is tested and well accepted.</p>\n<p>If cryptographic qualities are needed I would highly recommend to use a function of the sha family, which is well tested and standardised, but for educational purposes this is how you would make one:</p>\n<p>First you take a good non-cryptographic hash function, then you apply a one-way function like exponentiation on a prime field or <code>k</code> many applications of <code>(n*(n+1)/2) mod 2^k</code> interspersed with an xorshift when <code>k</code> is the number of bits in the resulting hash.</p>\n'}, {'answer_id': 69964280, 'author': 'otmar', 'author_id': 5439309, 'author_profile': 'https://Stackoverflow.com/users/5439309', 'pm_score': 0, 'selected': False, 'text': '<p>I highly recommend the SMhasher GitHub project <a href="https://github.com/rurban/smhasher" rel="nofollow noreferrer">https://github.com/rurban/smhasher</a> which is a test suite for hash functions. The fastest state-of-the-art non-cryptographic hash functions without known quality problems are listed here: <a href="https://github.com/rurban/smhasher#summary" rel="nofollow noreferrer">https://github.com/rurban/smhasher#summary</a>.</p>\n'}, {'answer_id': 74025413, 'author': 'cwtuan', 'author_id': 2822680, 'author_profile': 'https://Stackoverflow.com/users/2822680', 'pm_score': 0, 'selected': False, 'text': '<p>Different application scenarios have different design requirements for hash algorithms, but a good hash function should have the following three points:</p>\n<ul>\n<li><strong>Collision Resistance</strong>: try to avoid conflicts. If it is difficult to find two inputs that are hashed to the same output, the hash function is anti-collision</li>\n<li><strong>Tamper Resistant</strong>: As long as one byte is changed, its hash value will be very different.</li>\n<li><strong>Computational Efficiency</strong>: Hash table is an algorithm that can make a trade-off between time consumption and space consumption.</li>\n</ul>\n<p>In 2022, we can choose the <a href="https://fe-tool.com/en-us/hash/sha256" rel="nofollow noreferrer">SHA-2</a> family to use in secure encryption, <a href="http://localhost:3000/en-us/hash/sha3" rel="nofollow noreferrer">SHA-3</a> it is safer but has greater performance loss. A safer approach is to add salt and mix encryption., we can choose the SHA-2 family to use in secure encryption, SHA-3 it is safer but has greater performance loss. A safer approach is to add salt and mix encryption.</p>\n'}]
['https://Stackoverflow.com/questions/34595', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/3485/']