SHA-based subclass for random module

Trevor Perrin trevp_spam at trevp.net
Tue Mar 23 17:33:28 EST 2004


Raymond Hettinger wrote:

> [Trevor Perrin]
> 
>>  - getrandstring() is a useful addition to the API, whereas 
>>getrandbits() is trivally done by calling randint(0, 2**k).
> 
> 
> Actually, randint() is implemented in terms of getrandbits() when
> k>53.  This saves needless conversions in and out of floating point.

I'm proposing that getrandstring() (returning a string) is a better 
primitive than getrandbits() (returning a long).  A generator should 
only have to implement getrandstring(), and the base class would 
synthesize everything else.  That way, the conversion routines (from 
byte-strings to longs and floats) don't have to be replicated in each 
subclass.

This would simplify Paul's sharandom class, and the platform-specific 
generators I'm thinking of:

class devurandom(random.Random):
     def __init__(self):
         self.f = open("/dev/urandom", "rb")
	
     def getrandstring(n):
         return self.f.read(n)


Also, the getrandstring() function would be useful for end-users (which 
was my point above):

sslPreMasterSecret = secureRandom.getrandstring(48)

This would be easy to implement with Mersenne Twister too.  Though it 
would involve some rewriting.

Do you think this is worthwhile?


Trevor



More information about the Python-list mailing list