Cryptographically random numbers

Bryan Olson fakeaddress at nowhere.org
Tue Mar 7 00:17:37 EST 2006


Tuvas wrote:
[...]
> As to the s2num(text), well, that looks really neat. Is there an easy
> way to do the reverse of that? Thanks!

Easy?  Well, you be the judge:

   def num2string(n):
       """ Pass a non-negative int or long n.
           Returns a string with bytes holding the big-endian base-256
           representation of n. Zero is represented by the empty string.
       """
       h = hex(n).lstrip('0x').rstrip('Ll')
       if len(h) % 2:
           h = '0' + h
       return unhexlify(h)



I did a little testing:

     for i in xrange(300):
         assert s2num(num2string(i)) == i
     for i in xrange(1, 20):
         for _ in xrange(100):
             r = os.urandom(i)
             assert num2string(s2num(r)) == r.lstrip(chr(0))



-- 
--Bryan



More information about the Python-list mailing list