Algorithm Search⌘K

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
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 mm pairs (pi,ℓi)(p_i, \ell_i), with pip_i a known input nibble and ℓi\ell_i a trace of TT real samples. The device holds a fixed key nibble kk. The leakage model is

ℓi[j∗]=f(HW(S(pi⊕k)))+Nij∗,ℓi[j]=Nij for j≠j∗,\ell_i[j^\ast] = f\big(\mathrm{HW}(S(p_i \oplus k))\big) + N_{ij^\ast}, \qquad \ell_i[j] = N_{ij} \ \text{for } j \ne j^\ast,

where SS is the 4-bit S-box of PRESENT, ff is a function that the attacker does not know, the noise values NijN_{ij} are independent with law N(0,σ2)N(0, \sigma^2), 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 kk. The cost model is the real RAM.

The algorithm

The estimate of the mutual information uses a histogram: each sample is cut into BB bins of equal width from its smallest to its largest value. The entropies are the plug-in Shannon entropies of the counts, in bits.

  1. MIA(traces (p_1, l_1) .. (p_m, l_m), S-box S, model M, bins B)
  2. 1best ← none, top ← -∞
  3. 2for each sample j: bin_i[j] ← the bin of l_i[j] among B equal bins of column j
  4. 3for each key guess g = 0 .. |S| - 1 do
  5. 4for i = 1 .. m do h_i ← M(S(p_i ⊕ g)) ▷ the model value, HW here
  6. 5for each sample j = 1 .. T do
  7. 6count the pairs (h_i, bin_i[j]) in a table
  8. 7I_j ← H(bin) + H(h) - H(h, bin) ▷ plug-in entropies of the counts
  9. 8score(g) ← max over j of I_j
  10. 9if score(g) > top then
  11. 10best ← g, top ← score(g)
  12. 11return best and the list of scores

Line L7 is the identity I(X;Y)=H(X)+H(Y)−H(X,Y)I(X; Y) = H(X) + H(Y) - H(X, Y), 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 H(bin∣h)H(\text{bin} \mid h): the right guess is the one whose groups have the most concentrated power.

Example

Hamming weight leakage. Take k=Bk = \texttt{B}, f(w)=wf(w) = w, no noise, one sample in each trace, each of the 16 inputs once, and B=5B = 5 bins. The trace values 0,…,40, \ldots, 4 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 H(HW)=2.031H(\mathrm{HW}) = 2.031 bits, the entropy of the weights 0,1,2,3,40, 1, 2, 3, 4 with counts 1,4,6,4,11, 4, 6, 4, 1: the groups are pure. The closest rivals are the guesses 1 and 5, at 1.2811.281 bits.

Non-linear leakage. Now let f(w)=(w−2)2f(w) = (w - 2)^2, so the power is 0 for weight 2, 1 for weights 1 and 3, and 4 for weights 0 and 4. The covariance of ww and (w−2)2(w-2)^2 is the third central moment of a symmetric binomial law, which is 0, so the right guess of CPA has correlation 0. With B=4B = 4 bins, MIA gives the right guess 1.4061.406 bits and the best wrong guess, k⊕Fk \oplus \texttt{F}, 1.01.0 bit. A measurement in the model, with σ=1\sigma = 1, 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 0.3060.306 with (w−2)2(w - 2)^2, 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 HW(S(p⊕k))\mathrm{HW}(S(p \oplus k)), the binned power depends only on the noise, so a wrong model value cannot carry more information about it. For every binning bb and every gg,

I(b(ℓ[j∗]); HW(S(p⊕g)))≤I(b(ℓ[j∗]); HW(S(p⊕k))).I\big(b(\ell[j^\ast]);\ \mathrm{HW}(S(p \oplus g))\big) \le I\big(b(\ell[j^\ast]);\ \mathrm{HW}(S(p \oplus k))\big).

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 n(a,c)n(a, c) with total mm, write P^(a,c)=n(a,c)/m\hat P(a, c) = n(a, c)/m and P^(a)\hat P(a), P^(c)\hat P(c) 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. □\square

Lemma 2 (line L7). Line L7 computes the plug-in mutual information

I^=∑a,cP^(a,c)log⁡P^(a,c)P^(a)P^(c),\hat I = \sum_{a, c} \hat P(a, c) \log \frac{\hat P(a, c)}{\hat P(a) \hat P(c)},

where the sum is over the cells with n(a,c)>0n(a, c) > 0, and I^≥0\hat I \ge 0.

Proof. Expand the logarithm of the quotient: log⁡P^(a,c)−log⁡P^(a)−log⁡P^(c)\log \hat P(a, c) - \log \hat P(a) - \log \hat P(c). Summing P^(a,c)\hat P(a, c) times the first term gives −H(h,bin)-H(h, \text{bin}). Summing over cc first, ∑cP^(a,c)=P^(a)\sum_c \hat P(a, c) = \hat P(a), so the second term gives H(h)H(h), and in the same way the third gives H(bin)H(\text{bin}). So I^=H(bin)+H(h)−H(h,bin)\hat I = H(\text{bin}) + H(h) - H(h, \text{bin}), which is line L7. It is the Kullback-Leibler divergence of P^(a,c)\hat P(a, c) from the product P^(a)P^(c)\hat P(a)\hat P(c), and so it is at least 0 by Gibbs' inequality. □\square

The model. The inputs pp are uniform on {0,…,15}\{0, \ldots, 15\}, and ℓ[j∗]=f(Wk)+N\ell[j^\ast] = f(W_k) + N with Wg=HW(S(p⊕g))W_g = \mathrm{HW}(S(p \oplus g)) for each guess gg, any function ff, and noise NN independent of pp. Let bb be any function from the reals to a finite set of bins, and put Z=b(ℓ[j∗])Z = b(\ell[j^\ast]).

Lemma 3 (the right key has the largest population value). For every guess gg, I(Z;Wg)≤I(Z;Wk)I(Z; W_g) \le I(Z; W_k).

Proof. Given Wk=wW_k = w, the value Z=b(f(w)+N)Z = b(f(w) + N) is a function of NN alone, and NN is independent of pp, so ZZ is independent of WgW_g given WkW_k. That is, I(Z;Wg∣Wk)=0I(Z; W_g \mid W_k) = 0. Apply the chain rule of mutual information to the pair (Wg,Wk)(W_g, W_k) in two orders:

I(Z;Wg,Wk)=I(Z;Wk)+I(Z;Wg∣Wk)=I(Z;Wk),I(Z; W_g, W_k) = I(Z; W_k) + I(Z; W_g \mid W_k) = I(Z; W_k),
I(Z;Wg,Wk)=I(Z;Wg)+I(Z;Wk∣Wg)≥I(Z;Wg).I(Z; W_g, W_k) = I(Z; W_g) + I(Z; W_k \mid W_g) \ge I(Z; W_g).

So I(Z;Wg)≤I(Z;Wk)I(Z; W_g) \le I(Z; W_k). □\square

This is the data processing inequality for the chain Wg→Wk→ZW_g \to W_k \to Z. It holds for every ff, 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 pp, and that I(Z;Wk)>I(Z;Wg)I(Z; W_k) > I(Z; W_g) for every g≠kg \ne k. Then the probability that MIA returns kk tends to 1 as m→∞m \to \infty.

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 xlog⁡xx \log x is continuous on [0,1][0, 1]. So each estimate converges with probability 1 to the population value. At a sample j≠j∗j \ne j^\ast the bin is independent of pp, so the limit is 0 for every guess. At j∗j^\ast the limit of guess gg is I(Z;Wg)I(Z; W_g). So score(k)→I(Z;Wk)\mathrm{score}(k) \to I(Z; W_k), and for g≠kg \ne k, score(g)→max⁡(I(Z;Wg),0)=I(Z;Wg)\mathrm{score}(g) \to \max(I(Z; W_g), 0) = I(Z; W_g), which is strictly smaller by assumption. With 16 guesses, with probability 1 the right key has the strictly largest score for all large mm, and Lemma 1 then returns it. ■\blacksquare

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 hi=M(S(pi⊕g))h_i = M(S(p_i \oplus g)) for an injective MM, then all 16 scores are equal, for every set of traces.

Proof. The map p↦M(S(p⊕g))p \mapsto M(S(p \oplus g)) is injective, because XOR with gg, the S-box and MM are all injective. So for every guess the model value is a relabelling of the input pp, and the table of line L6 for guess gg is the table of the pairs (pi,bini[j])(p_i, \text{bin}_i[j]) 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. ■\blacksquare

The examples. On the 16 noiseless balanced traces with f(w)=wf(w) = w and 5 bins, each value has its own bin, so the score of gg is the exact I(Wk;Wg)I(W_k; W_g) for a uniform input. For g=kg = k this is H(Wk)=−∑c16log⁡c16H(W_k) = -\sum \tfrac{c}{16}\log\tfrac{c}{16} over the counts 1,4,6,4,11, 4, 6, 4, 1, which is 2.0312.031 bits. For f(w)=(w−2)2f(w) = (w-2)^2 and 4 bins, the values 0,1,40, 1, 4 fall into 3 different bins, so the score of kk is the entropy of the counts 6,8,26, 8, 2, which is 1.4061.406 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 Θ(mT)\Theta(mT) time. For each of the gg guesses and each of the TT samples, line L6 fills a table of V×BV \times B counts from mm pairs, and line L7 reads the table, which costs Θ(m+VB)\Theta(m + VB). So the time is Θ(gT(m+VB))\Theta(g T (m + VB)) in every case. The extra space is Θ(mT)\Theta(mT) for the bin indices, Θ(VB)\Theta(VB) for one table and Θ(g)\Theta(g) for the scores. With the Hamming weight model of a 4-bit value, V=5V = 5.

Properties

  • Generic. The score sees any dependence between the model and the power, linear or not, in either direction. It needs no assumption on ff 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 (V−1)(B−1)/(2mln⁡2)(V-1)(B-1)/(2m \ln 2) 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 H(bin)H(\text{bin}) is the same for every guess, so it is enough to rank the guesses by H(bin∣h)H(\text{bin} \mid h), 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 m1/3m^{1/3}, 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 hi←S(pi⊕g)h_i \leftarrow S(p_i \oplus g), 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, 2.0312.031 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 H(h,bin)=H(bin)H(h, \text{bin}) = H(\text{bin}) and line L7 gives H(h)H(h), 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 plog⁡(p/pq)p \log (p / pq) 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.

mutual_information_analysis.pyI0RawGitHub
# 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

  1. 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
  2. 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)
  3. 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)
  4. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.average
  • a full proof of time.best
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example