Get the 32-bit hash value from boost :: hash

I use boost::hash to get the hash value for the string. But it gives different hash values โ€‹โ€‹for a single line on 32-bit and 64-bit Windows systems.

So, how can I get the same hash value (32-bit or 64-bit) using boost::hash regardless of platform?

+6
source share
3 answers

What is the guarantee regarding boost::hash ? I donโ€™t see guarantees that the generated hash code can be used outside the process that generates it. (This often happens with a hash function.) If external data requires a hash value, valid for different programs and different platforms (for example, hashed access to data on disk), then you have to write your own. Sort of:

 uint32_t hash( std::string const& key ) { uint32_t results = 12345; for ( auto current = key.begin(); current != key.end(); ++ current ) { results = 127 * results + static_cast<unsigned char>( *current ); } return results; } 

should do the trick if you don't need to worry about porting to some exotic mainframes (which may not support uint32_t ).

+4
source

Use some of the well-known generic hash functions, such as SHA, because they must ensure that the same line has the same hash. Please note that if you are doing something related to security, SHA may be too fast. This is strange, but sometimes quickly it doesnโ€™t mean good, because it opens up the possibility of brute force attack - in this case there is another, slower hash function, some of which mainly re-apply SHA many times in a row, Itโ€™s different if you use hashing passwords, do not forget to salt them (I will not go into details, but the information is easily accessible on the Internet).

0
source

The hash function above is simple, but weak and vulnerable.

For example, go to this function line, such as "bb" "bbbb", "bbddbb" "ddffbb" - any combination of character pairs with even ASCII codes and look at the low byte. It will always be 57.

Rather, I recommend using my hash function, which is relatively lightweight and has no easy vulnerability:

 #define NLF(h, c) (rand[(uint8_t)(c ^ h)]) uint32_t rand[0x100] = { 256 random non-equal values }; uint32_t oleg_h(const char *key) { uint32_t h = 0x1F351F35; char c; while(c = *key++) h = ((h >> 11) | (h << (32 - 11))) + NLF(h, c); h ^= h >> 16; return h ^ (h >> 8); } 
0
source

Source: https://habr.com/ru/post/948543/


All Articles