কম্পিউটার বিজ্ঞান · বই 1 · শ্রেণি 1–9

Primary & Middle School Computer Science

এই বইটি এখনো বাংলা ভাষায় পাওয়া যায় না। সংস্করণ: English।

Primary & Middle School Computer Science · শ্রেণি 1–9

36Secret Codes: A First Look at Cryptography

Lina and Sami pass notes in class. To keep them private, they replace every letter by the one three places further in the alphabet: see you at noon becomes vhh brx dw qrrq. One day their teacher picks up a note, looks at it for a minute, and reads it out loud. How did she do it, and how could they have done better? This chapter writes secret codes in Python, and then breaks them.

You already know

A string is a sequence of characters; ord gives the code of a character and chr the character of a code (Chapter 21). A dictionary can count how often each value appears (Chapter 26). random.shuffle mixes a list, and a seed makes it repeat (Chapter 35). A password proves who you are to a server (Chapter 13).

36.1 Encrypting and decrypting with a key

Definition 36.1 (Cipher, plaintext, ciphertext)

A cipher is a method that turns a readable message, the plaintext, into a scrambled one, the ciphertext, and back.

Definition 36.2 (Encryption and decryption)

Encryption turns plaintext into ciphertext; decryption turns the ciphertext back into the plaintext.

Definition 36.3 (Encryption key)

The encryption key of a cipher is the secret setting that the sender and the receiver share, such as the number of places each letter moves. The same cipher with another key gives another ciphertext.

The ciphertext travels where anyone may see it: on a note passed across the room, or over a network. The method is often known to all; only the key is secret. A good cipher stays safe even when the enemy knows how it works, as long as the key stays hidden.

A secret message: the key is shared in advance; the ciphertext travels in the open, where someone without the key can read it but should not understand it.
A secret message: the key is shared in advance; the ciphertext travels in the open, where someone without the key can read it but should not understand it.

36.2 The shift cipher and its 25 keys

Definition 36.4 (Shift cipher)

A shift cipher moves every letter of the plaintext the same number of places along the alphabet, going round from z back to a. The number of places is the key.

A cipher wheel set to shift 3: each letter of the outer ring is replaced by the letter just inside it (a by D, b by E, …, x by A).
A cipher wheel set to shift 3: each letter of the outer ring is replaced by the letter just inside it (a by D, b by E, …, x by A).

This cipher is very old. A Roman historian wrote that Julius Caesar used it for his confidential letters: to read them, one had to put D for A, and so on with the other letters, a shift of three.

In Python, a letter’s position in the alphabet is ord(letter) - ord("a"), from 0 to 25. Adding the key and keeping the remainder by 26 makes the alphabet go round:

ALPHABET = "abcdefghijklmnopqrstuvwxyz"


def shift_letter(letter, key):
    """The letter moved key places round the alphabet; other characters stay."""
    if letter not in ALPHABET:
        return letter
    return chr((ord(letter) - ord("a") + key) % 26 + ord("a"))


def encrypt(text, key):
    """The shift cipher: every letter of text moved key places."""
    result = ""
    for letter in text.lower():
        result = result + shift_letter(letter, key)
    return result


if __name__ == "__main__":
    print(encrypt("meet me at the lighthouse at nine", 3))
    print(encrypt("xyz", 3))
Listing 36.1. The shift cipher. code/grade-9/06-first-cryptography/listings/shift.py
$ python shift.py
phhw ph dw wkh oljkwkrxvh dw qlqh
abc
Output 36.1. x, y and z go round to a, b and c.

To decrypt, shift by the opposite of the key. Python’s % keeps the result between 0 and 25 even when the number is negative:

from shift import encrypt

secret = encrypt("meet me at the lighthouse at nine", 3)
print("ciphertext:", secret)
print("decrypted: ", encrypt(secret, -3))        # move every letter back
Listing 36.2. Decrypting: the same function, the opposite key. code/grade-9/06-first-cryptography/listings/shift_back.py
$ python shift_back.py
ciphertext: phhw ph dw wkh oljkwkrxvh dw qlqh
decrypted:  meet me at the lighthouse at nine
Output 36.2. There and back.

Definition 36.5 (Brute-force search)

A brute-force search tries every possible key, one after the other, until one gives a readable message.

The shift cipher has only 25 useful keys, so a program tries them all in a blink:

from shift import encrypt

ciphertext = "gur obng yrnirf ng qnja"
for key in range(1, 26):
    print(f"{key:>2}: {encrypt(ciphertext, -key)}")
Listing 36.3. Every key, one after the other. code/grade-9/06-first-cryptography/listings/brute_force.py
$ python brute_force.py
 1: ftq namf xqmhqe mf pmiz
 2: esp mzle wplgpd le olhy
 3: dro lykd vokfoc kd nkgx
 4: cqn kxjc unjenb jc mjfw
 5: bpm jwib tmidma ib liev
 6: aol ivha slhclz ha khdu
 7: znk hugz rkgbky gz jgct
 8: ymj gtfy qjfajx fy ifbs
 9: xli fsex pieziw ex hear
10: wkh erdw ohdyhv dw gdzq
11: vjg dqcv ngcxgu cv fcyp
12: uif cpbu mfbwft bu ebxo
13: the boat leaves at dawn
14: sgd anzs kdzudr zs czvm
Output 36.3. Key 13 gives English. Some lines are left out.

That is how the teacher read Lina’s note: a person can try 25 shifts by hand in a few minutes. A cipher is only as strong as the work it takes to try all its keys.

A cipher wheel once used to train soldiers: the inner ring turns against the outer one, and the position chosen is the key. On this wheel the inner alphabet runs the other way round.
A cipher wheel once used to train soldiers: the inner ring turns against the outer one, and the position chosen is the key. On this wheel the inner alphabet runs the other way round.

36.3 Substitution ciphers and letter frequencies

Definition 36.6 (Substitution cipher)

A substitution cipher replaces each letter by another, following a table in which every letter of the alphabet appears once: the key is a mixed alphabet.

The shift cipher is the special case where the table is the alphabet turned round. A general key is any shuffle of the alphabet:

import random

ALPHABET = "abcdefghijklmnopqrstuvwxyz"


def random_key(seed):
    """A mixed alphabet: the letter that replaces a, then b, and so on."""
    random.seed(seed)
    letters = list(ALPHABET)
    random.shuffle(letters)
    return "".join(letters)


def substitute(text, source, target):
    """Replace each letter of source found in text by the letter of target."""
    result = ""
    for letter in text.lower():
        if letter in source:
            result = result + target[source.index(letter)]
        else:
            result = result + letter
    return result


if __name__ == "__main__":
    key = random_key(2026)
    print("plain: ", ALPHABET)
    print("key:   ", key)
    secret = substitute("meet me at the lighthouse at nine", ALPHABET, key)
    print(secret)
    print(substitute(secret, key, ALPHABET))      # the same table, read upwards
Listing 36.4. A substitution cipher with a shuffled alphabet. code/grade-9/06-first-cryptography/listings/substitution.py
$ python substitution.py
plain:  abcdefghijklmnopqrstuvwxyz
key:    migcwfstyelbjavopnrhzuxqkd
jwwh jw mh htw bysthtvzrw mh ayaw
meet me at the lighthouse at nine
Output 36.4. The key replaces a by m, b by i, and so on.

How many keys are there? 26 choices for the letter that replaces a, then 25 for b, 24 for c, and so on down to 1:

keys = 1
for choices in range(26, 0, -1):     # 26 choices for a, then 25 for b, ...
    keys = keys * choices
print(f"{keys:,} substitution keys")
Listing 36.5. Counting the keys. code/grade-9/06-first-cryptography/listings/count_keys.py
$ python count_keys.py
403,291,461,126,605,635,584,000,000 substitution keys
Output 36.5. A 27-digit number.

Far too many to try, even for a computer (Exercise 36.10). But the cipher has a weakness: each letter is always replaced by the same symbol, so the ciphertext keeps the letter frequencies of the language.

Definition 36.7 (Frequency analysis)

Frequency analysis breaks a substitution cipher by counting how often each symbol appears in the ciphertext and matching the most frequent symbols with the most frequent letters of the language.

The chapter keeps an invented passage of four paragraphs in a text file, passage.txt. It begins:

The old lighthouse stands at the end of the harbour wall, where the river meets the sea.
For more than a hundred years its keepers climbed the stairs every evening to light the
lamp, and every morning they came down to write in the logbook. They wrote the weather,
Listing 36.6. The first lines of the chapter’s passage. code/grade-9/06-first-cryptography/listings/passage.txt

Counting its letters with a dictionary:

def letter_counts(text):
    """A dictionary: each letter of text and the number of times it appears."""
    counts = {}
    for letter in text.lower():
        if "a" <= letter <= "z":
            counts[letter] = counts.get(letter, 0) + 1
    return counts


def by_frequency(counts):
    """The letters, from the most frequent to the least."""
    return sorted(counts, key=lambda letter: -counts[letter])


if __name__ == "__main__":
    with open("passage.txt", encoding="utf-8") as f:
        passage = f.read()
    counts = letter_counts(passage)
    total = sum(counts.values())
    print(total, "letters")
    for letter in by_frequency(counts)[:10]:
        print(f"{letter}: {counts[letter]:>4}  {100 * counts[letter] / total:5.1f} %")
Listing 36.7. The letters of the passage, the most frequent first. code/grade-9/06-first-cryptography/listings/frequencies.py
$ python frequencies.py
1517 letters
e:  213   14.0 %
t:  180   11.9 %
h:  129    8.5 %
a:  116    7.6 %
o:  102    6.7 %
s:  100    6.6 %
n:   97    6.4 %
r:   89    5.9 %
i:   85    5.6 %
l:   63    4.2 %
Output 36.6. E, t, h and a lead.

sorted with key=lambda letter: -counts[letter] sorts the letters by their counts, largest first: a lambda is a function written in one line, here “given a letter, return minus its count”.

The letter counts of the passage and of its ciphertext with shift 3: the same bars, moved three places to the right. The tallest bar, e, has become h.
The letter counts of the passage and of its ciphertext with shift 3: the same bars, moved three places to the right. The tallest bar, e, has become h.

The same works on a substitution cipher, with a long text in the same language as a guide. The program below takes the first two paragraphs of the passage as the known text, encrypts the last two with a random key, and guesses the key by matching the letters in order of frequency:

from frequencies import by_frequency, letter_counts
from substitution import ALPHABET, random_key, substitute

with open("passage.txt", encoding="utf-8") as f:
    paragraphs = f.read().split("\n\n")
known = paragraphs[0] + paragraphs[1]          # a long text we can read
message = paragraphs[2] + paragraphs[3]        # the message to protect
secret = substitute(message, ALPHABET, random_key(7))

known_order = "".join(by_frequency(letter_counts(known)))
for letter in ALPHABET:                         # letters never seen go last
    if letter not in known_order:
        known_order = known_order + letter
secret_order = "".join(by_frequency(letter_counts(secret)))
print("known: ", known_order)
print("secret:", secret_order)


def show(guess):
    right = 0
    for k in range(len(guess)):
        if guess[k] == message.lower()[k] and guess[k] in ALPHABET:
            right = right + 1
    print(guess[:62], "...", right, "right")


guess = substitute(secret, secret_order, known_order)
show(guess)
guess = substitute(guess, "on", "no")          # "pheo" looks like "when"
show(guess)
guess = substitute(guess, "ro", "or")          # "trdab" looks like "today"
show(guess)
print("letters in the message:", sum(letter_counts(message).values()))
Listing 36.8. A first guess from frequencies, then two corrections. code/grade-9/06-first-cryptography/listings/guess_substitution.py
$ python guess_substitution.py
known:  etharnosildwgmupybkcvfjqxz
secret: hrtjadqzlxipcyouwefgbnm
trdab the lawc tgion ro kb stnelm pheo the eveosou uirpn daif, ... 401 right
trdab the lawc tgino rn kb stoelm phen the evensnu uirpo daif, ... 453 right
todab the lawc tginr on kb strelm phen the evensnu uiopr daif, ... 514 right
letters in the message: 810
Output 36.7. Each line shows the start of the guessed message and the number of letters right.

The first guess already gets the right, and about half of the letters. The rest comes from reading: pheo the eveosou looks like when the evening, so o and n swap; then trdab looks like today, so r and o swap. Each correction gets more letters right, from 401 to 453 to 514 of the 810; a few more of the same kind make the whole message clear.

History — Counting letters

In the ninth century, in Baghdad, the scholar al-Kindi wrote a manuscript on deciphering secret messages. His method: take a fairly long text in the same language, count each of its letters, and rank them; then rank the symbols of the secret message the same way, and match first with first, second with second. His own counts used seven pages, 3,667 letters. Much later, in Europe, writers on ciphers such as Alberti, Bellaso and Vigenère described ciphers that change the shift from letter to letter, against this kind of attack.

36.4 A cipher with a keyword

Definition 36.8 (Keyword cipher)

A keyword cipher shifts each letter of the plaintext by a different amount, given in turn by the letters of a keyword (a for 0, b for 1, and so on); after the last letter of the keyword, it starts again from the first.

The keyword lamp over meet me at: each letter moves by the keyword letter above it (l = 11, a = 0, m = 12, p = 15). The two e’s of meet become e and q, and the two m’s both become x, because they fall under the same keyword letter.
The keyword lamp over meet me at: each letter moves by the keyword letter above it (l = 11, a = 0, m = 12, p = 15). The two e’s of meet become e and q, and the two m’s both become x, because they fall under the same keyword letter.
from shift import ALPHABET, shift_letter


def keyword_encrypt(text, keyword):
    """Shift each letter by the next letter of the keyword (a = 0, b = 1, ...)."""
    result = ""
    k = 0
    for letter in text.lower():
        if letter in ALPHABET:
            key = ALPHABET.index(keyword[k % len(keyword)])
            result = result + shift_letter(letter, key)
            k = k + 1
        else:
            result = result + letter
    return result


if __name__ == "__main__":
    print(keyword_encrypt("meet me at the lighthouse at nine", "lamp"))
Listing 36.9. The keyword cipher. code/grade-9/06-first-cryptography/listings/keyword_cipher.py
$ python keyword_cipher.py
xeqi xe mi ehq atgtisoghp af ctnq
Output 36.8. The message with the keyword lamp.

The counter k moves only on letters, so spaces do not use up keyword letters. A same plaintext letter now gives several ciphertext letters, and the frequencies flatten:

from frequencies import by_frequency, letter_counts
from keyword_cipher import keyword_encrypt
from shift import encrypt

with open("passage.txt", encoding="utf-8") as f:
    passage = f.read()
texts = [["plain", passage],
         ["shift 3", encrypt(passage, 3)],
         ["keyword lamp", keyword_encrypt(passage, "lamp")],
         ["keyword lighthouse", keyword_encrypt(passage, "lighthouse")]]
for name, text in texts:
    counts = letter_counts(text)
    total = sum(counts.values())
    top = by_frequency(counts)[:4]
    shares = ""
    for letter in top:
        shares = shares + f"  {letter} {100 * counts[letter] / total:4.1f} %"
    print(f"{name:<19}{shares}")
Listing 36.10. The four most frequent letters, with three ciphers. code/grade-9/06-first-cryptography/listings/keyword_frequencies.py
$ python keyword_frequencies.py
plain                e 14.0 %  t 11.9 %  h  8.5 %  a  7.6 %
shift 3              h 14.0 %  w 11.9 %  k  8.5 %  d  7.6 %
keyword lamp         t 10.3 %  e  9.2 %  p  6.2 %  a  5.9 %
keyword lighthouse   l  6.3 %  z  6.2 %  h  5.9 %  s  5.1 %
Output 36.9. The longer the keyword, the flatter the counts.

The shift cipher keeps the exact counts, just on other letters. With the four-letter keyword, the top letter falls from 14.0 % to 10.3 %; with the ten-letter keyword lighthouse, to 6.3 %, and the top four are nearly level. A longer keyword spreads each letter over more shifts. It can still be broken: each fourth letter is shifted the same way, and repeated groups of letters betray the keyword’s length (Exercise 36.12).

36.5 Why a long random key resists; the padlock in a browser

Every cipher of this chapter is broken by a pattern that the key leaves in the ciphertext. Take that idea to its end: a keyword as long as the message itself, its letters chosen at random (with a generator made for secrets, not random), and never used twice. Then every shift is independent of the others, every plaintext of that length is equally possible, and no counting can help. The price is a key as long as everything one wants to send, shared in advance.

When the address bar of a browser shows a padlock, the page travels between the server and your computer encrypted, and the server has proved its name, so that another machine cannot pretend to be it. The ciphers used there are far stronger than those of this chapter, and the two computers agree on a fresh key without ever sending it in the open. How they do it is told in the next book.

36.6 Exercises

Exercise 36.1 ★

Encrypt code with the shift cipher and the key 3.

Solution

Solution of Exercise 36.1.

frgh: c, o, d, e move three places to f, r, g, h.

Exercise 36.2 ★

The word qeb was encrypted with the key 23. Decrypt it.

Solution

Solution of Exercise 36.2.

Moving back 23 places is the same as moving forward 3: qeb becomes the.

Exercise 36.3 ★

What does count_keys.py compute, step by step, for an alphabet of only 4 letters? How many substitution keys does such an alphabet have?

Solution

Solution of Exercise 36.3.

It multiplies the numbers of choices: 4×3×2×1=244 \times 3 \times 2 \times 1 = 24. Four letters can be mixed in 24 ways, so there are 24 keys, one of which (the alphabet unchanged) hides nothing.

Exercise 36.4 ★

Write a shift cipher that keeps capital letters as capitals and leaves spaces, punctuation and digits unchanged. Try it on Meet Me at Noon, by the Zoo! with the key 3.

Solution

Solution of Exercise 36.4.

Capitals have their own codes, from ord("A"): the function treats each case with its own starting letter.

def shift_letter(letter, key):
    """Move a letter key places, keeping capitals; leave other characters."""
    if "a" <= letter <= "z":
        return chr((ord(letter) - ord("a") + key) % 26 + ord("a"))
    if "A" <= letter <= "Z":
        return chr((ord(letter) - ord("A") + key) % 26 + ord("A"))
    return letter


def encrypt(text, key):
    result = ""
    for letter in text:
        result = result + shift_letter(letter, key)
    return result


print(encrypt("Meet Me at Noon, by the Zoo!", 3))
A shift that keeps capitals. code/grade-9/06-first-cryptography/exercises/shift_case.py

It prints Phhw Ph dw Qrrq, eb wkh Crr!.

Exercise 36.5 ★★

This function forgets the alphabet’s end. What does it print? Fix it.

def shift_letter(letter, key):
    return chr(ord(letter) + key)


print(shift_letter("a", 3), shift_letter("x", 3), shift_letter("z", 3))
Listing 36.11. A shift without the remainder. code/grade-9/06-first-cryptography/exercises/shift_bug.py
Solution

Solution of Exercise 36.5.

It prints d { }: the codes after z’s are those of other characters, the braces { and }. The fix counts the position in the alphabet and keeps the remainder by 26, as shift_letter does in Listing 36.1.

Exercise 36.6 ★★

This program should print the message back. What does it print instead, and why? Fix it.

from shift import encrypt

secret = encrypt("see you at the harbour", 5)
print(encrypt(secret, 5))
Listing 36.12. A decryption. code/grade-9/06-first-cryptography/exercises/decrypt_bug.py
Solution

Solution of Exercise 36.6.

It prints coo iye kd dro rkblyeb: the message shifted by 10, since it shifts by 5 a second time instead of back. Decrypt with encrypt(secret, -5) (or with 21, which goes round to the same place).

Exercise 36.7 ★★

Write a brute-force search that prints only the decryption with the most common English words (the, and, a, to, of, in, at, is, it, on). Try it on vjg mggrgt nkv vjg ncor cv vjg gpf qh vjg fca.

Solution

Solution of Exercise 36.7.

A function scores each candidate by its common words, and the loop keeps the best:

from shift import encrypt

COMMON = ["the", "and", "a", "to", "of", "in", "at", "is", "it", "on"]


def score(text):
    """How many words of text are common English words."""
    points = 0
    for word in text.split():
        if word in COMMON:
            points = points + 1
    return points


def best_decryption(ciphertext):
    best = ""
    for key in range(1, 26):
        candidate = encrypt(ciphertext, -key)
        if score(candidate) > score(best):
            best = candidate
    return best


print(best_decryption("vjg mggrgt nkv vjg ncor cv vjg gpf qh vjg fca"))
The decryption with the most common words. code/grade-9/06-first-cryptography/exercises/best_guess.py

It prints the keeper lit the lamp at the end of the day (the key was 2).

Exercise 36.8 ★★

Write keyword_decrypt(text, keyword), which undoes the keyword cipher, and check it on the ciphertext of Output 36.8.

Solution

Solution of Exercise 36.8.

The same loop as keyword_encrypt, with each shift taken the other way:

from shift import ALPHABET, shift_letter


def keyword_decrypt(text, keyword):
    """Undo the keyword cipher: shift each letter back by the keyword's letter."""
    result = ""
    k = 0
    for letter in text.lower():
        if letter in ALPHABET:
            key = ALPHABET.index(keyword[k % len(keyword)])
            result = result + shift_letter(letter, -key)
            k = k + 1
        else:
            result = result + letter
    return result


print(keyword_decrypt("xeqi xe mi ehq atgtisoghp af ctnq", "lamp"))
Undoing the keyword cipher. code/grade-9/06-first-cryptography/exercises/keyword_decrypt.py

It prints meet me at the lighthouse at nine.

Exercise 36.9 ★★

What does a shift of 26 do to a message? And a shift of 29? Why does the shift cipher have 25 useful keys and not 26 or more?

Solution

Solution of Exercise 36.9.

A shift of 26 takes every letter all the way round, back to itself: the message does not change. A shift of 29 is the same as a shift of 3, because only the remainder by 26 matters. So the keys 1 to 25 are the only different ones that change the message.

Exercise 36.10 ★★★

A computer tries a billion substitution keys per second. How many years does it need to try them all? Compute it with a program.

Solution

Solution of Exercise 36.10.

keys = 1
for choices in range(26, 0, -1):
    keys = keys * choices
seconds = keys / 1_000_000_000          # a billion keys per second
years = seconds / (365 * 24 * 3600)
print(f"{years:,.0f} years")
Trying every substitution key. code/grade-9/06-first-cryptography/exercises/all_keys_time.py

It prints 12,788,288,341 years: almost thirteen billion years. Trying every key is hopeless; frequency analysis does not need to.

Exercise 36.11 ★★★

Count the five most frequent letters in the first 20, 100 and 1,000 letters of the passage, with a program. Use the counts to explain why frequency analysis needs a long ciphertext.

Solution

Solution of Exercise 36.11.

from frequencies import by_frequency, letter_counts

with open("passage.txt", encoding="utf-8") as f:
    letters = ""
    for letter in f.read().lower():
        if "a" <= letter <= "z":
            letters = letters + letter
for length in [20, 100, 1000]:
    counts = letter_counts(letters[:length])
    top = by_frequency(counts)[:5]
    print(length, "letters:", [letter + " " + str(counts[letter]) for letter in top])
Counts on the start of the passage. code/grade-9/06-first-cryptography/exercises/short_counts.py

It prints, for 20 letters, t 3, h 3, e 2, o 2, l 2; for 100, e 18, t 11, h 11, r 9, a 8; for 1,000, e 150, t 123, h 80, o 68, a 68. In 20 letters, every letter appears only a few times, and one word more or less changes the order: e is not even first. With 1,000 letters, the order is close to that of the whole passage. A frequency guess needs enough letters for the counts to settle, as the frequency of a six did in Chapter 35.

Exercise 36.12 ★★★

The passage, without spaces, is encrypted with the keyword lamp. Write a program that finds every group of three letters that appears again later in the ciphertext, and records the distance between the two places. Then count, for each length from 2 to 8, how many distances it divides. Which length stands out, and why?

Solution

Solution of Exercise 36.12.

A dictionary remembers where each group of three letters was last seen:

from keyword_cipher import keyword_encrypt

with open("passage.txt", encoding="utf-8") as f:
    letters = ""
    for letter in f.read().lower():
        if "a" <= letter <= "z":
            letters = letters + letter
secret = keyword_encrypt(letters, "lamp")

first_seen = {}
distances = []
for k in range(len(secret) - 2):
    group = secret[k:k + 3]
    if group in first_seen:
        distances.append(k - first_seen[group])
    first_seen[group] = k
print(len(distances), "repeats; the first ten distances:", distances[:10])
for length in range(2, 9):
    divides = 0
    for d in distances:
        if d % length == 0:
            divides = divides + 1
    print(f"length {length}: divides {divides} distances")
Repeated groups and their distances. code/grade-9/06-first-cryptography/exercises/repeats.py

It finds 372 repeats. Among the lengths 3 to 8, length 4 divides by far the most distances: 333, against 132 for 3 and 155 for 8. A word such as the gives the same three ciphertext letters only when it falls under the same part of the keyword, so the distance between the two places is a multiple of 4. Length 2 divides even more distances (352), but only because every multiple of 4 is also even: the keyword’s length is the largest length that divides nearly as many.

36.7 Problem: Breaking a Message without the Key

Problem 36.1

Weekend problem — breaking a message without the key

A message from the passage has been encrypted with the shift cipher and an unknown key. Can a program find the key with no help but letter counts? And how long must the message be?

Part I — By hand.

from frequencies import by_frequency, letter_counts
from shift import encrypt


def guess_key(ciphertext):
    """Guess a shift key: the most frequent letter is taken to be an e."""
    top = by_frequency(letter_counts(ciphertext))[0]
    return (ord(top) - ord("e")) % 26


if __name__ == "__main__":
    with open("passage.txt", encoding="utf-8") as f:
        message = f.read().split("\n\n")[1]
    secret = encrypt(message, 11)
    print(secret.split("\n")[0])
    key = guess_key(secret)
    print("guessed key:", key)
    print(encrypt(secret, -key).split("\n")[0])
    print("whole message right:", encrypt(secret, -key) == message.lower())
Listing 36.13. Guessing a shift key from the most frequent letter. code/grade-9/06-first-cryptography/listings/guess_shift.py
$ python guess_shift.py
esp wzrmzzvd lcp vpae ezolj ty l dxlww czzx zq esp ezhy xfdpfx. lyjzyp nly cplo espx.
Output 36.10. The first line of the ciphertext. Some lines are left out.
  1. Count the letters of this line by hand. Which letter is the most frequent?
  2. If that letter stands for e, what is the key?
  3. Decrypt the first word with that key. Does it make sense? If not, try the second most frequent letter.

Part II — A program guesses.

  1. What does guess_key assume, and how does it turn the most frequent letter into a key?
  2. Why is the result taken modulo 26?
  3. Run the program. Does it find the key, and is the whole message right?
  4. On which kind of message would this guess fail, even if it were long?

Part III — How long must the message be?

import random

from guess_shift import guess_key
from shift import encrypt

with open("passage.txt", encoding="utf-8") as f:
    letters = ""
    for letter in f.read().lower():
        if "a" <= letter <= "z":
            letters = letters + letter

random.seed(9)
for length in [10, 20, 50, 100, 200, 500, 1000]:
    right = 0
    for _ in range(100):
        start = random.randint(0, len(letters) - length)
        message = letters[start:start + length]
        key = random.randint(1, 25)
        if guess_key(encrypt(message, key)) == key:
            right = right + 1
    print(f"{length:>4} letters: key found {right:>3} times out of 100")
Listing 36.14. Guessing the key of 100 messages of each length. code/grade-9/06-first-cryptography/listings/short_messages.py
  1. Where do the 100 messages of each length come from, and with which keys are they encrypted?
  2. Run it. How often is the key found with 10 letters? With 100?
  3. Why is 200 letters barely better than 100, and 500 letters perfect?
  4. What does this tell Lina and Sami about short notes?
  5. State the result.
Solution

Solution of Problem 36.1.

1. z appears 9 times, p 8, l 7, e 6.

2. Counting from 0, as ord(letter) - ord("a") does, z is at position 25 and e at position 4: 25−4=2125 - 4 = 21.

3. With 21, esp becomes jxu, which means nothing. With the second letter, p: 15−4=1115 - 4 = 11, and esp becomes the. On one line, o (here z) happened to beat e.

4. That the most frequent letter of the ciphertext stands for e. The key is the distance from e to that letter.

5. The letter may come before e in the alphabet: for b, 1−4=−31 - 4 = -3, and the remainder by 26 turns it into the key 23.

$ python guess_shift.py
esp wzrmzzvd lcp vpae ezolj ty l dxlww czzx zq esp ezhy xfdpfx. lyjzyp nly cplo espx.
guessed key: 11
the logbooks are kept today in a small room of the town museum. anyone can read them.
whole message right: True
Output 36.11. The whole paragraph, decrypted.

6. Yes: the key 11, and every letter of the paragraph is right.

7. On a message where e is not the most frequent letter: a list of names, a text in another language, or a text written to avoid the letter e.

8. Each message is a run of letters cut from a random place of the passage, and each is encrypted with its own random key from 1 to 25.

$ python short_messages.py
  10 letters: key found  23 times out of 100
  20 letters: key found  33 times out of 100
  50 letters: key found  46 times out of 100
 100 letters: key found  56 times out of 100
 200 letters: key found  57 times out of 100
 500 letters: key found 100 times out of 100
1000 letters: key found 100 times out of 100
Output 36.12. The share of keys found, by length.

9. 23 times out of 100 with 10 letters, 56 with 100.

10. In this passage, t comes close behind e (11.9 % against 14.0 %): in 100 or 200 letters, a few more t’s often put t first. With 500 letters, the gap of about ten letters is larger than the luck of the cut. And runs of 500 or 1,000 letters take a large part of a 1,517-letter passage, where e leads clearly.

11. A short note is hard to break by counting: its frequencies are not yet those of the language. But the shift cipher has only 25 keys, so trying them all still breaks any note, however short.

12. Result. The guess from the most frequent letter finds the key of a 10-letter message 23 times out of 100, of a 100-letter one 56 times, and of messages of 500 or 1,000 letters every time.

এই অধ্যায়ে সংজ্ঞায়িত পরিভাষা-শব্দ

পরিভাষায় সব 1050 টি শব্দ দেখো