Generating a one-time pad key in Python
Builds a one-time pad key by picking one random number from 0 to 25 for each character in the message, so the key is as long as the message. Never reuse a key.
Understanding Generating a one-time pad key in Python in QCE Digital Solutions Unit 4
What it does: Looping over message gives one random number for each character, so len(key) equals len(message). secrets.randbelow(26) gives a number from 0 to 25 and is designed for security use, so it suits one-time pad keys. randint is a function inside the random module, so you import random and then call random.randint(). Reusing a key lets an attacker compare messages and find patterns. This breaks the security of the one-time pad. A pattern can be guessed. Every key value must be random and independent of the others. Generate a brand new key for every message, by running the key-building line again with the new message.
Common mistakes: The key must start as an empty list so that .append() can add one random number per character. A string has no append method, so it should be key = []. The code calls secrets.randbelow(26), so it must import the secrets module. Importing random leaves secrets undefined and causes a NameError. It should be import secrets.
Free printable worksheet with full answer key — or add this module to a class and your students practise it interactively.
This module's key terms are also in a printable crossword (Modules 334–401) and word search (Modules 127–401).
Take this worksheet further — free with Cloodit
Each concept is reinforced from every angle — learned, then applied, then tested.
Cloodit turns curriculum-aligned coding content into journeys students work through one biome at a time.
Over 100 of them, across seven natural biomes.
Turns their work into revision material ready for Flash Cards and Exam study.
Live, competitive practice for the start of the lesson or a teacher-led lesson finisher.
Honour your top performers, or encourage a student who's trying hard — ready to print in seconds.
Quick Questions
Match the Pairs
Key Term
key = [random.randint(0, 25) for c in message]Fill in the Blanks
Spot the Error
Student with a class code? Join your class →