SHA-based subclass for random module

Trevor Perrin trevp_spam at trevp.net
Tue Mar 23 06:16:35 EST 2004


Raymond Hettinger wrote:
> [Trevor Perrin]
> 
>>>Actually, Random could be made even easier to subclass.  getrandbits
>>>(which is new in 2.4) returns a long.  It would be better for us if
>>>there was a getrandstring() function that an underlying generator
>>>could implement.  This would also be a helpful addition to the API, at
>>>least for cryptographic uses.
> 
> 
> [Paul Rubin]
> 
>>I agree with this, and was going to propose the same thing.
>>getrandbits can be defined easily in terms of getrandstring, and the
>>current sample sharandom implemenation at
>>
>>   http://www.nightsong.com/phr/python/sharandom.py
>>
>>does something along those lines.
> 
> 
> If you're sure you need this, please put a feature request on SF.  It
> needs to have a use case other than feeding message digest funtions --
> that need is readily met with str(x) or the faster hex(x).

One use case is cryptographic things like symmetric keys, IVs, nonces, 
random padding, etc.

> The new genrandbits() method was designed around the use case of
> making randrange() work over very large intervals which was necessary
> for creating large primes for RSA work.  In addition, all of the
> methods internal to the Random module work with numbers instead of
> byte strings.

Even still, I think getrandstring() would be a more convenient primitive 
than getrandbits():
  - cryptographic generators (which you'll want for RSA) are more 
naturally defined in terms of byte strings
  - it's not hard to convert byte-strings to longs or floats, but it 
would be better for this conversion to be done in the Random base class, 
instead of forcing every subclass to do it
  - getrandstring() is a useful addition to the API, whereas 
getrandbits() is trivally done by calling randint(0, 2**k).


Trevor



More information about the Python-list mailing list