[Python-Dev] os.urandom API

Tim Peters tim.peters at gmail.com
Sun Aug 29 23:55:57 CEST 2004


I agree with Martin that the patch submitter and reviewers really want
strings to come back -- there are many use cases for that in
cryptoweenie land, as simple as generating a random session key.

Long ints might be cool too, but if so that deserves a distinct API. 
Something like "urandom(n) -- return a uniform random int from 0
through 256**n-1" would be a pretty bizarre spec.

Note that it's easy (abeit obscure) to generate a long from a string s:

    long(binascii.hexlify(s), 16)

It's harder to go in the other direction.  First you do hex(n). Then
you chop off the leading "0x".  Then there may or may not be a
trailing "L", and iff there is you have to lose that too.  Then
binascii.unhexlify() gets the string.  Then you may have to go on to
pad with one or more leading NUL bytes.

Regardless of whether there's another API added, it might be good to
change random.seed() under the covers to use (say) 4 urandom bytes for
default initialization (when os.urandom is available).  Initializing
based on time.time() is weak, and especially on Windows (where there
are typically only 18.2 distinct time.time() values per second).


More information about the Python-Dev mailing list