Generating unique row ID ints.

Paul Rubin http
Sun Oct 1 11:54:01 EDT 2006


"Simon Wittber" <simonwittber at gmail.com> writes:
> Some of the tables require single integer primary keys which might be
> exposed in some parts of the web interface. If users can guess the next
> key in a sequence, it might be possible for them to 'game' or
> manipulate the system in unexpected ways. I want to avoid this by
> generating a random key for each row ID, and have decided to use the
> same approach for all my single key tables.

Normally primary keys are sequential but only live inside the system.
Users are not supposed to enter them.

> If the random module is suitable, does anyone have any good ideas on
> how this could be implemented?

The random module does not aim to be secure against knowledgeable
attackers trying to guess the output (i.e. it's not cryptographic
randomness).  Use os.urandom instead.

> I've got my own ideas for implementing this, but am interested to see
> how/if anyone else has tackled the same problem.

The simplest thing to do is generate random strings, e.g.

   key = os.urandom(16)

for a 16-byte binary string.  You can of course encode it as printing
characters with your favorite binascii function.  16-byte strings like
that should be unguessable and collision-free until you have an
enormous number of them (on the order of 2**64).



More information about the Python-list mailing list