Description
Documentation
I recently needed to generate some cryptographic key material. As far as I can tell, secrets.token_bytes()
is the recommended way of doing this, and cpython's concrete implementation appears to be suitable for this purpose. However, the precise wording of the documentation for the API does not make this 100% clear.
The token subsection says:
The secrets module provides functions for generating secure tokens, suitable for applications such as password resets, hard-to-guess URLs, and similar.
And, under token_bytes()
specifically:
Return a random byte string containing nbytes number of bytes. [...]
In my very pedantic reading of this, it does not make the sufficient guarantees for securely generating cryptographic key material. It does guarantee that generated tokens will be hard-to-guess, but that's a weaker guarantee than is sometimes necessary.
As an example, generating ECDSA signatures requires a uniform-random nonce value. If even a single bit of that nonce is biased one way or another, over a sufficient number of signatures, then an attacker can use that information to recover the private key (see https://eprint.iacr.org/2019/023.pdf )
As such, I think the documentation for these methods should be amended to explicitly state that the generated bytes are uniformly random, or to otherwise explicitly state that the direct output of secrets.token_bytes()
may be suitable for generating cryptographic key material.
To be clear, I am not requesting any changes to the current implementation, merely that the docs accurately reflect what I assume to be the intended and current behaviour.