SHA-based subclass for random module

Anton Vredegoor anton at
Wed Mar 24 12:19:46 CET 2004

Trevor Perrin <trevp_spam at> 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()


>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',
        '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 =
        while 1:
            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__':


More information about the Python-list mailing list