Random Strings
For secrets and other useful things
Last updated
Was this helpful?
For secrets and other useful things
Last updated
Was this helpful?
Do Not Do This: This Stack Overflow question is the current top Google result for "random string Python". The current top answer is "wrong."
This is an excellent method, but the in random is not cryptographically secure. I assume many people researching this question will want to generate random strings for encryption or passwords. You can do this securely by making a small change in the above code:
Using random.SystemRandom()
instead of just random uses /dev/urandom on *nix machines and CryptGenRandom()
in Windows. These are cryptographically secure PRNGs. Using random.choice
instead of random.SystemRandom().choice
in an application that requires a secure PRNG could be potentially devastating, and given the popularity of this question, I bet that mistake has been made many times already.
If you're using python3.6 or above, you can use the new module as mentioned in :
The module docs also discuss convenient ways to and .