Algorithmadvanced
Mutual information analysis
Also called MIA.
Ranks key guesses by the estimated mutual information between leakage and predicted values, which works without a linear leakage model.
- Time
- Θ(g T (m + V B)) worst · average · best
- Space
- Θ(m T + V B + g) extra
- Where
- B = the number of bins; T = the number of samples in each trace; V = the number of model values; g = the number of key guesses; m = the number of traces
- Model
- Real RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Benedikt Gierlichs, Lejla Batina, Pim Tuyls, Bart Preneel, 2008
Mutual information analysis (MIA) finds a key from power traces with the mutual information between the measured power and a predicted value, in place of the correlation of CPA. For each key guess it groups the traces by a model value, such as the Hamming weight of an S-box output, and estimates how much knowing that value reduces the uncertainty of the power. Because mutual information sees any dependence, not only a linear one, the attack works when the power is a non-linear function of the model. Gierlichs, Batina, Tuyls and Preneel (2008) proposed it as a generic distinguisher.
In plain words
Sort the recorded runs into boxes by a value that a key guess predicts, for example the number of ones in a value inside the chip. Then look at the power in each box. If the guess is right, each box holds runs with similar power, so knowing the box tells you a lot about the power. If the guess is wrong, every box holds a mix, and the box tells you little. Mutual information measures, in bits, how much one thing tells you about another. It does not care whether the power goes up or down with the value, or in which pattern. It only asks whether the boxes differ. The guess whose boxes differ the most wins.
The problem
The attacker sees pairs , with a known input nibble and a trace of real samples. The device holds a fixed key nibble . The leakage model is
where is the 4-bit S-box of PRESENT, is a function that the attacker does not know, the noise values are independent with law , and the inputs are independent and uniform. The attacker knows that the power depends on the Hamming weight, but not how. The goal is to output . The cost model is the real RAM.
The algorithm
The estimate of the mutual information uses a histogram: each sample is cut into bins of equal width from its smallest to its largest value. The entropies are the plug-in Shannon entropies of the counts, in bits.
MIA(traces (p_1, l_1) .. (p_m, l_m), S-box S, model M, bins B)- 1
best ← none, top ← -∞ - 2
for each sample j: bin_i[j] ← the bin of l_i[j] among B equal bins of column j - 3
for each key guess g = 0 .. |S| - 1 do - 4
for i = 1 .. m do h_i ← M(S(p_i ⊕ g)) ▷ the model value, HW here - 5
for each sample j = 1 .. T do - 6
count the pairs (h_i, bin_i[j]) in a table - 7
I_j ← H(bin) + H(h) - H(h, bin) ▷ plug-in entropies of the counts - 8
score(g) ← max over j of I_j - 9
if score(g) > top then - 10
best ← g, top ← score(g) - 11
return best and the list of scores
Line L7 is the identity , applied to the empirical joint distribution of the table of line L6. The first term is the same for every guess at a given sample, so the ranking at one sample depends only on the conditional entropy : the right guess is the one whose groups have the most concentrated power.
Example
Hamming weight leakage. Take , , no noise, one sample in each trace, each of the 16 inputs once, and bins. The trace values then fall in 5 different bins, and the scores are exact mutual informations:
| guess | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | A | B | C | D | E | F |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| score (bits) | 0.906 | 1.281 | 0.686 | 0.686 | 1.250 | 1.281 | 0.906 | 0.686 | 0.561 | 0.936 | 0.906 | 2.031 | 0.561 | 0.811 | 0.906 | 1.186 |
The right guess scores bits, the entropy of the weights with counts : the groups are pure. The closest rivals are the guesses 1 and 5, at bits.
Non-linear leakage. Now let , so the power is 0 for weight 2, 1 for weights 1 and 3, and 4 for weights 0 and 4. The covariance of and is the third central moment of a symmetric binomial law, which is 0, so the right guess of CPA has correlation 0. With bins, MIA gives the right guess bits and the best wrong guess, , bit. A measurement in the model, with , 8 bins, 200 seeded runs for each cell and a random key in each run:
| traces m | 25 | 50 | 100 | 200 | 400 |
|---|---|---|---|---|---|
| MIA, f(w) = w | 0.385 | 0.72 | 0.985 | 1.0 | 1.0 |
| CPA, f(w) = w | 0.915 | 0.995 | 1.0 | 1.0 | 1.0 |
| MIA, f(w) = (w - 2)² | 0.42 | 0.645 | 0.86 | 0.97 | 0.99 |
| CPA, f(w) = (w - 2)² | 0.15 | 0.105 | 0.035 | 0.005 | 0.0 |
When the linear model is right, CPA needs fewer traces. When it is wrong, CPA converges to a wrong key, because some wrong guesses keep a correlation of up to with , while MIA still converges to the right one.
Correctness
The loop of line L3 keeps the loop invariant that top is the largest score so far and best is the first guess with it, so line L11 returns the first argmax. Line L7 is the plug-in mutual information of the table, by the identity above. The key fact is a theorem about the population, from the data processing inequality: given the right model value , the binned power depends only on the noise, so a wrong model value cannot carry more information about it. For every binning and every ,
With fixed bin edges and a strict inequality, the plug-in estimates converge, and the right key wins with a probability that tends to 1. The proof gives these steps, and also the proof that an injective model makes all guesses equal.
Proof: MIA computes the plug-in mutual information, the right key maximizes the population value, and an injective model failsfull
All logarithms are to base 2. For a finite table of counts with total , write and , for its row and column sums.
Lemma 1 (the loop of line L3). Line L11 returns the first guess with the largest score.
Proof. Every score is a finite number at least 0 (Lemma 2), so the first guess passes line L9. After that, line L9 replaces best only when a score is strictly larger. By induction on the guesses, top is the largest score so far and best is the first guess that reaches it.
Lemma 2 (line L7). Line L7 computes the plug-in mutual information
where the sum is over the cells with , and .
Proof. Expand the logarithm of the quotient: . Summing times the first term gives . Summing over first, , so the second term gives , and in the same way the third gives . So , which is line L7. It is the Kullback-Leibler divergence of from the product , and so it is at least 0 by Gibbs' inequality.
The model. The inputs are uniform on , and with for each guess , any function , and noise independent of . Let be any function from the reals to a finite set of bins, and put .
Lemma 3 (the right key has the largest population value). For every guess , .
Proof. Given , the value is a function of alone, and is independent of , so is independent of given . That is, . Apply the chain rule of mutual information to the pair in two orders:
So .
This is the data processing inequality for the chain . It holds for every , every noise law and every binning, which is the sense in which MIA is generic. It does not say that the inequality is strict.
Theorem (consistency with fixed bins). Suppose that the bin edges are fixed in advance, that the other samples are independent of , and that for every . Then the probability that MIA returns tends to 1 as .
Proof. For each guess and each sample, the table of line L6 has finitely many cells. By the strong law of large numbers, each cell frequency converges with probability 1 to its probability. The plug-in mutual information is a continuous function of the cell frequencies, because is continuous on . So each estimate converges with probability 1 to the population value. At a sample the bin is independent of , so the limit is 0 for every guess. At the limit of guess is . So , and for , , which is strictly smaller by assumption. With 16 guesses, with probability 1 the right key has the strictly largest score for all large , and Lemma 1 then returns it.
The code takes the bin edges from the smallest and the largest value of each column. Those edges depend on the data, so the theorem applies to the code only in the form above; the tests check the code against exact values on noiseless traces and by measured success rates on noisy ones.
Proposition (an injective model fails). If the model value of line L4 is for an injective , then all 16 scores are equal, for every set of traces.
Proof. The map is injective, because XOR with , the S-box and are all injective. So for every guess the model value is a relabelling of the input , and the table of line L6 for guess is the table of the pairs with its rows renamed. Entropies do not depend on the names of the rows, so line L7 gives the same value for every guess at every sample, and line L8 the same score.
The examples. On the 16 noiseless balanced traces with and 5 bins, each value has its own bin, so the score of is the exact for a uniform input. For this is over the counts , which is bits. For and 4 bins, the values fall into 3 different bins, so the score of is the entropy of the counts , which is bits. The test file computes all other values of both tables by the sum of Lemma 2 and checks the code against them for every key.
Complexity
Line L2 finds the range of each column and the bin of each value in time. For each of the guesses and each of the samples, line L6 fills a table of counts from pairs, and line L7 reads the table, which costs . So the time is in every case. The extra space is for the bin indices, for one table and for the scores. With the Hamming weight model of a 4-bit value, .
Properties
- Generic. The score sees any dependence between the model and the power, linear or not, in either direction. It needs no assumption on beyond the fact that it is not constant on the model values.
- Needs a non-injective model. If the model is a bijection of the S-box output, every guess gives the same partition of the inputs up to a relabelling, and all scores are equal (a theorem, proved on the proof page). The Hamming weight works because it merges values.
- Estimator bias. The plug-in estimate of mutual information is biased upward when there are few traces in each cell of the table. A common heuristic is the Miller and Madow correction of about bits. The bias is of the same order for every guess, but it adds variance to the ranking.
- Slower than CPA when CPA is right. In the measurement above, MIA needs two to four times as many traces as CPA for a success rate of 0.95 under linear leakage.
- First order. Against Boolean masking, the distribution of the power at one sample is the same for every key, so the mutual information with any first-order model is 0.
Variants and improvements
- Kernel density estimates. Replace the histogram by a kernel density estimate of the power in each group. This gives a smoother estimate with a bandwidth in place of a bin count.
- Rank by conditional entropy. At one sample is the same for every guess, so it is enough to rank the guesses by , which saves one entropy per guess.
- A choice of the bin count. The bin count trades bias for resolution. Rules such as one bin for each few traces of each group, or a count that grows like , are heuristics.
- Other generic distinguishers. Any distance between the conditional distributions of the power in the groups can replace the mutual information, for example a distance between cumulative distribution functions.
- Profiled use. With a copy of the device, the conditional distributions can be learned in advance. This is the template attack.
When to use it
Use MIA when the shape of the leakage is unknown or not monotone in the model, for example when the power of a bus depends on transitions in a way that the Hamming weight does not fit. When a linear model is known to fit, use CPA, which needs fewer traces. When a profiling device is available, a template attack does better than both.
Pitfalls
- An injective model. If line L4 is , the 16 model values are a relabelling of the 16 inputs for every guess, so every guess has the same table up to the order of the rows, and every score is the same, bits in the example. Line L4 must merge values, as the Hamming weight does.
- Too many bins. If line L2 uses so many bins that each trace has its own bin, then and line L7 gives , the entropy of the model values of the guess, which depends only on the inputs and not on the power. Use a bin count that is much smaller than the number of traces in each group, such as the 8 bins of the measurement.
- A constant column. If all traces have the same value at a sample, line L2 has no range to cut. The code puts all values in bin 0, and the score at that sample is then 0 for every guess.
- Comparing against CPA at its best. A table of MIA against CPA under linear leakage only shows that CPA wins there. The reason to use MIA is a leakage that CPA does not fit; test it on one.
Implementations
The code of this page is an abstract model on synthetic data. Its traces come from the leakage model of "The problem", drawn with a seeded random.Random by the function simulate_traces; the code never reads a device, a file or a clock. The tests check the example tables, the equal scores of an injective model, the result with too many bins, the agreement with a direct sum of on 500 random inputs, and the success rate under linear and quadratic leakage.
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mutual-information-analysis/. The authors are listed in prov/DNRK95.jsonl.
"""Mutual information analysis with a histogram estimator, on synthetic traces.
The traces come from a stated statistical model, never from a device:
sample ``leak_sample`` of a trace is ``leak(HW(S(p xor k))) + noise`` and
every other sample is noise only. S is the 4-bit S-box of PRESENT
(Bogdanov et al., CHES 2007). The noise is Gaussian with a seeded
``random.Random``. This is a study model for defenders and students.
"""
import math
import random
from collections.abc import Callable
PRESENT_SBOX: tuple[int, ...] = (
0xC, 0x5, 0x6, 0xB, 0x9, 0x0, 0xA, 0xD,
0x3, 0xE, 0xF, 0x8, 0x4, 0x7, 0x1, 0x2,
)
Trace = tuple[int, list[float]]
def hamming_weight(v: int) -> int:
"""Return the number of 1 bits of a non-negative integer."""
return bin(v).count("1")
def simulate_traces(
rng: random.Random,
key: int,
m: int,
sigma: float,
samples: int = 4,
leak_sample: int = 2,
leak: Callable[[int], float] = float,
sbox: tuple[int, ...] = PRESENT_SBOX,
) -> list[Trace]:
"""Draw m synthetic traces (input, samples).
Each input p is uniform on the S-box domain. Sample ``leak_sample`` is
leak(HW(sbox[p ^ key])) + N(0, sigma^2); the other samples are
N(0, sigma^2). The default leak is the Hamming weight itself.
Cost: O(m * samples).
"""
n = len(sbox)
out: list[Trace] = []
for _ in range(m):
p = rng.randrange(n)
row = [rng.gauss(0.0, sigma) if sigma > 0 else 0.0 for _ in range(samples)]
row[leak_sample] += leak(hamming_weight(sbox[p ^ key]))
out.append((p, row))
return out
def equal_width_bins(column: list[float], bins: int) -> list[int]:
"""Map each value to one of ``bins`` equal bins from min to max.
The maximum goes to the last bin. A constant column goes to bin 0.
Cost: O(len(column)).
"""
lo = min(column)
hi = max(column)
if hi == lo:
return [0] * len(column)
width = (hi - lo) / bins
return [min(int((v - lo) / width), bins - 1) for v in column]
def plug_in_entropy(counts: list[int], total: int) -> float:
"""Shannon entropy in bits of the empirical distribution of the counts."""
h = 0.0
for c in counts:
if c:
q = c / total
h -= q * math.log2(q)
return h
def mutual_information_analysis(
traces: list[Trace],
bins: int = 8,
sbox: tuple[int, ...] = PRESENT_SBOX,
model: Callable[[int], int] = hamming_weight,
) -> tuple[int, list[float]]:
"""Return (best guess, score of each guess) by the MIA of Gierlichs et al.
Each sample is cut into ``bins`` equal-width bins. For a key guess g
the model value of trace i is model(sbox[p_i ^ g]). The score of g is
the largest plug-in estimate, over the samples, of the mutual
information in bits between the bin of the sample and the model value.
The first guess with the top score wins.
Precondition: at least one trace, every trace has the same number of
samples T >= 1, bins >= 1, and every input is in range(len(sbox)).
Cost: Theta(m * T) to bin and Theta(g * T * (m + V * B)) for the
guesses, with V model values and B bins; Theta(m * T + V * B) extra
space.
"""
if not traces:
raise ValueError("need at least one trace")
m = len(traces)
t_len = len(traces[0][1])
best, top = -1, -math.inf # @line L1
binned = [equal_width_bins([row[j] for _, row in traces], bins) for j in range(t_len)] # @line L2
scores: list[float] = []
for g in range(len(sbox)): # @line L3
h = [model(sbox[p ^ g]) for p, _ in traces] # @line L4
values = sorted(set(h))
index = {v: a for a, v in enumerate(values)}
mis = []
for j in range(t_len): # @line L5
joint = [[0] * bins for _ in values]
for i in range(m):
joint[index[h[i]]][binned[j][i]] += 1 # @line L6
row_counts = [sum(r) for r in joint]
col_counts = [sum(joint[a][b] for a in range(len(values))) for b in range(bins)]
flat = [c for r in joint for c in r]
mis.append(
plug_in_entropy(col_counts, m)
+ plug_in_entropy(row_counts, m)
- plug_in_entropy(flat, m)
) # @line L7
score = max(mis) # @line L8
scores.append(score)
if score > top: # @line L9
best, top = g, score # @line L10
return best, scores # @line L11
test_mutual_information_analysis.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/mutual-information-analysis/. The authors are listed in prov/DNRK95.jsonl.
import math
import random
import statistics
from collections import Counter
import pytest
from mutual_information_analysis import (
PRESENT_SBOX,
hamming_weight,
mutual_information_analysis,
simulate_traces,
)
def quad(w: int) -> float:
return float((w - 2) ** 2)
def oracle_mi(xs, ys):
"""I(X; Y) in bits as the sum of p(x, y) log p(x, y) / (p(x) p(y))."""
n = len(xs)
px = Counter(xs)
py = Counter(ys)
total = 0.0
for (x, y), c in Counter(zip(xs, ys)).items():
total += c / n * math.log2(c * n / (px[x] * py[y]))
return total
def oracle_bins(column, bins):
lo, hi = min(column), max(column)
if hi == lo:
return [0] * len(column)
out = []
for v in column:
b = 0
while b < bins - 1 and v >= lo + (b + 1) * (hi - lo) / bins:
b += 1
out.append(b)
return out
def oracle_scores(traces, bins, model):
t_len = len(traces[0][1])
cols = [oracle_bins([row[j] for _, row in traces], bins) for j in range(t_len)]
return [
max(oracle_mi([model(PRESENT_SBOX[p ^ g]) for p, _ in traces], cols[j]) for j in range(t_len))
for g in range(16)
]
def balanced_traces(key, leak=float):
return [(p, [leak(hamming_weight(PRESENT_SBOX[p ^ key]))]) for p in range(16)]
def test_worked_example() -> None:
best, scores = mutual_information_analysis(balanced_traces(0xB), bins=5)
assert best == 0xB
assert scores[0xB] == pytest.approx(2.0306390622, abs=1e-9)
assert sorted(scores, reverse=True)[1] == pytest.approx(1.2806390622, abs=1e-9)
for g in range(16):
a = [hamming_weight(PRESENT_SBOX[p ^ 0xB]) for p in range(16)]
b = [hamming_weight(PRESENT_SBOX[p ^ g]) for p in range(16)]
assert scores[g] == pytest.approx(oracle_mi(a, b), abs=1e-9)
def test_noiseless_recovers_every_key() -> None:
for key in range(16):
assert mutual_information_analysis(balanced_traces(key), bins=5)[0] == key
def test_injective_model_pitfall() -> None:
# With the S-box output itself as the model, every guess scores H(HW).
_, scores = mutual_information_analysis(balanced_traces(3), bins=5, model=lambda v: v)
assert all(s == pytest.approx(2.0306390622, abs=1e-9) for s in scores)
def test_too_many_bins_pitfall() -> None:
# With one trace in each bin, the score of g is only H of its model values.
rng = random.Random(5)
traces = [(rng.randrange(16), [float(i)]) for i in range(30)]
_, scores = mutual_information_analysis(traces, bins=60)
assert len(set(oracle_bins([row[0] for _, row in traces], 60))) == 30
for g in range(16):
h = [hamming_weight(PRESENT_SBOX[p ^ g]) for p, _ in traces]
n = len(h)
ent = -sum(c / n * math.log2(c / n) for c in Counter(h).values())
assert scores[g] == pytest.approx(ent, abs=1e-9)
def test_nonlinear_leakage() -> None:
# Leakage (HW - 2)^2 has zero correlation with HW at the right key.
want = [1.4056, 0.4528, 0.5613, 0.2806, 0.5613, 0.4528, 0.3113, 0.2806,
0.2335, 0.3113, 0.6556, 0.5841, 0.2335, 0.5841, 0.6556, 1.0]
for key in range(16):
best, scores = mutual_information_analysis(balanced_traces(key, quad), bins=4)
assert best == key
for g in range(16):
assert scores[g] == pytest.approx(want[g ^ key], abs=1e-4)
a = [hamming_weight(PRESENT_SBOX[x]) for x in range(16)]
b = [quad(w) for w in a]
assert statistics.covariance(a, b) == pytest.approx(0.0, abs=1e-12)
def test_edges() -> None:
with pytest.raises(ValueError):
mutual_information_analysis([])
best, scores = mutual_information_analysis([(2, [1.0, 1.0])])
assert best == 0 and scores == [0.0] * 16
def test_against_oracle_random() -> None:
rng = random.Random(20240503)
for _ in range(500):
m = rng.randrange(1, 14)
t_len = rng.randrange(1, 3)
bins = rng.randrange(1, 6)
identity = rng.random() < 0.3
model = (lambda v: v) if identity else hamming_weight
traces = [(rng.randrange(16), [rng.uniform(-3, 3) for _ in range(t_len)]) for _ in range(m)]
best, scores = mutual_information_analysis(traces, bins=bins, model=model)
want = oracle_scores(traces, bins, model)
assert scores == pytest.approx(want, abs=1e-9)
assert want[best] == pytest.approx(max(want), abs=1e-9)
def test_success_rate_with_noise() -> None:
rng = random.Random(13)
runs = 20
hits_hw = hits_quad = 0
for _ in range(runs):
key = rng.randrange(16)
t = simulate_traces(rng, key, m=200, sigma=1.0)
hits_hw += mutual_information_analysis(t)[0] == key
t = simulate_traces(rng, key, m=400, sigma=1.0, leak=quad)
hits_quad += mutual_information_analysis(t)[0] == key
assert hits_hw >= runs - 2
assert hits_quad >= runs - 2
History
Gierlichs, Batina, Tuyls and Preneel presented mutual information analysis at CHES 2008 as a distinguisher that needs fewer assumptions than the difference of means of DPA and the correlation of CPA. The idea of measuring side-channel leakage in bits, by information theory, also underlies the framework of Standaert, Malkin and Yung (2009), which compares attacks by their success rate and their guessing entropy.
References
- Benedikt Gierlichs, Lejla Batina, Pim Tuyls and Bart Preneel, Mutual information analysis, CHES 2008, LNCS 5154, pages 426 to 442, the definition of the distinguisher, the histogram estimate of the conditional entropy, and the comparison with the correlation attack
- Stefan Mangard, Elisabeth Oswald and Thomas Popp, Power Analysis Attacks, Springer, 2007, ISBN 978-0-387-30857-9, Chapter 3 (the Hamming weight model) and Chapter 6, pages 119 to 165 (the correlation attack that MIA is compared with)
- Andrey Bogdanov and others, PRESENT, an ultra-lightweight block cipher, CHES 2007, LNCS 4727, the description of the substitution layer (the table of the 4-bit S-box used in the examples of this page)
- François-Xavier Standaert, Tal G. Malkin and Moti Yung, A unified framework for the analysis of side-channel key recovery attacks, EUROCRYPT 2009, LNCS 5479, pages 443 to 461, the information theoretic metric and the definitions of the success rate and the guessing entropy
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag DNRK95 Edit this page History Report an error Markdown