Old python hashing done left to right - why is it bad?
Question: I am trying to learn how to defend against security attacks on websites. The
link below shows a good tutorial, but I am puzzled by one statement:

In <http://google-gruyere.appspot.com/part3#3__client_state_manipulation> ,
under "Cookie manipulation", Gruyere says Pythons hash is insecure since it
hashes from left-to-right.

The Gruyere application is using this to encrypt data:

    
    
    # global cookie_secret; only use positive hash values
    h_data = str(hash(cookie_secret + c_data) & 0x7FFFFFF)
    

c_data is a username; cookie_secret is a static string (which is just '' by
default)

I understand that in more secure hash functions, one change generates a whole
new result, but I don't understand why this insecure, because different c_data
generates whole different hashes!

EDIT: How would one go about beating a hash like this?


Answer: I think that's just a bad explanation there. Python's `hash()` is insecure
because it's easy to find collisions, but "hashes from left to right" has
nothing to do with _why_ it's easy to find collisions. [Cryptographically
secure hashes](http://en.wikipedia.org/wiki/Cryptographic_hash_function) also
process data strictly in sequence; they're likely to operate on data 128 or
256 bits at a time rather than one byte at a time, but that's just a detail of
the implementation.

(It should be said that `hash()` being insecure is _not_ a bug in Python,
because that's not what it's for. It's an exposed detail of the implementation
of Python's dictionaries as [hash
tables](http://en.wikipedia.org/wiki/Hash_table), and you generally _don't_
want a secure hash function for your hash table, because that would slow it
down so much that it would defeat the purpose. Python does provide secure hash
functions in the [hashlib](http://docs.python.org/library/hashlib.html)
module.)

(The use of an insecure hash is not the only problem with the code you show,
but it is by far the most important problem.)

