[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)
>>> random_int(bits=256)
>>> random_token(bits=256)
>>> random_hex_digits(bits=256)


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

More information about the Python-ideas mailing list