Information TheoryComputer Science, Applied · Book 1
0 / 0

Shelves / Information Theory

IT·10

Information Everywhere: Language, DNA, Randomness and Passwords

Measuring information in the real world, where nobody hands you the probabilities: how any model gives an upper bound on a source's entropy rate; Shannon's guessing game, played by a context model on Shakespeare (2.13 bits per letter with five letters of context, against Shannon's estimate of about 1 bit for people); the same declaration in thirteen languages and scripts; a chloroplast genome at 1.93 bits per base, and the third of it that's a reversed copy; Shannon entropy against min-entropy, the measure that matters for keys and secrets; why Python's ordinary random numbers can be predicted from 624 of them; and 32.6 million leaked passwords, of which 11 % fall to the 1,000 most common guesses.

29 topics · ~36 min read · 12-question quiz
Updated Suggest a correction

Start here

What this chapter answers

How do you measure the information in a real source when you don't know its probabilities? How much information does English carry per letter, and how do you know? Is a text in Hindi more or less informative than the same text in English? Why is DNA so hard to compress? Which entropy matters for random numbers and secrets? And how strong are the passwords people actually choose?

Measuring a real source

Every model gives an upper bound

A real source's entropy rate is unknown: nobody can list the true probabilities of every English sentence. What we can do is build a model that assigns probabilities, and measure its average surprise on text it hasn't seen. Chapter 11 proves what the source coding theorem already suggests: a model's average surprise on real data, its cross-entropy, is never less than the true entropy rate (on average, over long data). So every model gives an upper bound, every better model a tighter one, and every compressor's output size is a measured upper bound too.

That turns "what's the entropy of English?" into a race between models: the context counts of chapter 7, compressors such as lzma, statistical language models, and today's neural language models, each lowering the bound.

Blending contexts

Chapter 7 found that long contexts overfit: most are rare, so their counts memorise the training text. The cure, used in compressors since PPM (John Cleary and Ian Witten, 1984) and in language models since the 1980s, is to blend orders: predict from the longest context that has been seen, but trust it only as much as the evidence allows, and fill in from shorter contexts. The lab's Blend model uses Witten–Bell weights: a context seen n times, followed by t different symbols, gets weight nn+t, and the rest goes to the next shorter context. A context seen often with few different followers is trusted; a context seen twice with two different followers isn't.

English, and the guessing game

Shannon's game

Shannon showed people the start of a text and asked them to guess the next letter, then the next, counting the guesses each letter took. A person who guesses right first time 80 % of the time is reading a very predictable text. From the distribution of guess counts he derived two bounds: an upper bound, the entropy of the guess counts (the text can be rewritten as guess counts, which carry the same information), and a lower bound that's valid only if the guesser is ideal. With up to 100 letters of context, his subjects' figures put English between about 0.6 and 1.3 bits per letter.

A model plays the game

The lab lets the blended model play: trained on 90 % of the plays (letters and spaces only, 27 symbols), it ranks all 27 symbols for each of 20,000 unseen positions, and the rank of the right one is its guess count. With no context it guesses right first time 19.8 % of the time and the model's surprise is 4.08 bits per symbol; with three letters of context, 46.6 % and 2.40 bits; with five, 56.4 % and 2.13 bits, the best here. With seven letters it gets slightly worse (2.35 bits), the overfitting of chapter 7 that blending reduces but doesn't remove.

Interactive diagram: Shannon's guessing game, played by a model. It needs JavaScript; the text around it says the same.

The guess-count upper bounds (2.46 bits with five letters) agree that the model isn't close to Shannon's 1 bit. People know words, grammar, plots and meaning; five letters of context and counts from one million characters know far less. The lower bounds (1.43 with five letters) don't apply here: they assume an ideal guesser, and this one isn't. Modern neural language models, trained on vast text, report cross-entropies below 1 bit per character on standard English benchmarks, consistent with Shannon's estimate.

What a letter's information means

About 1 bit per letter means English is roughly 80 % redundant compared with 4.7 bits for independent equally likely letters. That redundancy is why you can read text with letters missing, why spelling mistakes rarely stop understanding, and why crossword puzzles are possible (Shannon noted that with no redundancy any grid of letters would be a crossword, and with too much none would). Compressors exploit part of it: chapter 1's lzma reached about 2.6 bits per character on the plays, and chapter 7's best count model 2.29.

The same text in many languages

How much does the script matter? The lab takes the start of the Universal Declaration of Human Rights in 13 languages (about 10,000 bytes of each, all the corpus keeps) and measures characters, bytes and what lzma makes of them.

Bytes are a poor measure of information. Every sample is about 10,000 bytes of UTF-8, but that holds 9,888 characters of English, 5,419 of Russian (each Cyrillic letter takes 2 bytes), 3,600 of Tamil and 3,334 of Japanese (3 bytes for most characters). Per character, the scripts differ widely: lzma needs 2.80 bits per character for English, 3.95 for Russian, 4.53 for Hindi, 5.89 for Chinese, 8.17 for Japanese, because one Chinese or Japanese character often carries a syllable or a whole word, where English needs several letters. Per byte of UTF-8, the order reverses: Tamil compresses to 1.54 bits per byte and Hindi to 1.74, against English's 2.80, because UTF-8 spends three bytes on each of their characters, and much of that is redundant. Comparing languages fairly needs the same content; these samples cover different amounts of the declaration (10,000 bytes of English is much more of the text than 10,000 bytes of Tamil), so the figures describe scripts and encodings, not which language is "more informative". Studies that compare whole parallel texts find that languages carry broadly similar information per sentence, trading characters for information per character.

DNA

A genome is a text in four letters, A, C, G and T, so 2 bits per base is the obvious encoding, and the most a base could carry. The lab measures the complete chloroplast genome of the thale cress, Arabidopsis thaliana (154,478 bases).

The letters aren't equally likely (A and T 31 % and 32 %, C and G 18 % each), so the order-0 entropy is 1.945 bits. Context helps far less than in English: a blended model trained on 90 % of the genome needs 1.93 bits per base on the rest with two to four bases of context, and longer contexts overfit (2.41 bits with 8, 2.84 with 11; counted on the whole genome, 8 bases of context "achieve" 1.16, pure memorisation). General compressors do worse than 2-bit packing: deflate needs 2.28 bits per base and lzma 2.16, because they spend effort looking for repeats that mostly aren't there and code in bytes.

But DNA has its own structure. This genome contains a long inverted repeat: a stretch of about 26,000 bases that appears twice, the second copy reversed and with each base replaced by its pair (A with T, C with G), as the two strands of DNA pair. The lab finds that 34 % of positions start a 32-base run whose reversed complement appears elsewhere. A compressor that knows how DNA pairs could code one copy as "the reverse complement of that one" and save a sixth of the genome; specialised DNA compressors do exactly this, along with modelling genes and codons, and reach roughly 1.6 to 1.9 bits per base on typical genomes. Genomes look nearly random to general tools because their redundancy is the kind only biology explains.

Randomness

The entropy that matters for secrets

Average surprise isn't what matters to someone guessing a secret. If a key is chosen so that one value occurs half the time and the rest are spread over 1,023 others, its Shannon entropy is about 6 bits, which sounds respectable; but an attacker who tries the common value first succeeds half the time. The relevant measure is the min-entropy:

An attacker's best single guess succeeds with probability 2−H∞. The lab's examples: uniform over 1,024 values, 10 bits either way; one value at half, 6.0 bits of Shannon entropy but 1 bit of min-entropy; one value at 1 %, 9.98 bits against 6.64. Standards for random number generators (NIST's Special Publication 800-90, part B, on entropy sources) measure the min-entropy of noise sources for exactly this reason.

Where random numbers come from

Computers are deterministic, so randomness has to come from outside: timing of interrupts, thermal noise in circuits, dedicated hardware generators. The operating system collects such noise, estimates its min-entropy conservatively, and feeds it through a cryptographically secure pseudorandom generator, whose output can't be predicted even by someone who has seen earlier output. Programs get it through os.urandom (or getrandom, /dev/urandom, BCryptGenRandom); in Python, the secrets module. The lab's million bytes from os.urandom have 7.9998 bits of order-0 entropy per byte (the shortfall is the small-sample bias of chapter 4), and lzma makes them 108 bytes larger.

Ordinary pseudorandom generators are a different thing. Python's random module uses the Mersenne Twister (Makoto Matsumoto and Takuji Nishimura, 1998), excellent for simulations but not secret: its 624 words of state can be reconstructed from 624 consecutive 32-bit outputs. The lab does it: seeded unpredictably from the operating system, the generator's next 1,000 outputs were all predicted correctly after watching 624. Its outputs have high Shannon entropy and pass statistical tests; their min-entropy, for someone who has seen the earlier outputs, is zero.

Seeds matter as much as generators. A generator seeded with the time in seconds has as many possible states as the attacker's uncertainty about the time: 16.4 bits if they know the day, 24.9 if they know the year, a search a laptop finishes at once. Keys must come from a cryptographically secure generator seeded with enough min-entropy, typically at least 128 bits.

Passwords

What people choose

In December 2009, an attacker stole the passwords of 32.6 million accounts of RockYou, a social-games company that stored them as plain text. The list, published with how many accounts used each password, is the largest public record of what people choose, and the lab uses only its counts. There are 14.3 million different passwords, 11.9 million of them used by a single account. The most common one is used by 0.89 % of accounts: a min-entropy of only 6.81 bits. The plug-in Shannon entropy is 21.07 bits (an underestimate, since most passwords appear once: chapter 4's bias).

Guessing in order

An attacker who tries the most common passwords first breaks 2.05 % of accounts with 10 guesses, 11.30 % with 1,000, 22.30 % with 10,000, and more than half with a million. (These figures guess with the list itself, an attacker's ideal; real attackers use lists from other leaks, which are nearly as good, as studies of many leaks have shown.) A random password of 8 lowercase letters has 37.6 bits, and 10 million guesses would break it only 0.0048 % of the time. The gap between 37.6 bits possible and under 7 bits chosen is the gap between what a password could be and what people make it.

Interactive diagram: How fast chosen passwords fall. It needs JavaScript; the text around it says the same.

That's why password strength can't be judged by length and character classes: "Password1!" satisfies most composition rules and is near the top of every list. Current guidance (NIST's SP 800-63B, 2017) drops composition rules, requires checking new passwords against lists of breached ones, limits online guessing attempts, and encourages long passphrases and password managers. A passphrase of 4 words chosen at random from a list of 7,776 (the Diceware method) has 4log27776≈51.7 bits, all of it min-entropy, because the computer, not the person, chooses.

Lab: real sources

Python
"""real.py: measuring information in real sources, for chapter 10's lab."""
import math
from collections import Counter, defaultdict

def entropy(counts):
    """Plug-in entropy, in bits, of a collection of counts."""
    n = sum(counts)
    return -sum(c / n * math.log2(c / n) for c in counts if c)

def cond_entropy(seq, k):
    """Plug-in H(next symbol | previous k symbols), in bits, from one sequence."""
    ctx, full = Counter(), Counter()
    for i in range(k, len(seq)):
        ctx[seq[i - k:i]] += 1
        full[seq[i - k:i + 1]] += 1
    n = len(seq) - k
    return -sum(c / n * math.log2(c / ctx[g[:k]]) for g, c in full.items())

class Blend:
    """A context model of orders 0..K, blended with Witten-Bell weights: trust a context in proportion
    to how often it has been seen, against how many different symbols have followed it."""
    def __init__(self, alphabet, K):
        self.alphabet, self.K = list(alphabet), K
        self.next = [defaultdict(Counter) for _ in range(K + 1)]
    def train(self, text):
        for i in range(len(text)):
            for k in range(self.K + 1):
                if i >= k:
                    self.next[k][text[i - k:i]][text[i]] += 1
    def probs(self, history):
        p = {c: 1 / len(self.alphabet) for c in self.alphabet}          # below order 0: uniform
        for k in range(self.K + 1):
            if len(history) < k:
                break
            seen = self.next[k].get(history[len(history) - k:])
            if not seen:
                break
            n, t = sum(seen.values()), len(seen)
            p = {c: (seen[c] + t * p[c]) / (n + t) for c in self.alphabet}
        return p

def min_entropy(probs):
    """-log2 of the largest probability: how hard the single best guess is."""
    return -math.log2(max(probs))

Experiment 1: a model plays Shannon's guessing game

Python
import math, re
from pathlib import Path
from real import Blend, entropy

text = re.sub(r"[^a-z]+", " ", Path("data/shakespeare.txt").read_text().lower())
cut = int(len(text) * 0.9)
train, test = text[:cut], text[cut:cut + 20_000]
alphabet = sorted(set(text))
print(f"{len(alphabet)} symbols; training on {cut:,}, guessing {len(test):,} unseen symbols\n")
print(f"{'context':>8}{'model bits/symbol':>19}{'right first guess':>19}{'guess-count upper':>19}{'lower':>8}")
for K in (0, 1, 2, 3, 5, 7):
    m = Blend(alphabet, K); m.train(train)
    bits, ranks = 0.0, []
    for i in range(len(test)):
        p = m.probs(text[cut + i - K:cut + i])               # the test text follows the training text
        bits -= math.log2(p[test[i]])
        order = sorted(alphabet, key=lambda c: -p[c])
        ranks.append(order.index(test[i]) + 1)      # how many guesses the model needs, as in Shannon's game
    q = [ranks.count(r) / len(ranks) for r in range(1, len(alphabet) + 2)]
    upper = entropy([x for x in q if x])
    lower = sum(r * (q[r - 1] - q[r]) * math.log2(r) for r in range(1, len(alphabet) + 1))
    print(f"{K:>8}{bits / len(test):>19.3f}{100 * q[0]:>17.1f} %{upper:>19.3f}{lower:>8.3f}")
Text
27 symbols; training on 953,622, guessing 20,000 unseen symbols

 context  model bits/symbol  right first guess  guess-count upper   lower
       0              4.084             19.8 %              4.079   3.274
       1              3.379             26.3 %              3.507   2.596
       2              2.799             38.0 %              3.087   2.077
       3              2.400             46.6 %              2.741   1.717
       5              2.130             56.4 %              2.459   1.430
       7              2.349             57.5 %              2.438   1.408

The blended model's best figure, 2.13 bits per symbol with five letters of context, improves on chapter 7's 2.29 from counts of a single length, because blending lets rare long contexts borrow from shorter ones. Seven letters is worse again: blending softens overfitting without removing it. The guess-count upper bound follows the model's surprise; the "lower bound" column isn't one here, because the model isn't an ideal guesser.

Experiment 2: one declaration, thirteen languages

Python
import lzma
from collections import Counter
from pathlib import Path
from real import entropy

files = {"English": ("English-Latin1", "latin-1"), "French": ("French_Francais-Latin1", "latin-1"),
         "German": ("German_Deutsch-Latin1", "latin-1"), "Finnish": ("Finnish_Suomi-Latin1", "latin-1"),
         "Swahili": ("Swahili_Kiswahili-Latin1", "latin-1"), "Russian": ("Russian-UTF8", "utf-8"),
         "Greek": ("Greek_Ellinika-UTF8", "utf-8"), "Hebrew": ("Hebrew_Ivrit-UTF8", "utf-8"),
         "Hindi": ("Hindi-UTF8", "utf-8"), "Tamil": ("Tamil-UTF8", "utf-8"),
         "Chinese": ("Chinese_Mandarin-UTF8", "utf-8"), "Japanese": ("Japanese_Nihongo-UTF8", "utf-8"),
         "Korean": ("Korean_Hankuko-UTF8", "utf-8")}
print("The start of the Universal Declaration of Human Rights in 13 languages (the corpus keeps about 10,000 bytes of each)")
print(f"{'language':<10}{'characters':>11}{'UTF-8 bytes':>12}{'distinct chars':>15}{'order-0 bits/char':>19}{'lzma bytes':>11}{'lzma bits/char':>15}{'per byte':>9}")
for lang, (name, enc) in files.items():
    text = " ".join(Path("data/udhr", name).read_bytes().decode(enc, errors="ignore").split())   # a cut-off last character is dropped
    raw = text.encode("utf-8")
    xz = len(lzma.compress(raw, format=lzma.FORMAT_RAW, filters=[{"id": lzma.FILTER_LZMA2, "preset": 9 | lzma.PRESET_EXTREME}]))
    print(f"{lang:<10}{len(text):>11,}{len(raw):>12,}{len(set(text)):>15}{entropy(list(Counter(text).values())):>19.2f}{xz:>11,}{8 * xz / len(text):>15.2f}{8 * xz / len(raw):>9.2f}")
Text
The start of the Universal Declaration of Human Rights in 13 languages (the corpus keeps about 10,000 bytes of each)
language   characters UTF-8 bytes distinct chars  order-0 bits/char lzma bytes lzma bits/char per byte
English         9,888       9,888             57               4.27      3,465           2.80     2.80
French          9,899      10,203             60               4.26      3,698           2.99     2.90
German          9,922      10,063             71               4.45      3,724           3.00     2.96
Finnish         9,919      10,329             54               4.25      3,793           3.06     2.94
Swahili         9,909       9,909             62               4.20      3,378           2.73     2.73
Russian         5,419       9,956             66               4.59      2,678           3.95     2.15
Greek           5,470       9,998             68               4.72      2,808           4.11     2.25
Hebrew          5,572       9,957             38               4.31      2,867           4.12     2.30
Hindi           3,814       9,936             76               4.83      2,159           4.53     1.74
Tamil           3,600       9,980             52               4.50      1,922           4.27     1.54
Chinese         4,941       9,919            522               5.07      3,640           5.89     2.94
Japanese        3,334       9,656            455               7.06      3,406           8.17     2.82
Korean          4,125       9,888            308               6.09      3,373           6.54     2.73

Equal bytes hold very different numbers of characters, and characters carry very different amounts of information: 2.80 bits each in English, 8.17 in Japanese. Per byte of UTF-8, the Indian scripts compress most (Tamil 1.54 bits per byte), because their encoding is the most wasteful. These samples aren't the same content, so they compare scripts and encodings, not languages.

Experiment 3: a genome

Python
import lzma, math, zlib
from pathlib import Path
from real import Blend, cond_entropy

dna = Path("data/chloroplast.txt").read_text().strip()
print(f"chloroplast genome of the thale cress (Arabidopsis thaliana): {len(dna):,} bases; " +
      ", ".join(f"{b} {dna.count(b) / len(dna):.3f}" for b in "ACGT"))
print("\nH(base | previous k bases), counted on the whole genome:")
print("  " + "   ".join(f"k={k}: {cond_entropy(dna, k):.4f}" for k in range(0, 9, 2)))
cut = int(len(dna) * 0.9)
print("\nblended model trained on the first 90 %, bits per base on the last 10 %:")
row = []
for K in (0, 2, 4, 6, 8, 11):
    m = Blend("ACGT", K); m.train(dna[:cut])
    bits = -sum(math.log2(m.probs(dna[i - K:i])[dna[i]]) for i in range(cut, len(dna)))
    row.append(f"order {K}: {bits / (len(dna) - cut):.3f}")
print("  " + "   ".join(row))
raw = dna.encode()
print(f"\nbits per base: 2 bits per letter packing 2.000, deflate {8 * len(zlib.compress(raw, 9)) / len(dna):.3f}, "
      f"lzma {8 * len(lzma.compress(raw, preset=9 | lzma.PRESET_EXTREME)) / len(dna):.3f}")

comp = str.maketrans("ACGT", "TGCA")
k = 32
kmers = {dna[i:i + k] for i in range(len(dna) - k + 1)}
covered = sum(dna[i:i + k].translate(comp)[::-1] in kmers for i in range(len(dna) - k + 1))
print(f"positions whose next {k} bases appear elsewhere reversed and complemented: {covered:,} ({100 * covered / len(dna):.1f} %)")
Text
chloroplast genome of the thale cress (Arabidopsis thaliana): 154,478 bases; A 0.314, C 0.184, G 0.178, T 0.323

H(base | previous k bases), counted on the whole genome:
  k=0: 1.9449   k=2: 1.9216   k=4: 1.9088   k=6: 1.8434   k=8: 1.1643

blended model trained on the first 90 %, bits per base on the last 10 %:
  order 0: 1.960   order 2: 1.934   order 4: 1.930   order 6: 1.983   order 8: 2.409   order 11: 2.843

bits per base: 2 bits per letter packing 2.000, deflate 2.280, lzma 2.164
positions whose next 32 bases appear elsewhere reversed and complemented: 52,488 (34.0 %)

DNA is close to 2 bits per base for every general method: 1.93 at best from context, 2.16 from lzma. Long contexts overfit badly. Yet a third of the genome is a reversed, complemented copy of another part, structure that only a model knowing how DNA pairs can use.

Experiment 4: randomness

Python
import lzma, math, os, random
from collections import Counter
from real import entropy, min_entropy

# 1. Shannon entropy against min-entropy: how surprising on average, against how guessable the best guess is
print("distribution of 1,024 values                     Shannon   min-entropy (bits)")
for name, p in (("uniform", [1 / 1024] * 1024),
                ("one value half the time, rest uniform", [0.5] + [0.5 / 1023] * 1023),
                ("one value 1 % of the time, rest uniform", [0.01] + [0.99 / 1023] * 1023)):
    print(f"  {name:<46}{entropy([x * 10**9 for x in p]):>8.3f}{min_entropy(p):>13.3f}")

# 2. The operating system's random bytes look like noise to every test here
r = os.urandom(1_000_000)
print(f"\nos.urandom, 1,000,000 bytes: order-0 entropy {entropy(list(Counter(r).values())):.4f} bits per byte; "
      f"lzma makes it {len(lzma.compress(r, preset=9)):,} bytes")

# 3. Python's random module is predictable: 624 outputs reveal its whole state
def untemper(y):
    y ^= y >> 18
    y ^= (y << 15) & 0xEFC60000
    t = y
    for _ in range(5):
        t = y ^ ((t << 7) & 0x9D2C5680)
    y = t
    t = y
    for _ in range(3):
        t = y ^ (t >> 11)
    return t & 0xFFFFFFFF

victim = random.Random(os.urandom(16))              # seeded from the operating system: unknown to us
seen = [victim.getrandbits(32) for _ in range(624)]
clone = random.Random()
clone.setstate((3, tuple(untemper(v) for v in seen) + (624,), None))
predicted = [clone.getrandbits(32) for _ in range(1000)]
actual = [victim.getrandbits(32) for _ in range(1000)]
print(f"Mersenne Twister: after watching 624 outputs, predicted the next 1,000 with {sum(a == b for a, b in zip(predicted, actual))} correct")

# 4. A generator seeded with the time in seconds has only as much min-entropy as the attacker's uncertainty about the time
for span, label in ((60, "within a minute"), (86_400, "within a day"), (365 * 86_400, "within a year")):
    print(f"  seed = the time in seconds, known {label:<15}: {math.log2(span):5.1f} bits to guess")
Text
distribution of 1,024 values                     Shannon   min-entropy (bits)
  uniform                                         10.000       10.000
  one value half the time, rest uniform            5.999        1.000
  one value 1 % of the time, rest uniform          9.979        6.644

os.urandom, 1,000,000 bytes: order-0 entropy 7.9998 bits per byte; lzma makes it 1,000,108 bytes
Mersenne Twister: after watching 624 outputs, predicted the next 1,000 with 1000 correct
  seed = the time in seconds, known within a minute:   5.9 bits to guess
  seed = the time in seconds, known within a day   :  16.4 bits to guess
  seed = the time in seconds, known within a year  :  24.9 bits to guess

Shannon entropy can be high while min-entropy is low (6.0 against 1 bit). The operating system's bytes are incompressible. Python's ordinary generator was predicted perfectly from 624 outputs, and time-based seeds leave between 6 and 25 bits to guess.

Experiment 5: 32.6 million passwords

Python
import math
from itertools import accumulate

# The 2009 RockYou leak, as published with counts: "count password" per line. Only the counts are used here.
counts = []
with open("data/rockyou-withcount.txt", "rb") as f:
    for line in f:
        field = line.split(None, 1)[:1]
        if field and field[0].isdigit():
            counts.append(int(field[0]))
counts.sort(reverse=True)
N = sum(counts)
print(f"{N:,} accounts, {len(counts):,} different passwords; {sum(c == 1 for c in counts):,} used by one account only\n")

p = [c / N for c in counts]
H = -sum(x * math.log2(x) for x in p)
print(f"Shannon entropy of the choice (plug-in, an underestimate): {H:.2f} bits")
print(f"min-entropy (the most common password's share, {p[0]:.4f}): {-math.log2(p[0]):.2f} bits")
running = list(accumulate(p))
print("\nan attacker who tries the most common passwords first, in order, against one account:")
for g in (1, 10, 100, 1_000, 10_000, 100_000, 1_000_000, 10_000_000):
    print(f"  {g:>10,} {'guess  ' if g == 1 else 'guesses'}: succeeds {100 * running[g - 1]:6.2f} % of the time")
print(f"\nfor comparison: a random 8-letter lowercase password has {8 * math.log2(26):.1f} bits; "
      f"10,000,000 guesses succeed {100 * 10_000_000 / 26**8:.4f} % of the time")
Text
32,603,388 accounts, 14,344,391 different passwords; 11,884,632 used by one account only

Shannon entropy of the choice (plug-in, an underestimate): 21.07 bits
min-entropy (the most common password's share, 0.0089): 6.81 bits

an attacker who tries the most common passwords first, in order, against one account:
           1 guess  : succeeds   0.89 % of the time
          10 guesses: succeeds   2.05 % of the time
         100 guesses: succeeds   4.55 % of the time
       1,000 guesses: succeeds  11.30 % of the time
      10,000 guesses: succeeds  22.30 % of the time
     100,000 guesses: succeeds  36.67 % of the time
   1,000,000 guesses: succeeds  54.18 % of the time
  10,000,000 guesses: succeeds  86.68 % of the time

for comparison: a random 8-letter lowercase password has 37.6 bits; 10,000,000 guesses succeed 0.0048 % of the time

The most common choice covers 0.89 % of accounts, so the min-entropy is 6.81 bits; 1,000 guesses break 11.3 % of accounts and a million break 54 %. A random 8-letter password would resist 10 million guesses 99.995 % of the time.

Worked examples

A PIN people choose

Information in a genome

A passphrase

Exercises

Practice

  1. A model's average surprise on unseen English text is 1.9 bits per character. What can you conclude about the entropy rate of English?
  2. Find the min-entropy of a die that shows 6 with probability 12 and each other face with probability 110. Compare with its Shannon entropy.
  3. Why does a text in Tamil take more UTF-8 bytes per character than one in English?
  4. What's the most information a base of DNA can carry, and why do genomes come close to it?
  5. Why is Python's random module unsuitable for generating passwords?
  6. A website requires passwords of at least 8 characters with a digit and a capital letter. Why doesn't that guarantee 8 characters' worth of entropy?
  7. What does a cryptographically secure pseudorandom generator promise that the Mersenne Twister doesn't?
Answers
  1. Its entropy rate is at most about 1.9 bits per character (every model gives an upper bound); it may be much lower.
  2. H∞ =−log212 =1 bit. Shannon: 12×1+5×110log210≈0.5+1.661 =2.161 bits.
  3. UTF-8 spends one byte on ASCII characters and three on most Indian scripts' characters.
  4. 2 bits (four letters). Genomes are close because most of their structure isn't visible to general statistics; their letters are nearly balanced and weakly dependent.
  5. Its outputs can be predicted from earlier outputs (624 of them reveal its state), and it's often seeded predictably.
  6. People choose predictable patterns that satisfy the rules ("Password1"); the min-entropy of chosen passwords is far below that of random ones.
  7. That its outputs can't be predicted, even by someone who has seen earlier outputs, without breaking a cryptographic assumption.

Harder

  1. Explain why the cross-entropy of any model on a long text from a source is at least the source's entropy rate, using the source coding theorem.
  2. A random number generator outputs 128-bit keys, but a bug means it was seeded with a 16-bit process number. What's the min-entropy of the keys, and how long would it take to try them all at 106 per second?
  3. A password list's plug-in Shannon entropy is 21 bits. Explain why the true entropy of the distribution of human-chosen passwords could be higher, and why that doesn't make passwords safer.
  4. In the lab, counting 8-base contexts on the whole genome gave 1.16 bits per base, but the held-out figure was 2.41. Explain both numbers.
  5. Shannon's upper bound from guess counts holds for any guesser, but his lower bound needs an ideal one. Explain why the upper bound is safe.
Answers
  1. A model gives a code (arithmetic coding with its probabilities, chapter 6) whose length is its surprise on the text. The source coding theorem says no code can compress long sequences from the source below the entropy rate on average, so the model's surprise, its cross-entropy, can't be below it either.
  2. The key is a function of the 16-bit seed, so there are at most 216=65,536 keys: min-entropy at most 16 bits, whatever the key length. Trying them all takes 0.07 seconds. The Debian OpenSSL bug (2006 to 2008) was of this kind: about 32,767 possible keys per type and size.
  3. The plug-in estimate is biased low when most values appear once: 11.9 million passwords were seen only once, and many more possible passwords were never seen. But the attacker's success depends on the top of the distribution, the common passwords, which min-entropy and guess curves measure; a long tail of unique passwords raises Shannon entropy without protecting the many accounts that use the common ones.
  4. With 4⁸ = 65,536 possible contexts and only 154,478 bases, most contexts are seen once or twice, so their counts predict the training sequence almost perfectly (the plug-in bias of chapter 4). On held-out data those counts are mostly wrong, and a blended model falls back on poorly estimated long contexts, doing worse than order 0. The honest figure is 2.41; the best honest figure comes from short contexts (1.93).
  5. Replacing each letter by the guesser's guess count is reversible for anyone who has the same guesser: run the guesser, and at each position take the guess with that count. So the guess-count sequence carries all the information of the text, and its entropy (per symbol) can't be below the text's. That holds for any deterministic guesser, good or bad; a poor guesser just gives a looser bound.

Challenge

  1. An online service allows 10 password attempts per account per day. Using the lab's guess curve, estimate the fraction of accounts an attacker would break in a year by trying the most common passwords in order, and propose a defence that changes the answer.
Discussion

In a year, 365×10=3,650 guesses per account: between the lab's 1,000 (11.30 %) and 10,000 (22.30 %), so roughly 15 to 18 % of accounts with RockYou-like passwords. Defences: block the most common passwords at registration (removing the top 100,000 removes the 36.67 % that the first 100,000 guesses would get, forcing users further down the curve); detect guessing spread across many accounts (attackers try a few common passwords against every account, which per-account limits don't stop); require a second factor; and use stricter limits with growing delays. Checking new passwords against breached lists, as NIST recommends, attacks the problem where the curve is steepest.

In real life

Misconceptions and limits

The model to keep

Common misconceptions

Misconception What's actually true Where it's shown
"A model's surprise on text measures the entropy of the language." It's an upper bound; better models lower it. Measuring a real source
"More context always predicts better." Seven letters did worse than five for the blended model. Experiment 1
"Equal file sizes mean equal information." 10,000 bytes held 9,888 English characters or 3,334 Japanese. Experiment 2
"DNA is just a text, so text compressors work on it." lzma used 2.16 bits per base, worse than 2-bit packing. Experiment 3
"High entropy means hard to guess." 6 bits of Shannon entropy can have 1 bit of min-entropy. Experiment 4
"Random-looking numbers are secure." The Mersenne Twister's next 1,000 outputs were predicted from 624. Experiment 4
"A long key is a strong key." A 128-bit key from a 16-bit seed has 16 bits of min-entropy. Harder exercise 9
"Composition rules make passwords strong." Human choices have under 7 bits of min-entropy; 11 % fall to 1,000 guesses. Experiment 5

Limits and trade-offs

  • Entropy estimates are biased. Plug-in estimates are biased low (chapter 4), model-based ones high; every reported "entropy of X" depends on the data size and the model, and should say which.
  • Samples aren't sources. A genome, a password leak or a corpus is one sample from its population: the chloroplast genome isn't typical of all DNA, and RockYou's users aren't all users.
  • Min-entropy is a worst case for one guess. Attackers make many guesses, so guess curves (how many accounts fall to k guesses) describe password strength better than any single number.

Revision sheet

Key ideas

  • Cross-entropy of a model on unseen data ≥ the source's entropy rate: every model is an upper bound.
  • Blending (PPM, Witten–Bell): trust a context by nn+t, fall back to shorter ones.
  • Shannon's guessing game: guess counts bound the entropy; English ≈ 0.6 to 1.3 bits per letter for people.
  • Scripts: information per character varies; UTF-8 bytes measure encoding, not information.
  • DNA: ≤ 2 bits per base; near 2 for general methods; reverse-complement repeats are biological structure.
  • Min-entropy H∞=−log2maxp: what a single guess faces; ≤H.
  • CSPRNG vs PRNG: unpredictable from earlier output vs merely statistically random.
  • Passwords: min-entropy about 6.8 bits in RockYou; guess curves; breached-list checks, rate limits, managers, passphrases.

Glossary

  • Cross-entropy (of a model): a model's average surprise, in bits per symbol, on data from a source; never less than the source's entropy rate.
  • Upper bound (on entropy): a value the true entropy can't exceed; every model and compressor gives one.
  • Shannon's guessing game: estimating a text's entropy from how many guesses a person needs for each next letter.
  • Prediction by partial matching (PPM): a compression method that predicts from the longest matching context and escapes to shorter ones.
  • Witten–Bell smoothing: weighting a context by how often it was seen against how many different symbols followed it.
  • UTF-8: the variable-length encoding of Unicode characters into one to four bytes.
  • Inverted repeat: a stretch of DNA that appears again elsewhere reversed and with each base replaced by its pair.
  • Min-entropy: the surprise of the most likely value, −log2maxxp(x); the measure of how guessable a secret is.
  • Cryptographically secure pseudorandom generator (CSPRNG): a generator whose output can't feasibly be predicted from earlier output.
  • Mersenne Twister: a widely used pseudorandom generator with excellent statistics and a state that can be recovered from 624 outputs.
  • Seed: the starting value of a pseudorandom generator, which determines all its output.
  • Guess curve: the fraction of accounts an attacker breaks as a function of the number of guesses, trying the most likely passwords first.
  • Passphrase: a password made of several words, strong when the words are chosen at random.