Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get dictionary keys hashes without recalculation

Is there a way to extract existing key hashes from a dictionary, without recalculating them again?

What would be the risks for exposing them and consequntly, accessing the dict by hashes not keys?

like image 234
Vlad Nikiporoff Avatar asked Dec 19 '25 06:12

Vlad Nikiporoff


1 Answers

I don't think Python's dictionary objects have any public API that allows you to see the hashes their objects are stored with. You can't store an object directly by hash in Python code (it may be possible by calling internal C functions in CPython). There are a few good reasons that you can't add values to a dictionary by hash value, rather than by key.

The most obvious is that multiple key objects might have the same hash. If such a hash collision happens, the second value will be inserted somewhere else in the hash table. The important thing is that it won't overwrite the previous value stored under a different key that hashes the same. If you could just pass the hash and not the key too, Python wouldn't be able to tell if you were using the same key or if you were providing a new key that happened to have a colliding hash.

A secondary reason that you can't insert by hash is that it would be a security vulnerability. The performance of a hash table like Python's dictionaries is very good when there are few hash collisions. It is very bad however if every hash is the same. If you could submit data to a Python program that all hashes to the same value, you can perform a very efficient denial of service attack (the new hash randomization for strings was added in recent versions of Python to make this kind of attack harder).

like image 169
Blckknght Avatar answered Dec 21 '25 18:12

Blckknght



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!