cribs 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cribs/__init__.py +52 -0
- cribs/basics.py +55 -0
- cribs/clues.py +39 -0
- cribs/coincidence.py +25 -0
- cribs/data/quadgrams.txt.gz +0 -0
- cribs/data/words.txt.gz +0 -0
- cribs/data.py +31 -0
- cribs/frequency.py +30 -0
- cribs/keys.py +21 -0
- cribs/pairs.py +69 -0
- cribs/patterns.py +30 -0
- cribs/repeats.py +46 -0
- cribs/scoring.py +46 -0
- cribs/transposition.py +44 -0
- cribs-0.1.1.dist-info/METADATA +96 -0
- cribs-0.1.1.dist-info/RECORD +18 -0
- cribs-0.1.1.dist-info/WHEEL +4 -0
- cribs-0.1.1.dist-info/licenses/LICENSE +21 -0
cribs/__init__.py
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
"""cribs: the companion package of *Cryptanalysis guides for young codebreakers*.
|
|
2
|
+
|
|
3
|
+
One import line, ``import cribs``, gives every function of the book: ``cribs.caesar(t, 3)``.
|
|
4
|
+
Each module is one chapter of the book, imported here in book order (a module may use only
|
|
5
|
+
the names of the modules above it), and every public name is re-exported.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from cribs.basics import (
|
|
9
|
+
ALPHABET, caesar, chunks, columns, grouped, letters, ngrams, shift, show_grid, to_letter,
|
|
10
|
+
to_number,
|
|
11
|
+
)
|
|
12
|
+
from cribs.clues import bars, clues, divisors, doubled_pairs, ioc, symbols
|
|
13
|
+
from cribs.frequency import ENGLISH, best_shift, by_frequency, chi_squared, substitute
|
|
14
|
+
from cribs.keys import affine, affine_decrypt, affine_keys
|
|
15
|
+
from cribs.coincidence import average_ioc, friedman, vigenere, vigenere_decrypt
|
|
16
|
+
from cribs.repeats import autokey_decrypt, beaufort, factor_table, find_key, gaps, repeats, where
|
|
17
|
+
from cribs.data import FLOOR, QUADGRAMS, WORDS
|
|
18
|
+
from cribs.patterns import candidates, drag, keyword_alphabet, pattern, stacked_pairs
|
|
19
|
+
from cribs.transposition import (
|
|
20
|
+
CONTACTS, block_order, columnar_order, contacts, key_order, pick, rail_order, unpick,
|
|
21
|
+
)
|
|
22
|
+
from cribs.scoring import annealing, climb, fitness, make_scores, swapped, uphill
|
|
23
|
+
from cribs.pairs import (
|
|
24
|
+
cell, hill, hill_crib, hill_inverse, playfair, playfair_pair, playfair_ready, polybius,
|
|
25
|
+
row_col, square,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
__all__ = [
|
|
29
|
+
# the primer
|
|
30
|
+
"ALPHABET", "chunks", "grouped", "show_grid", "columns", "ngrams", "letters", "to_number",
|
|
31
|
+
"to_letter", "shift", "caesar",
|
|
32
|
+
# 01
|
|
33
|
+
"symbols", "divisors", "ioc", "doubled_pairs", "bars", "clues",
|
|
34
|
+
# 02
|
|
35
|
+
"ENGLISH", "chi_squared", "best_shift", "substitute", "by_frequency",
|
|
36
|
+
# 03
|
|
37
|
+
"affine", "affine_decrypt", "affine_keys",
|
|
38
|
+
# 04
|
|
39
|
+
"vigenere", "vigenere_decrypt", "average_ioc", "friedman",
|
|
40
|
+
# 05
|
|
41
|
+
"where", "repeats", "gaps", "factor_table", "find_key", "beaufort", "autokey_decrypt",
|
|
42
|
+
# 06
|
|
43
|
+
"pattern", "candidates", "keyword_alphabet", "drag", "stacked_pairs", "WORDS",
|
|
44
|
+
# 07
|
|
45
|
+
"pick", "unpick", "key_order", "rail_order", "columnar_order", "block_order", "CONTACTS",
|
|
46
|
+
"contacts",
|
|
47
|
+
# 08
|
|
48
|
+
"make_scores", "QUADGRAMS", "FLOOR", "fitness", "swapped", "uphill", "annealing", "climb",
|
|
49
|
+
# 09
|
|
50
|
+
"square", "polybius", "row_col", "cell", "playfair_pair", "playfair", "playfair_ready",
|
|
51
|
+
"hill", "hill_inverse", "hill_crib",
|
|
52
|
+
]
|
cribs/basics.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
"""The primer, Python for codebreakers: cutting a text up, cleaning it, and letters as numbers."""
|
|
2
|
+
|
|
3
|
+
# The 26 capital letters, in order.
|
|
4
|
+
ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def chunks(text, n):
|
|
8
|
+
"""text cut into pieces of n letters (the last one may be shorter)."""
|
|
9
|
+
return [text[i:i + n] for i in range(0, len(text), n)]
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def grouped(text, n=5):
|
|
13
|
+
"""text in blocks of n, the way ciphertexts are printed."""
|
|
14
|
+
return " ".join(chunks(text, n))
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def show_grid(text, width):
|
|
18
|
+
"""Print text in rows of width letters."""
|
|
19
|
+
for row in chunks(text, width):
|
|
20
|
+
print(" ".join(row))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def columns(text, n):
|
|
24
|
+
"""The n columns of text written in rows of n: every n-th letter."""
|
|
25
|
+
return [text[i::n] for i in range(n)]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def ngrams(text, n):
|
|
29
|
+
"""Every run of n letters in a row: the windows of a sliding window."""
|
|
30
|
+
return [text[i:i + n] for i in range(len(text) - n + 1)]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def letters(text):
|
|
34
|
+
"""Only the letters of text, in capitals."""
|
|
35
|
+
return "".join(filter(str.isalpha, text.upper()))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def to_number(letter):
|
|
39
|
+
"""A=0, B=1, ..., Z=25."""
|
|
40
|
+
return ALPHABET.index(letter)
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def to_letter(number):
|
|
44
|
+
"""0=A, 1=B, ..., wrapping round: 26 is A again, -1 is Z."""
|
|
45
|
+
return ALPHABET[number % 26]
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def shift(letter, k):
|
|
49
|
+
"""letter moved k places along the alphabet."""
|
|
50
|
+
return to_letter(to_number(letter) + k)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def caesar(text, k):
|
|
54
|
+
"""Every letter of text moved k places: k to encrypt, -k to decrypt."""
|
|
55
|
+
return "".join(shift(ch, k) for ch in text)
|
cribs/clues.py
ADDED
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Guide 01, Reading the clues: the measurements that say what kind of cipher a text is."""
|
|
2
|
+
|
|
3
|
+
from collections import Counter
|
|
4
|
+
from cribs import letters
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def symbols(text):
|
|
8
|
+
"""Every different symbol in text, in order, spaces and line breaks left out."""
|
|
9
|
+
return "".join(sorted(set("".join(text.split()))))
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def divisors(n):
|
|
13
|
+
"""The whole numbers from 2 to n that divide n exactly."""
|
|
14
|
+
return [d for d in range(2, n + 1) if n % d == 0]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def ioc(text):
|
|
18
|
+
"""The index of coincidence: the chance two letters picked at random match."""
|
|
19
|
+
n = len(text)
|
|
20
|
+
return sum(f * (f - 1) for f in Counter(text).values()) / (n * (n - 1))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def doubled_pairs(text):
|
|
24
|
+
"""How many of the pairs AB CD EF ... are one letter twice."""
|
|
25
|
+
return sum(a == b for a, b in zip(text[::2], text[1::2]))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def bars(text):
|
|
29
|
+
"""A bar chart of the letter counts, one row per letter."""
|
|
30
|
+
for letter, n in sorted(Counter(text).items()):
|
|
31
|
+
print(letter, "#" * n)
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def clues(text):
|
|
35
|
+
"""The clues of Guide 01, measured."""
|
|
36
|
+
t = letters(text)
|
|
37
|
+
return {"symbols": symbols(text), "length": len(t), "divisors": divisors(len(t)),
|
|
38
|
+
"commonest": Counter(t).most_common(6), "ioc": round(ioc(t), 3),
|
|
39
|
+
"doubled pairs": doubled_pairs(t)}
|
cribs/coincidence.py
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
"""Guide 04, Index of coincidence: the Vigenère cipher and how to measure its key length."""
|
|
2
|
+
|
|
3
|
+
from itertools import cycle
|
|
4
|
+
from statistics import mean
|
|
5
|
+
from cribs import columns, ioc, shift, to_number
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def vigenere(text, key):
|
|
9
|
+
"""Shift each letter by the key letter under it; the key repeats."""
|
|
10
|
+
return "".join(shift(ch, to_number(k)) for ch, k in zip(text, cycle(key)))
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def vigenere_decrypt(text, key):
|
|
14
|
+
"""Undo vigenere(text, key): shift back by each key letter."""
|
|
15
|
+
return "".join(shift(ch, -to_number(k)) for ch, k in zip(text, cycle(key)))
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def average_ioc(text, n):
|
|
19
|
+
"""The average IoC of the n columns: near 0.066 when n is the key length."""
|
|
20
|
+
return mean(ioc(col) for col in columns(text, n))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def friedman(text, english=0.066, flat=1 / 26):
|
|
24
|
+
"""Friedman's rough estimate of a Vigenère key's length."""
|
|
25
|
+
return (english - flat) / (ioc(text) - flat)
|
|
Binary file
|
cribs/data/words.txt.gz
ADDED
|
Binary file
|
cribs/data.py
ADDED
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""The two tables that come with cribs, read once on import (the book does not spell this out).
|
|
2
|
+
|
|
3
|
+
Both were counted by ``tools/build_data.py`` from twelve public-domain novels: the quadgram
|
|
4
|
+
table is what ``make_scores`` gives on them (each quadgram scored as log10 of its share; those
|
|
5
|
+
seen only once are left to the floor), and
|
|
6
|
+
``WORDS`` holds the 5,000 commonest words, most frequent first.
|
|
7
|
+
"""
|
|
8
|
+
|
|
9
|
+
import gzip
|
|
10
|
+
from importlib.resources import files
|
|
11
|
+
from math import log10
|
|
12
|
+
|
|
13
|
+
_DATA = files("cribs") / "data"
|
|
14
|
+
COMMON_WORDS = 5000
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _rows(name):
|
|
18
|
+
with gzip.open(str(_DATA / name), "rt", encoding="utf-8") as f:
|
|
19
|
+
return [line.rstrip("\n").split("\t") for line in f]
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _quadgrams():
|
|
23
|
+
header, *rows = _rows("quadgrams.txt.gz")
|
|
24
|
+
total = int(header[1])
|
|
25
|
+
return {g: log10(int(c) / total) for g, c in rows}, log10(0.1 / total)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# The quadgrams of the novels with their scores, and the floor for one never seen.
|
|
29
|
+
QUADGRAMS, FLOOR = _quadgrams()
|
|
30
|
+
# The 5,000 commonest words in the novels, commonest first.
|
|
31
|
+
WORDS = [w for w, _ in _rows("words.txt.gz")[:COMMON_WORDS]]
|
cribs/frequency.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Guide 02, Frequency analysis: how English a text's letter counts look, and substitution."""
|
|
2
|
+
|
|
3
|
+
from collections import Counter
|
|
4
|
+
from cribs import ALPHABET, caesar
|
|
5
|
+
|
|
6
|
+
# How often each letter turns up in English, as a share of all letters.
|
|
7
|
+
ENGLISH = dict(zip(ALPHABET, [
|
|
8
|
+
0.082, 0.015, 0.028, 0.043, 0.127, 0.022, 0.020, 0.061, 0.070, 0.0015, 0.0077, 0.040, 0.024,
|
|
9
|
+
0.067, 0.075, 0.019, 0.00095, 0.060, 0.063, 0.091, 0.028, 0.0098, 0.024, 0.0015, 0.020, 0.00074]))
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def chi_squared(text):
|
|
13
|
+
"""How far text's letter counts are from English's: low means English."""
|
|
14
|
+
n, counts = len(text), Counter(text)
|
|
15
|
+
return sum((counts[ch] - n * p) ** 2 / (n * p) for ch, p in ENGLISH.items())
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def best_shift(text):
|
|
19
|
+
"""The Caesar key whose decryption looks most like English."""
|
|
20
|
+
return min(range(26), key=lambda k: chi_squared(caesar(text, -k)))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def substitute(text, old, new):
|
|
24
|
+
"""text with each letter of old swapped for the letter of new in the same place."""
|
|
25
|
+
return text.translate(str.maketrans(old, new))
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def by_frequency(text):
|
|
29
|
+
"""The letters of text, commonest first."""
|
|
30
|
+
return "".join(letter for letter, n in Counter(text).most_common())
|
cribs/keys.py
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
"""Guide 03, Keys and brute force: the affine cipher, and trying every key."""
|
|
2
|
+
|
|
3
|
+
from itertools import product
|
|
4
|
+
from math import gcd
|
|
5
|
+
from cribs import to_letter, to_number
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def affine(text, a, b):
|
|
9
|
+
"""The affine cipher: each letter x becomes a*x + b, mod 26."""
|
|
10
|
+
return "".join(to_letter(a * to_number(ch) + b) for ch in text)
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def affine_decrypt(text, a, b):
|
|
14
|
+
"""Undo affine(text, a, b): itself an affine cipher, with a's inverse."""
|
|
15
|
+
inv = pow(a, -1, 26)
|
|
16
|
+
return affine(text, inv, -inv * b)
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def affine_keys():
|
|
20
|
+
"""All 312 affine keys (a, b): a must share no factor with 26."""
|
|
21
|
+
return [(a, b) for a, b in product(range(26), repeat=2) if gcd(a, 26) == 1]
|
cribs/pairs.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"""Guide 09, Two letters at a time: Polybius and Playfair squares, and the Hill cipher."""
|
|
2
|
+
|
|
3
|
+
from itertools import product
|
|
4
|
+
from cribs import ALPHABET, letters, to_letter, to_number
|
|
5
|
+
|
|
6
|
+
|
|
7
|
+
def square(keyword=""):
|
|
8
|
+
"""A 5x5 square as 25 letters: the keyword's letters once, then the rest; no J."""
|
|
9
|
+
return "".join(dict.fromkeys((keyword + ALPHABET).replace("J", "I")))
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def polybius(text, sq=square()):
|
|
13
|
+
"""Each letter as its row and column in the square, 1 to 5."""
|
|
14
|
+
return " ".join(str(sq.index(ch) // 5 + 1) + str(sq.index(ch) % 5 + 1) for ch in text)
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def row_col(letter, sq):
|
|
18
|
+
"""Where letter sits in the square: (row, column), counting from 0."""
|
|
19
|
+
i = sq.index(letter)
|
|
20
|
+
return i // 5, i % 5
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def cell(row, col, sq):
|
|
24
|
+
"""The letter at (row, col) of the square, wrapping round at the edges."""
|
|
25
|
+
return sq[row % 5 * 5 + col % 5]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def playfair_pair(a, b, sq, step=1):
|
|
29
|
+
"""One pair through Playfair's three rules: step 1 encrypts, -1 decrypts."""
|
|
30
|
+
(ra, ca), (rb, cb) = row_col(a, sq), row_col(b, sq)
|
|
31
|
+
if ra == rb:
|
|
32
|
+
return cell(ra, ca + step, sq) + cell(rb, cb + step, sq)
|
|
33
|
+
if ca == cb:
|
|
34
|
+
return cell(ra + step, ca, sq) + cell(rb + step, cb, sq)
|
|
35
|
+
return cell(ra, cb, sq) + cell(rb, ca, sq)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def playfair(text, sq, step=1):
|
|
39
|
+
"""Playfair on a whole text, pair by pair: step=-1 decrypts."""
|
|
40
|
+
return "".join(playfair_pair(a, b, sq, step) for a, b in zip(text[::2], text[1::2]))
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def playfair_ready(text):
|
|
44
|
+
"""Letters only, J as I, an X between doubled letters in a pair, an X to make it even."""
|
|
45
|
+
out = ""
|
|
46
|
+
for ch in letters(text).replace("J", "I"):
|
|
47
|
+
if len(out) % 2 == 1 and out[-1] == ch:
|
|
48
|
+
out += "X"
|
|
49
|
+
out += ch
|
|
50
|
+
return out + "X" * (len(out) % 2)
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def hill(text, key):
|
|
54
|
+
"""The 2x2 Hill cipher with key (a, b, c, d), pair by pair."""
|
|
55
|
+
a, b, c, d = key
|
|
56
|
+
xs = list(map(to_number, text))
|
|
57
|
+
return "".join(to_letter(a * x + b * y) + to_letter(c * x + d * y) for x, y in zip(xs[::2], xs[1::2]))
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def hill_inverse(key):
|
|
61
|
+
"""The key that undoes hill(text, key)."""
|
|
62
|
+
a, b, c, d = key
|
|
63
|
+
r = pow(a * d - b * c, -1, 26)
|
|
64
|
+
return (r * d % 26, -r * b % 26, -r * c % 26, r * a % 26)
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
def hill_crib(plain, cipher):
|
|
68
|
+
"""Every Hill key that turns the 4-letter crib plain into cipher."""
|
|
69
|
+
return [k for k in product(range(26), repeat=4) if hill(plain, k) == cipher]
|
cribs/patterns.py
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
"""Guide 06, Cribs and patterns: word shapes, keyword alphabets and dragging a crib."""
|
|
2
|
+
|
|
3
|
+
from cribs import ALPHABET, vigenere_decrypt
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def pattern(word):
|
|
7
|
+
"""The shape of a word: THAT is ABCA, LETTER is ABCCBD."""
|
|
8
|
+
firsts = list(dict.fromkeys(word))
|
|
9
|
+
return "".join(ALPHABET[firsts.index(ch)] for ch in word)
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
def candidates(cipher_word, words):
|
|
13
|
+
"""The words with the same pattern as cipher_word."""
|
|
14
|
+
return [w for w in words if pattern(w) == pattern(cipher_word)]
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def keyword_alphabet(keyword):
|
|
18
|
+
"""A cipher alphabet from a keyword: its letters once, then on from its last letter."""
|
|
19
|
+
rest = ALPHABET.index(keyword[-1]) + 1
|
|
20
|
+
return "".join(dict.fromkeys(keyword + ALPHABET[rest:] + ALPHABET[:rest]))
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
def drag(text, crib):
|
|
24
|
+
"""The key fragment the crib gives at every position of a Vigenère text."""
|
|
25
|
+
return [vigenere_decrypt(text[i:i + len(crib)], crib) for i in range(len(text) - len(crib) + 1)]
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def stacked_pairs(crib, width):
|
|
29
|
+
"""The pairs a columnar transposition of this width puts side by side."""
|
|
30
|
+
return [a + b for a, b in zip(crib, crib[width:])]
|
cribs/repeats.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Guide 05, Repeats and key length: Kasiski's repeats, the key itself, Beaufort and autokey."""
|
|
2
|
+
|
|
3
|
+
from collections import Counter
|
|
4
|
+
from itertools import cycle
|
|
5
|
+
from cribs import best_shift, columns, ngrams, shift, to_letter, to_number
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
def where(text, piece):
|
|
9
|
+
"""Every position where piece starts in text (counting from 0)."""
|
|
10
|
+
return [i for i in range(len(text)) if text[i:i + len(piece)] == piece]
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def repeats(text, n=3):
|
|
14
|
+
"""Each run of n letters seen more than once, with where it starts."""
|
|
15
|
+
return {g: where(text, g) for g, c in Counter(ngrams(text, n)).items() if c > 1}
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def gaps(text, n=3):
|
|
19
|
+
"""The distances between neighbouring copies of each repeat."""
|
|
20
|
+
found = []
|
|
21
|
+
for places in repeats(text, n).values():
|
|
22
|
+
found += [b - a for a, b in zip(places, places[1:])]
|
|
23
|
+
return found
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def factor_table(gaps, largest=12):
|
|
27
|
+
"""For each d from 2 to largest, how many of the gaps d divides."""
|
|
28
|
+
return {d: sum(g % d == 0 for g in gaps) for d in range(2, largest + 1)}
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
def find_key(text, n):
|
|
32
|
+
"""A Vigenère key of length n: each column solved as a Caesar cipher."""
|
|
33
|
+
return "".join(to_letter(best_shift(col)) for col in columns(text, n))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def beaufort(text, key):
|
|
37
|
+
"""Beaufort: key minus letter. The same function encrypts and decrypts."""
|
|
38
|
+
return "".join(to_letter(to_number(k) - to_number(ch)) for ch, k in zip(text, cycle(key)))
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def autokey_decrypt(text, primer):
|
|
42
|
+
"""Undo vigenere(plain, primer + plain): the key grows from the message itself."""
|
|
43
|
+
plain = ""
|
|
44
|
+
for ch in text:
|
|
45
|
+
plain += shift(ch, -to_number((primer + plain)[len(plain)]))
|
|
46
|
+
return plain
|
cribs/scoring.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
"""Guide 08, Scoring and hill climbing: how English a text looks, and climbing towards the key."""
|
|
2
|
+
|
|
3
|
+
from collections import Counter
|
|
4
|
+
from math import log10
|
|
5
|
+
from random import random, sample
|
|
6
|
+
from cribs import FLOOR, QUADGRAMS, ngrams
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def make_scores(sample_text, n=4):
|
|
10
|
+
"""log10 of each n-gram's share of sample_text, and the floor for unseen ones."""
|
|
11
|
+
counts = Counter(ngrams(sample_text, n))
|
|
12
|
+
total = sum(counts.values())
|
|
13
|
+
return {g: log10(c / total) for g, c in counts.items()}, log10(0.1 / total)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def fitness(text):
|
|
17
|
+
"""How English text looks: the sum of its quadgrams' scores (closer to 0 is better)."""
|
|
18
|
+
return sum(QUADGRAMS.get(q, FLOOR) for q in ngrams(text, 4))
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def swapped(key):
|
|
22
|
+
"""key with two of its letters, picked at random, swapped."""
|
|
23
|
+
a, b = sample(key, 2)
|
|
24
|
+
return key.translate(str.maketrans(a + b, b + a))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def uphill(change, progress):
|
|
28
|
+
"""Hill climbing's rule: keep a new key only if it scores better."""
|
|
29
|
+
return change > 0
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def annealing(change, progress, hot=30, cold=0.3):
|
|
33
|
+
"""Simulated annealing's rule: sometimes keep a worse key, less often as it cools."""
|
|
34
|
+
temperature = hot * (cold / hot) ** progress
|
|
35
|
+
return change > 0 or random() < 10 ** (change / temperature)
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def climb(text, decrypt, key, accept=uphill, move=swapped, steps=4000):
|
|
39
|
+
"""Change the key a little, again and again, keeping the changes accept allows."""
|
|
40
|
+
best = fitness(decrypt(text, key))
|
|
41
|
+
for step in range(steps):
|
|
42
|
+
new = move(key)
|
|
43
|
+
change = fitness(decrypt(text, new)) - best
|
|
44
|
+
if accept(change, step / steps):
|
|
45
|
+
key, best = new, best + change
|
|
46
|
+
return key, best
|
cribs/transposition.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""Guide 07, Transposition detective work: every transposition is a list of positions."""
|
|
2
|
+
|
|
3
|
+
from cribs import ngrams
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def pick(text, order):
|
|
7
|
+
"""The letters of text, taken in the order of the positions in order."""
|
|
8
|
+
return "".join(text[i] for i in order)
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def unpick(text, order):
|
|
12
|
+
"""Undo pick: put each letter back at the position it was taken from."""
|
|
13
|
+
return "".join(ch for i, ch in sorted(zip(order, text)))
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def key_order(keyword):
|
|
17
|
+
"""The order a keyword numbers its columns: TIGER gives [3, 2, 1, 4, 0]."""
|
|
18
|
+
return sorted(range(len(keyword)), key=lambda i: keyword[i])
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
def rail_order(n, rails):
|
|
22
|
+
"""The positions of an n-letter text, read rail by rail along a zigzag."""
|
|
23
|
+
lap = 2 * rails - 2
|
|
24
|
+
return sorted(range(n), key=lambda i: min(i % lap, lap - i % lap))
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def columnar_order(n, keyword):
|
|
28
|
+
"""The positions of an n-letter text, read down the columns in the keyword's order."""
|
|
29
|
+
w = len(keyword)
|
|
30
|
+
return [i for c in key_order(keyword) for i in range(c, n, w)]
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def block_order(n, order):
|
|
34
|
+
"""The positions of an n-letter text, each block reordered the same way."""
|
|
35
|
+
return [start + i for start in range(0, n, len(order)) for i in order]
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
# The commonest pairs of letters in English.
|
|
39
|
+
CONTACTS = {"TH", "HE", "IN", "ER", "AN", "RE", "ON", "AT", "EN", "ND", "ST", "ES"}
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def contacts(text):
|
|
43
|
+
"""How many of the commonest English pairs text contains."""
|
|
44
|
+
return sum(pair in CONTACTS for pair in ngrams(text, 2))
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: cribs
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: The companion package of a cryptology book for young codebreakers: short functions to break classical ciphers, standard library only.
|
|
5
|
+
Project-URL: Homepage, https://github.com/thorwhalen/cribs
|
|
6
|
+
Project-URL: Repository, https://github.com/thorwhalen/cribs
|
|
7
|
+
Project-URL: Documentation, https://thorwhalen.github.io/cribs
|
|
8
|
+
Author: Thor Whalen
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: ciphers,codebreaking,cryptanalysis,cryptology,education
|
|
12
|
+
Requires-Python: >=3.10
|
|
13
|
+
Provides-Extra: dev
|
|
14
|
+
Requires-Dist: pytest-cov>=4.0; extra == 'dev'
|
|
15
|
+
Requires-Dist: pytest>=7.0; extra == 'dev'
|
|
16
|
+
Requires-Dist: ruff>=0.1.0; extra == 'dev'
|
|
17
|
+
Provides-Extra: docs
|
|
18
|
+
Requires-Dist: sphinx-rtd-theme>=1.0; extra == 'docs'
|
|
19
|
+
Requires-Dist: sphinx>=6.0; extra == 'docs'
|
|
20
|
+
Description-Content-Type: text/markdown
|
|
21
|
+
|
|
22
|
+
# cribs
|
|
23
|
+
|
|
24
|
+
The companion package of the book *Cryptanalysis guides for young codebreakers*: short functions that break classical ciphers, standard library only.
|
|
25
|
+
|
|
26
|
+
```
|
|
27
|
+
pip install cribs
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
(In a Colab or Jupyter notebook: `%pip install cribs`. Note the **s**: `crib` on PyPI is an unrelated package.)
|
|
31
|
+
|
|
32
|
+
```python
|
|
33
|
+
import cribs
|
|
34
|
+
|
|
35
|
+
t = cribs.caesar("MEETMEATTHEOLDMILL", 3) # 'PHHWPHDWWKHROGPLOO'
|
|
36
|
+
cribs.best_shift(t) # 3: the key whose decryption looks most like English
|
|
37
|
+
cribs.caesar(t, -3) # 'MEETMEATTHEOLDMILL'
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## What is in it
|
|
41
|
+
|
|
42
|
+
Every function is spelled out, and explained, in the book: the book prints the package's own source, so what you read is what you run. Each module is one chapter, but `import cribs` gives you everything, so you never need more than `cribs.<name>`.
|
|
43
|
+
|
|
44
|
+
| Module | Chapter | Functions |
|
|
45
|
+
|---|---|---|
|
|
46
|
+
| `basics` | Python for codebreakers | `chunks`, `grouped`, `show_grid`, `columns`, `ngrams`, `letters`, `ALPHABET`, `to_number`, `to_letter`, `shift`, `caesar` |
|
|
47
|
+
| `clues` | 01 Reading the clues | `symbols`, `divisors`, `ioc`, `doubled_pairs`, `bars`, `clues` |
|
|
48
|
+
| `frequency` | 02 Frequency analysis | `ENGLISH`, `chi_squared`, `best_shift`, `substitute`, `by_frequency` |
|
|
49
|
+
| `keys` | 03 Keys and brute force | `affine`, `affine_decrypt`, `affine_keys` |
|
|
50
|
+
| `coincidence` | 04 Index of coincidence | `vigenere`, `vigenere_decrypt`, `average_ioc`, `friedman` |
|
|
51
|
+
| `repeats` | 05 Repeats and key length | `where`, `repeats`, `gaps`, `factor_table`, `find_key`, `beaufort`, `autokey_decrypt` |
|
|
52
|
+
| `patterns` | 06 Cribs and patterns | `pattern`, `candidates`, `keyword_alphabet`, `drag`, `stacked_pairs`, `WORDS` |
|
|
53
|
+
| `transposition` | 07 Transposition detective work | `pick`, `unpick`, `key_order`, `rail_order`, `columnar_order`, `block_order`, `CONTACTS`, `contacts` |
|
|
54
|
+
| `scoring` | 08 Scoring and hill climbing | `make_scores`, `QUADGRAMS`, `FLOOR`, `fitness`, `swapped`, `uphill`, `annealing`, `climb` |
|
|
55
|
+
| `pairs` | 09 Two letters at a time | `square`, `polybius`, `row_col`, `cell`, `playfair_pair`, `playfair`, `playfair_ready`, `hill`, `hill_inverse`, `hill_crib` |
|
|
56
|
+
|
|
57
|
+
The rules the code keeps, because its readers are 11 to 13: no classes, no dependencies, every function at most 7 lines (a test checks it), and each function built from earlier ones. Texts are cleaned once with `letters` (capitals A to Z only), and every other function expects that.
|
|
58
|
+
|
|
59
|
+
## A bigger example: a substitution cracked by simulated annealing
|
|
60
|
+
|
|
61
|
+
```python
|
|
62
|
+
import random
|
|
63
|
+
import cribs
|
|
64
|
+
|
|
65
|
+
plain = cribs.letters("The old lighthouse keeper had kept a diary for forty years ...") # a few hundred letters
|
|
66
|
+
secret = "".join(random.sample(cribs.ALPHABET, 26))
|
|
67
|
+
cipher = cribs.substitute(plain, cribs.ALPHABET, secret)
|
|
68
|
+
|
|
69
|
+
decrypt = lambda text, key: cribs.substitute(text, key, cribs.ALPHABET)
|
|
70
|
+
start = "".join(random.sample(cribs.ALPHABET, 26))
|
|
71
|
+
key, score = cribs.climb(cipher, decrypt, start, accept=cribs.annealing, steps=8000)
|
|
72
|
+
print(decrypt(cipher, key))
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
`climb` takes the decryption, the move and the acceptance rule as arguments, so hill climbing (`accept=cribs.uphill`, the default) and simulated annealing are one function with two rules. Run it a few times: a single climb does not always reach the top.
|
|
76
|
+
|
|
77
|
+
## Where the tables come from
|
|
78
|
+
|
|
79
|
+
`QUADGRAMS`, `FLOOR` and `WORDS` are counted from twelve public-domain novels from Project Gutenberg (Wells, Stevenson, Collins, Grahame, Stoker, Buchan, Austen, Dickens, Doyle and Nesbit; every author died before 1956). Only counts are kept: no book text is in the package. `tools/build_data.py` downloads the novels and rebuilds `cribs/data/quadgrams.txt.gz` and `cribs/data/words.txt.gz` byte for byte:
|
|
80
|
+
|
|
81
|
+
```
|
|
82
|
+
python tools/build_data.py /some/scratch/folder
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
The quadgram table is what `cribs.make_scores` gives on the novels: about 4.8 million quadgrams counted, the 56,451 different ones seen at least twice kept, and a floor of -7.68 for a quadgram never seen. `WORDS` is the 5,000 commonest words, commonest first.
|
|
86
|
+
|
|
87
|
+
## Tests
|
|
88
|
+
|
|
89
|
+
```
|
|
90
|
+
pytest # every worked example of the book's nine guides, and the short-function rule
|
|
91
|
+
pytest -m "not slow" # the same without hill_crib's 456,976 tries (a few seconds)
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
## Licence
|
|
95
|
+
|
|
96
|
+
MIT.
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
cribs/__init__.py,sha256=qMTCZNJou5cYIkfoO5dOCzRAPjREaYUXiI-PPrTkLRg,2373
|
|
2
|
+
cribs/basics.py,sha256=x_AHT6oqGegrVAHro2Q0CxznX7dvzblIWbMNirbDqOk,1505
|
|
3
|
+
cribs/clues.py,sha256=JmknL4TdR8NUkZ8pO-yWKHgwJOL66MEb0DyHrp3ltvM,1257
|
|
4
|
+
cribs/coincidence.py,sha256=xfMmsYkOD-76rODY6mP-RURpDdnX3cSXfx0a4fNcX6E,888
|
|
5
|
+
cribs/data.py,sha256=N-W1XpPYlG398ZxSaEVHVHL5hBTSdWlFpPogBJjuW8A,1076
|
|
6
|
+
cribs/frequency.py,sha256=GDqklGOgV337-36d9AO2SGiODPapsIR2vpHMxGEeTlQ,1173
|
|
7
|
+
cribs/keys.py,sha256=JplTL0soCe59cEwwSQ16osG1-fKHChw-dSUrDmG0oaY,679
|
|
8
|
+
cribs/pairs.py,sha256=4Zvj0xIaNf4C_8c5Smn6LUUnCffWhrkQeg1UNn3lth0,2371
|
|
9
|
+
cribs/patterns.py,sha256=igfa9MXH9QKTKZsOWabJOxMif0jZotOChHp29BBcOH8,1103
|
|
10
|
+
cribs/repeats.py,sha256=om-gyj5-7VhtAizw3F592mWxM96Th5P8XAB0PNF4bxw,1632
|
|
11
|
+
cribs/scoring.py,sha256=pzwqoWx_E6w1NXVzzSNjUkXrVcLXTOYnplYaR0CiYaM,1652
|
|
12
|
+
cribs/transposition.py,sha256=PtPOrfypd5cnVLrFuIZyOWx9puZFfuScNYacX-TPU4w,1475
|
|
13
|
+
cribs/data/quadgrams.txt.gz,sha256=3uM2SZaooi_ZYB1JM4xePGrHbaN2XxnkbmkDy7CGQzM,197030
|
|
14
|
+
cribs/data/words.txt.gz,sha256=0Zy2zaYwdgHwqwZ8fNeStznN5xcI5VUB481P1wSTgAI,75669
|
|
15
|
+
cribs-0.1.1.dist-info/METADATA,sha256=3YaGf4J9ZXWoU-Xk-E2SS12tdNe4MZUJSuqZoLkEaoM,5081
|
|
16
|
+
cribs-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
17
|
+
cribs-0.1.1.dist-info/licenses/LICENSE,sha256=ekE13yCE9fWWEJfP1NPnUJabZ_Wwrc6coKJV2ZZx27w,1068
|
|
18
|
+
cribs-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Thor Whalen
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|