Unit 7 · Borrowing Code · Lesson 54 of 57
Secrets Are Safer
How random is random?
Here's a secret about random: it isn't actually random.
Computers are machines that follow instructions exactly. They can't just "pick" something. So random uses math to make numbers that look random, starting from a number called a seed.
Same seed, same "random" numbers. Every time. Try it:
Run this a few times. Notice anything?
Python exercise
Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.
Same numbers, every time
Normally Python picks the seed for you from things like the current time, so it feels random. And for picking who pays for pizza, that's totally fine.
But for anything to do with security, like passwords, reset codes or login tokens, it's a problem. If an attacker can figure out the seed (or see enough of the numbers it made), they can predict what comes next.
Remember the session tokens from Web Exploitation? Those long, random strings that are "basically impossible to guess"? If a website made them with
random, they might not be so impossible after all.
secrets
For anything security related, Python has a module called secrets. It gets its randomness from your operating system, which is built specifically to be unpredictable.
import secrets
import string
print(secrets.choice(["Karl", "Amer", "Zain"]))
print(string.ascii_letters)
print(string.digits)
Zain
abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789
secrets.choice()works just likerandom.choice(), but safe enough for passwords.- The
stringmodule has handy strings with every letter and every digit already typed out for you. No need to type the alphabet yourself.
The rule is simple: games use random, security uses secrets.
Amer needs a better password. Let's make him one.
Make a function called make_password that takes a length and returns a password that long, made of random letters and digits.
Use secrets.choice() to pick each character, one at a time, from string.ascii_letters + string.digits.
Hint: start with an empty string,
password = "", and add one character at a time with a loop. You can use+=on strings too!
Python exercise
Write the program in an editor next to the lesson, run it, and have it checked automatically. Create a free account to do this part.
Do this lesson for real
With a free account you get the terminals, challenges and checks that go with the lessons in Intro to Python, and your progress is saved as you go. CyberAcad is a 501(c)(3) nonprofit, so there is nothing to pay.