[Python-ideas] PEP 504: Using the system RNG by default

Nick Coghlan ncoghlan at gmail.com
Thu Sep 17 14:35:18 CEST 2015


On 17 September 2015 at 04:55, Tim Peters <tim.peters at gmail.com> wrote:
> [Brett Cannon <brett at python.org>]
>> And if yes to a PEP, who's writing it? And then who is writing the
>> implementation in the end?
>
> Did you just volunteer?  Great!  Thanks ;-)  OK, Steven already
> volunteered to write a PEP for his proposal.

As far as implementation goes, based on a separate discussion at
https://github.com/pyca/cryptography/issues/2347, I believe the
essential cases can all be covered by:

    def random_bits(bits):
        return os.urandom(bits//8)

    def random_int(bits):
        return int.from_bytes(random_bits(bits), byteorder="big")

    def random_token(bits):
        return base64.urlsafe_b64encode(random_bits(bits)).decode("ascii")

    def random_hex_digits(bits):
        return binascii.hexlify(random_bits(bits)).decode("ascii")

So if you want a 128 bit (16 bytes) IV, you can just write
"secrets.random_bits(128)". Examples of all four in action:

>>> random_bits(256)
b'\xacc\xa6I[\x9c\xca\x86=B$\xd0\xbc\xee\x8a\xe3i\xe9\xb2\xf4w\xd4@\xc2{U\xb5\xb0\xac\x82\x8a='
>>> random_int(bits=256)
44147786895503064021838366541869866305141442570318401936078951782072369110412
>>> random_token(bits=256)
'-woFuniDCsApOFMtRP5vtjfPfFkmvVhdaPoh9eqAuSs='
>>> random_hex_digits(bits=256)
'e5b09c74bda516ca8464f38dc45428004b6bd81d4e4031fdf9f164e567fbed82'

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at gmail.com   |   Brisbane, Australia


More information about the Python-ideas mailing list