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

Free lesson

OS 6.1 (4 of 10): Access control and encryption

The whole lesson, free. Read it and have a go at the activities. To work the tasks and labs in the real lesson, press Start lab, with no account needed.

55 minutes

A quick check that you are not a bot, then your own lab opens on the interactive lesson.

Already have an account? Sign in

Who may open the door?

A school has a staff room. Teachers have a key. Students do not. The office has a safe. Only the head teacher has that key.

Software needs the same. Not every user may do everything. And if a thief steals the data, the data should be unreadable to them.

These are the two jobs of this lesson: control who gets in, and hide the data.

Key words

WordWhat it means
AuthenticationChecking who somebody is.
AuthorisationDeciding what a known person may do.
RoleA named set of permissions.
Least privilegeGiving each person only the access they need.
EncryptionScrambling data so only a key holder can read it.
HashingTurning data into a fixed code that cannot be turned back.
SaltExtra random text added to a password before hashing.
KeyA secret value used to lock (encrypt) and unlock (decrypt) data.
CipherA rule for scrambling text.
PlaintextData anybody can read.

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

Control user access

Two questions come in order.

Authentication: who are you? A password, a code or a fingerprint answers it.

Authorisation: what may you do? A role answers it. A student may read. A teacher may read and write. An admin may also delete.

The rule of least privilege says: give the smallest access that does the job.

Check a role in code

Code: python
ROLES = {"student": {"read"}, "teacher": {"read", "write"}}


def has_access(role, action):
    return action in ROLES.get(role, set())


print(has_access("student", "read"))
print(has_access("student", "write"))
print(has_access("visitor", "read"))

# Add an admin role that can also delete.

Make a free account to save your work and track your progress.

A role table

RoleReadWriteDelete
studentYesNoNo
teacherYesYesNo
adminYesYesYes

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

Check: who and what

Have a go

Check: who and what

3 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

Encrypt data

Encryption scrambles data with a key. Only somebody with the right key can read it.

Use it in two places. In transit: data moving over a network (computers joined together), which is what HTTPS does. At rest: data saved on a disk or in a database (an organised store of data).

Two kinds of key

KindHow many keysSimple pictureUsed for
SymmetricOne key locks and unlocksOne house key that both of you copyEncrypting files and the data in a session
AsymmetricA public key locks, a private key unlocksA letter box: anybody posts a letter, only you have the key to open itStarting a safe HTTPS connection

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

A toy cipher shifts each letter

Code: python
def shift(text, n):
    out = ""
    for ch in text:
        if "a" <= ch <= "z":
            out += chr((ord(ch) - ord("a") + n) % 26 + ord("a"))
        else:
            out += ch
    return out


secret = shift("hello", 3)
print(secret)
print(shift(secret, -3))

# This toy is NOT secure. Anybody can try all 25 shifts.

Make a free account to save your work and track your progress.

Never write your own encryption

Warning

Many people think a cipher they wrote themselves is safe enough. It is not. Home-made encryption is nearly always broken, because attackers know the tricks. The shift cipher here teaches the idea only. In a real product, use a trusted library and a tested method.

Hashing is not encrypting

EncryptionHashing
Can you get the data back?Yes, with the keyNo
Use it forMessages and files you must read laterPasswords you only need to check
Same input givesA different result with a different keyThe same hash every time
ExampleHTTPSSHA-256

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

Hash a password with salt

Code: python
import hashlib


def hash_password(password, salt):
    return hashlib.sha256((salt + password).encode()).hexdigest()


print(hash_password("letmein", "a1"))
print(hash_password("letmein", "b2"))

# Same password, different salt, different hash.
# Real products also use a slow method such as bcrypt or scrypt.

Make a free account to save your work and track your progress.

Match the idea

Have a go

Loading…

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

Write roles, hashes and a toy cipher

Build four security tools. has_access checks a role table. hash_password and check_password store passwords the safe way. shift_encrypt is a toy cipher for practice. Read the comments. Press Run Tests.

Code: python
import hashlib
import hmac

ROLES = {
    "student": {"read"},
    "teacher": {"read", "write"},
    "admin": {"read", "write", "delete"},
}


def has_access(role, action):
    # True only if the role exists and its set holds the action.
    # An unknown role has no access: give back False.
    return None


def hash_password(password, salt):
    # Join the salt and the password (salt first), turn the text into bytes with
    # encode(), and give back the SHA-256 hash as a hex string.
    return None


def check_password(password, salt, stored):
    # True if the password gives the stored hash.
    # Compare with hmac.compare_digest, not with ==.
    return None


def shift_encrypt(text, shift):
    # A toy cipher, NOT secure. Move each letter a to z forward by shift places.
    # Wrap round at the end: z moved forward one place becomes a. Keep the case. Leave other characters as they are.
    return None

Make a free account to save your work, or press Start lab to work through the whole lesson.

Key words crossword

Have a go

Loading…

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

Exit quiz

Have a go

Exit quiz

6 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

Teach this lesson with your class

On a college account your students work the tasks and the labs as well, and every mark is kept for you.