Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Preview

Make code safer

This is the first page of the lesson. Read it and have a go at the activities. The rest is in the full lesson.

40 minutes

A phone number on a big screen

The desk screen at the club is in the waiting room. It shows every member's full phone number.

A visitor reads the screen and writes the numbers down.

Nothing in the code is "broken". It does what it was told. But it is not safe. Safe code is part of good code.

Key words

WordWhat it meansExample
Security riskA way that data or a system could be harmed.a visible phone number
ValidationChecking that input is sensible before you use it.a name has only letters
Personal dataFacts about a real person.name, phone number
MaskHide part of a value.*******0123
HardcodedTyped straight into the code so anybody who reads it can see it.password = "club123"
CharacterOne letter, digit (0 to 9) or sign in a text.a, 7, !
HashingA one-way scramble. You cannot turn it back into the original.sha256

The cells students fill in are left blank in this preview.

Try it: hide most of a number

Code: python
phone = "07700900123"
shown = ""
for i in range(len(phone)):
    if i < len(phone) - 4:
        shown = shown + "*"
    else:
        shown = shown + phone[i]
print(shown)

# phone[i] is the character at place i.
# Only the last 4 places are shown.
# Change the phone number and run it again.

Four common risks and fixes

RiskExampleFix
Bad inputA name that holds code or is 5000 letters longValidate: check length and allowed characters
Data that everyone can seeA full phone number on a big screenMask it, or do not show it
Secrets in codepassword = "club123" in the fileDo not hardcode. Keep secrets outside the code
Weak passwordsThe password is 1234Check the length and the kinds of character

The cells students fill in are left blank in this preview.

About hashing

data-callouts.note.label

Real systems use a special slow method and add a random extra value. A plain hash is only a first idea. Your lecturer will tell you how far to go.

Try it: a hash

Code: python
import hashlib

first = hashlib.sha256("badger2024".encode()).hexdigest()
second = hashlib.sha256("badger2025".encode()).hexdigest()
print(first)
print(second)

# One letter changes. The whole hash changes.

Quick check: safe or not?

Have a go

Quick check: safe or not?

4 questions
Have a go: your answers are marked here and then forgotten. Sign in if you would like your score kept, and to pick up where you left off.Sign in to keep your score

Your answers are marked here and are not kept. A college account keeps every student’s marks.

The lesson goes on

3 more parts of this lesson are in the full curriculum, with the tasks, the final check and the labs. A college account gives your students all of it.