SHA-based subclass for random module

Anton Vredegoor anton at vredegoor.doge.nl
Wed Mar 24 06:19:46 EST 2004


Trevor Perrin <trevp_spam at trevp.net> wrote:

>(Conversion would be even easier if Python had a built-in way to convert 
>byte strings to longs.  Maybe something like:
>
>bigNumber = long(bigNumberString, 256)
>
>bigNumberString = bigNumber.tostring()

+1

>Having to return bits is ungainly cause what if the caller wants, say, 7 
>of them?  You gotta buffer the excess bit, and then tack it on to the 
>next call.

Maybe this:


from random import Random
from itertools import islice
import sha

asbits = {'0':'0000','1':'0001','2':'0010','3':'0011',
        '4':'0100','5':'0101','6':'0110','7':'0111',
        '8':'1000','9':'1001','a':'1010','b':'1011',
        'c':'1100','d':'1101', 'e':'1110','f':'1111'}

class ShaRandom(Random):

    def random(self, tofloat = 1.0 / 2 ** 53, gen = None):
        if gen is None: 
            gen = self.bitgen()
        bits = ''.join(islice(gen,53))
        return long(bits,2) * tofloat

    def bitgen(self, prf = sha.new()):
        while 1:
            prf.update(repr(Random.random(self)))
            for nibble in prf.hexdigest():
                for bit in asbits[nibble]:
                    yield bit
                    
def test():
    random = ShaRandom().random
    for i in range(10):
        print random()

if __name__=='__main__':
    test()

Anton




More information about the Python-list mailing list