[Python-ideas] Pre-PEP Adding A Secrets Module To The Standard Library

Nick Coghlan ncoghlan at gmail.com
Sun Sep 20 14:26:42 CEST 2015

On 20 September 2015 at 20:56, Paul Moore <p.f.moore at gmail.com> wrote:
> Given where this started, I'd suggest renaming token_alpha as
> "password". Beginners wouldn't necessarily associate the term "token"
> with the problem "I want to generate a random password" [1]. Maybe add
> a short recipe showing how to meet constraints like "at least 2
> digits" by simply generating repeatedly until a valid password is
> found.
> For a bit of extra bikeshedding, I'd make alphabet the second,
> optional, parameter and default it to
> string.ascii_letters+string.digits+string.punctuation, as that's often
> what password constraints require.
> Or at the very least, document how to use the module functions for the
> common tasks we see people getting wrong. But I thought the idea here
> was to make doing things the right way obvious, for people who don't
> read documentation, so I'd prefer to see the functions exposed by the
> module named based on the problems they solve, not on the features
> they provide. (Even if that involves a little duplication, and/or a
> split between "high level" and "low level" APIs).

Right, I'd suggest the following breakdown.

* Arbitrary password generation (also covers passphrase generation
from a word list):

    secrets.password(result_len: int,
alphabet=string.ascii_letters+string.digits+string.punctuation: T) ->

* Binary token generation ("num_random_bytes" is the arg to
os.urandom, not the length of result):

    secrets.token(num_random_bytes: int) -> bytes
    secrets.token_hex(num_random_bytes: int) -> bytes
    secrets.token_urlsafe_base64(num_random_bytes: int) -> bytes

* Serial number generation ("num_random_bytes" is the arg to
os.urandom, not the length of result):

    secrets.serial_number(num_random_bytes: int) -> int

* Constant time secret comparison (aka hmac.compare_digest):

    secrets.equal(a: T, b: T) -> bool

* Lower level building blocks:

    # Hold off on other SystemRandom methods?

(I don't have a strong opinion on that last point, as it's the higher
level APIs that I think are the important aspect of this proposal)


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

More information about the Python-ideas mailing list