Show contents
Chapter 5 of 6 · 20 min
Project: your secret notebook
By the end of this chapter, you'll be able to
- Implement the Vigenère cipher, which uses a keyword instead of a single shift
- Attach a fingerprint to each note to detect tampering
- Combine encryption and checking in a small complete program
- Explain the limits of this notebook and name reliable tools to protect your data
The Vigenère cipher: Caesar with several shifts
The Caesar cipher has only one shift, hence its 25 keys. The Vigenère cipher (16th century) uses a keyword: each letter of the keyword gives a different shift (a = 0, b = 1, … z = 25), and the keyword is repeated along the message.
The same letter can become different letters depending on its position: simple frequency analysis no longer works.
Text description of the animation
- The message to protect, letter by letter.
- The keyword is repeated as many times as needed.
- Each keyword letter becomes a shift.
- Each message letter moves by its own shift, like a different Caesar at each position.
- The same letter can become different letters depending on its position: simple frequency analysis no longer works.
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
def vigenere(text, keyword, direction=1):
"""direction=1 encrypts, direction=-1 decrypts. Only lowercase letters are transformed."""
result, i = "", 0
for c in text:
if c in ALPHABET:
shift = ALPHABET.index(keyword[i % len(keyword)])
result += ALPHABET[(ALPHABET.index(c) + direction * shift) % 26]
i += 1 # we only move along the keyword on letters
else:
result += c
return result
encrypted = vigenere("gift for aminata: a wax print bag", "sel")
print(encrypted)
print(vigenere(encrypted, "sel", direction=-1))
ymql jzj exarlle: l oei hvtfx msk
gift for aminata: a wax print bag
With a 3-letter keyword, there are 26 × 26 × 26 = 17,576 keys, and with a 10-letter keyword, more than 141,000 billion. That sounds like a lot… the pitfall will show why it is not enough.
Sealing each note with a fingerprint
To detect a change, we store with each encrypted note the SHA-256 fingerprint of that ciphertext. When opening it, we compute the fingerprint again: if it no longer matches, the note was modified (or damaged).
import hashlib
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
def vigenere(text, keyword, direction=1):
result, i = "", 0
for c in text:
if c in ALPHABET:
result += ALPHABET[(ALPHABET.index(c) + direction * ALPHABET.index(keyword[i % len(keyword)])) % 26]
i += 1
else:
result += c
return result
def seal(note, keyword):
encrypted = vigenere(note, keyword)
return {"encrypted": encrypted, "fingerprint": hashlib.sha256(encrypted.encode()).hexdigest()}
def open_note(entry, keyword):
if hashlib.sha256(entry["encrypted"].encode()).hexdigest() != entry["fingerprint"]:
return "WARNING: note modified!"
return vigenere(entry["encrypted"], keyword, direction=-1)
notebook = [seal("buy baobab fruit for mum", "baobab"),
seal("revise fractions before thursday", "baobab")]
notebook[1]["encrypted"] = notebook[1]["encrypted"].replace("s", "t", 1) # someone touches the note
for entry in notebook:
print(open_note(entry, "baobab"))
buy baobab fruit for mum
WARNING: note modified!
Mini-lab: your notebookPython 3.13
Output
Click “Run”: Python will load in your browser (about 10 MB the first time).Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Your turn
Worked exercise
Project: Kofi's secret notebook
Complete the notebook so that it manages several notes by title:
- a function
add(notebook, title, note, keyword)that stores the sealed note in a dictionarynotebookunder its title; - a function
read(notebook, title, keyword)that returns the decrypted note,"note modified"if the fingerprint does not match, or"note not found"if the title does not exist; - test with two notes, one of which you modify on purpose, and a title that does not exist.
Hint 1
notebook[title] = seal(note, keyword). For a missing title, test if title not in notebook:.Hint 2
vigenere and seal functions from the chapter; read follows the logic of open_note.Show the solution and common mistakes
import hashlib
ALPHABET = "abcdefghijklmnopqrstuvwxyz"
def vigenere(text, keyword, direction=1):
result, i = "", 0
for c in text:
if c in ALPHABET:
result += ALPHABET[(ALPHABET.index(c) + direction * ALPHABET.index(keyword[i % len(keyword)])) % 26]
i += 1
else:
result += c
return result
def fingerprint(text):
return hashlib.sha256(text.encode()).hexdigest()
def add(notebook, title, note, keyword):
encrypted = vigenere(note, keyword)
notebook[title] = {"encrypted": encrypted, "fingerprint": fingerprint(encrypted)}
def read(notebook, title, keyword):
if title not in notebook:
return "note not found"
entry = notebook[title]
if fingerprint(entry["encrypted"]) != entry["fingerprint"]:
return "note modified"
return vigenere(entry["encrypted"], keyword, direction=-1)
notebook = {}
add(notebook, "gifts", "a football for yao", "kora")
add(notebook, "plans", "learn the guitar", "kora")
notebook["plans"]["encrypted"] = "x" + notebook["plans"]["encrypted"][1:]
for title in ["gifts", "plans", "holidays"]:
print(f"{title:<8} → {read(notebook, title, 'kora')}")
gifts → a football for yao
plans → note modified
holidays → note not found
Each case is handled in order: first the missing title (otherwise notebook[title] would raise a KeyError), then the fingerprint, and only then the decryption.
Common mistakes:
- Computing the fingerprint of the plaintext and storing it alongside: someone could guess a short note by hashing guesses ("yes", "no"…) and comparing.
- Decrypting before checking the fingerprint: you risk showing a forged note as if it were genuine.
- Using capital letters or accents in the keyword:
ALPHABET.indexdoes not find them and raises aValueError.
Summary
- 1The Vigenère cipher applies a different shift to each letter, given by a repeated keyword.
- 2A fingerprint stored with each note detects an accidental change.
- 3SHA-256 has no key: an attacker can recompute the fingerprint, an HMAC is needed for protection.
- 4Vigenère has been broken since the 19th century: for real secrets, use proven tools.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.