|
| 1 | +# About |
| 2 | + |
| 3 | +A previous concept discussed the [concept:python/random]() module, which produces [pseudo-random numbers][pseudo-random-numbers] and pseudo-random list orderings. |
| 4 | + |
| 5 | +The [`secrets`][secrets] module overlaps with `random` in some of its functionality, but the two modules are designed with very different priorities. |
| 6 | + |
| 7 | +- `random` is optimized for high performance in modelling and simulation, with "good enough" pseudo-random number generation. |
| 8 | +- `secrets` is designed to be crytographically secure for applications such as password hashing, security token generation, and account authentication. |
| 9 | + |
| 10 | + |
| 11 | +Further details on why the addition of the `secrets` module proved necessary are given in [PEP 506][PEP506]. |
| 12 | + |
| 13 | +The `secrets` is relatively small and straightforward, with methods for generating random integers, bits, bytes or tokens, or a random entry from a given sequence. |
| 14 | + |
| 15 | +To use `scerets`, you mush first `import` it: |
| 16 | + |
| 17 | + |
| 18 | +```python |
| 19 | +>>> import secrets |
| 20 | + |
| 21 | +#Returns n, where 0 <= n < 1000. |
| 22 | +>>> secrets.randbelow(1000) |
| 23 | +577 |
| 24 | + |
| 25 | +#32-bit integers. |
| 26 | +>>> secrets.randbits(32) |
| 27 | +3028709440 |
| 28 | + |
| 29 | +>>> bin(secrets.randbits(32)) |
| 30 | +'0b11111000101100101111110011110100' |
| 31 | + |
| 32 | +#Pick at random from a sequence. |
| 33 | +>>> secrets.choice(['my', 'secret', 'thing']) |
| 34 | +'thing' |
| 35 | + |
| 36 | +#Generate a token made up of random hexadecimal digits. |
| 37 | +>>> secrets.token_hex() |
| 38 | +'f683d093ea9aa1f2607497c837cf11d7afaefa903c5805f94b64f068e2b9e621' |
| 39 | + |
| 40 | +#Generate a URL-safe token of random alphanumeric characters. |
| 41 | +>>> secrets.token_urlsafe(16) |
| 42 | +'gkSUKRdiPDHqmImPi2HMnw' |
| 43 | +``` |
| 44 | + |
| 45 | + |
| 46 | +If you are writing security-sensitive applications, you will certainly want to read the [full documentation][secrets], which gives further advice and examples. |
| 47 | + |
| 48 | + |
| 49 | +[PEP506]: https://peps.python.org/pep-0506/ |
| 50 | +[pseudo-random-numbers]: https://www.khanacademy.org/computing/computer-science/cryptography/crypt/v/random-vs-pseudorandom-number-generators |
| 51 | +[secrets]: https://docs.python.org/3/library/secrets.html |
0 commit comments