Algorithm Search⌘K

Algorithmcore

Correlation power analysis

Also called Brier-Clavier-Olivier attack.

Ranks key guesses by the Pearson correlation between measured power and a leakage model such as the Hamming weight of an intermediate value.

Time
Θ(g m T) worst · average · best
Space
Θ(m + T + g) extra
Where
T = the number of samples in each trace; g = the number of key guesses; m = the number of traces
Origin
Eric Brier, Christophe Clavier, Francis Olivier, 2004

Correlation power analysis (CPA) finds a key from power traces by a correlation test. For each key guess, it predicts the leakage of each trace with a model, usually the Hamming weight or the Hamming distance of an intermediate value, and it computes the Pearson correlation between the prediction and the measured power at each time sample. The guess with the largest correlation wins. Brier, Clavier and Olivier (2004) introduced it as an improvement of differential power analysis, which uses only one bit of the value.

In plain words

A chip uses a little more power for each wire that carries a one. Guess a small part of the key. With the guess and the known input of each run, you can compute a value inside the chip and count its ones. If the guess is right, the runs with many ones are the runs where the chip used more power, so the two lists of numbers rise and fall together. If the guess is wrong, your counts are for a different value, and the two lists agree much less. A correlation coefficient measures how well two lists rise and fall together. Compute it for every guess and keep the guess with the strongest agreement.

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∗]=ε⋅HW(S(pi⊕k))+Nij∗,ℓi[j]=Nij for j≠j∗,\ell_i[j^\ast] = \varepsilon \cdot \mathrm{HW}(S(p_i \oplus k)) + 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, ε>0\varepsilon > 0, 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 does not know j∗j^\ast, ε\varepsilon or σ\sigma. The goal is to output kk. The cost model is the real RAM.

The attacker needs a model that is close to linear in the true leakage, but not the scale or the offset: the correlation does not change if the power is a⋅HW+ca \cdot \mathrm{HW} + c for any a>0a > 0 and any cc.

The algorithm

  1. CPA(traces (p_1, l_1) .. (p_m, l_m), S-box S) ▷ each l_i has T samples
  2. 1best ← none, top ← -∞
  3. 2for each key guess g = 0 .. |S| - 1 do
  4. 3for i = 1 .. m do h_i ← HW(S(p_i ⊕ g)) ▷ the hypothesis of trace i
  5. 4for each sample j = 1 .. T do
  6. 5r_j ← corr((h_1 .. h_m), (l_1[j] .. l_m[j])) ▷ 0 if one list is constant
  7. 6score(g) ← max over j of |r_j|
  8. 7if score(g) > top then
  9. 8best ← g, top ← score(g)
  10. 9return best and the list of scores

Line L5 is the sample Pearson correlation

rj=∑i(hi−hˉ)(ℓi[j]−ℓˉ[j])∑i(hi−hˉ)2 ∑i(ℓi[j]−ℓˉ[j])2.r_j = \frac{\sum_i (h_i - \bar h)(\ell_i[j] - \bar\ell[j])}{\sqrt{\sum_i (h_i - \bar h)^2 \, \sum_i (\ell_i[j] - \bar\ell[j])^2}} .

The code computes the two means first and then the three sums of centred products. Line L6 takes the absolute value, so the attack works for a device whose power rises with the Hamming weight and for one whose power falls with it. Line L7 uses a strict test, so the first guess with the top score wins.

Example

Take k=Bk = \texttt{B} (hex), ε=1\varepsilon = 1, no noise, one sample in each trace, and each of the 16 inputs once. The trace values are HW(S(p⊕B))\mathrm{HW}(S(p \oplus \texttt{B})) for p=0,…,Fp = 0, \ldots, \texttt{F}:

1,4,3,2,1,1,3,1,3,2,2,2,3,2,0,2.1, 4, 3, 2, 1, 1, 3, 1, 3, 2, 2, 2, 3, 2, 0, 2 .

The signed correlation of each guess with these values is:

guess 0 1 2 3 4 5 6 7 8 9 A B C D E F
r 0.125 0.5 0.375 -0.5 -0.625 0.5 0.125 -0.5 0.25 -0.375 -0.25 1.0 0.25 -0.75 -0.25 0.125

The right guess has r=1r = 1, because the hypothesis is exactly the trace. The closest rival is the guess D, which is k⊕6k \oplus 6, with ∣r∣=0.75|r| = 0.75. For DPA on the same traces the margin was 0.250.25 on a scale where the right key scores 11; here it is also 0.250.25, but every one of the 16 traces adds to the signal, not only the 8 on one side of a bit.

Correctness

The loop of line L2 keeps the loop invariant that top is the largest score of the guesses seen so far, and best is the first guess with that score, so line L9 returns the first argmax of the scores. In the model, the population correlation of the hypothesis of guess gg with the leaking sample is

ρg=c(g⊕k)⋅ρ,ρ=11+σ2/ε2,\rho_g = c(g \oplus k) \cdot \rho, \qquad \rho = \frac{1}{\sqrt{1 + \sigma^2/\varepsilon^2}},

where c(δ)c(\delta) is the correlation of HW(S(X))\mathrm{HW}(S(X)) and HW(S(X⊕δ))\mathrm{HW}(S(X \oplus \delta)) for a uniform XX. Here c(0)=1c(0) = 1, and ∣c(δ)∣≤0.75|c(\delta)| \le 0.75 for δ≠0\delta \ne 0 on the PRESENT S-box. By the law of large numbers each rjr_j converges to its population value, so the right key wins with a probability that tends to 1. This is a theorem in the stated model. The proof gives the details and the table of cc.

Proof: CPA returns the first top-scoring guess, and it finds the key in the Hamming weight modelfull

We write s(g)s(g) for the score that line L6 gives to the guess gg.

Lemma 1 (the loop of line L2). After the iteration for guess gg, top is max⁡h≤gs(h)\max_{h \le g} s(h) and best is the smallest h≤gh \le g with s(h)=s(h) = top.

Proof. By induction on gg, as for DPA. Line L1 starts with top =−∞= -\infty. Every score is a finite number in [0,1][0, 1], so the first guess always passes line L7. Later, line L7 replaces best only when the new score is strictly larger, so among guesses with equal top scores the first one stays. □\square

So line L9 returns the first argmax of the scores.

Lemma 2 (scale and offset). For a≠0a \ne 0 and any cc, replacing every ℓi[j]\ell_i[j] by aℓi[j]+ca \ell_i[j] + c does not change ∣rj∣|r_j|.

Proof. The offset cc cancels in ℓi[j]−ℓˉ[j]\ell_i[j] - \bar\ell[j]. The factor aa multiplies the numerator of rjr_j by aa and the square root in the denominator by ∣a∣|a|. So rjr_j is multiplied by the sign of aa, and ∣rj∣|r_j| does not change. □\square

The model. Let kk be the key. The inputs are independent and uniform on {0,…,15}\{0, \ldots, 15\}. At the sample j∗j^\ast, ℓi[j∗]=ε HW(S(pi⊕k))+Nij∗\ell_i[j^\ast] = \varepsilon \, \mathrm{HW}(S(p_i \oplus k)) + N_{ij^\ast} with ε>0\varepsilon > 0, and ℓi[j]=Nij\ell_i[j] = N_{ij} elsewhere. The noise values are independent of each other and of the inputs, with mean 0 and variance σ2\sigma^2. For XX uniform on {0,…,15}\{0, \ldots, 15\} define

c(δ)=corr⁡(HW(S(X)), HW(S(X⊕δ))).c(\delta) = \operatorname{corr}\big(\mathrm{HW}(S(X)),\ \mathrm{HW}(S(X \oplus \delta))\big).

Lemma 3 (the population correlation). Fix a guess gg, put δ=g⊕k\delta = g \oplus k, and let h=HW(S(p⊕g))h = \mathrm{HW}(S(p \oplus g)) for a uniform input pp. Then

corr⁡(h,ℓ[j∗])=c(δ) ρ,ρ=εε2+σ2,\operatorname{corr}(h, \ell[j^\ast]) = c(\delta) \, \rho, \qquad \rho = \frac{\varepsilon}{\sqrt{\varepsilon^2 + \sigma^2}},

and corr⁡(h,ℓ[j])=0\operatorname{corr}(h, \ell[j]) = 0 for j≠j∗j \ne j^\ast.

Proof. Put X=p⊕kX = p \oplus k, which is uniform, so h=HW(S(X⊕δ))h = \mathrm{HW}(S(X \oplus \delta)). Since SS is a bijection, S(X)S(X) and S(X⊕δ)S(X \oplus \delta) are both uniform on 4 bits. The Hamming weight of a uniform 4-bit value is a sum of 4 independent fair bits, so its variance is 4⋅14=14 \cdot \tfrac14 = 1. So Var⁡(h)=1\operatorname{Var}(h) = 1, and the covariance of hh with HW(S(X))\mathrm{HW}(S(X)) equals their correlation c(δ)c(\delta). The noise is independent of pp, so

Cov⁡(h,ℓ[j∗])=ε c(δ),Var⁡(ℓ[j∗])=ε2⋅1+σ2.\operatorname{Cov}(h, \ell[j^\ast]) = \varepsilon \, c(\delta), \qquad \operatorname{Var}(\ell[j^\ast]) = \varepsilon^2 \cdot 1 + \sigma^2 .

Dividing the covariance by 1⋅(ε2+σ2)\sqrt{1 \cdot (\varepsilon^2 + \sigma^2)} gives the first claim. For j≠j∗j \ne j^\ast, ℓ[j]\ell[j] is independent of hh, so the covariance is 0. □\square

Lemma 4 (the table of cc). For the PRESENT S-box S=(C,5,6,B,9,0,A,D,3,E,F,8,4,7,1,2)S = (\texttt{C}, 5, 6, \texttt{B}, 9, 0, \texttt{A}, \texttt{D}, 3, \texttt{E}, \texttt{F}, 8, 4, 7, 1, 2), the values c(δ)c(\delta) for δ=0,1,…,15\delta = 0, 1, \ldots, 15 are

1, −0.25, −0.375, 0.25, 0.125, −0.25, −0.75, 0.25, −0.5, 0.375, 0.5, 0.125, −0.5, 0.125, 0.5, −0.625.1,\ -0.25,\ -0.375,\ 0.25,\ 0.125,\ -0.25,\ -0.75,\ 0.25,\ -0.5,\ 0.375,\ 0.5,\ 0.125,\ -0.5,\ 0.125,\ 0.5,\ -0.625 .

So ∣c(δ)∣≤0.75|c(\delta)| \le 0.75 for every δ≠0\delta \ne 0, with equality only at δ=6\delta = 6.

Proof. Both Hamming weights have mean 2 and variance 1, so c(δ)=116∑x(HW(S(x))−2)(HW(S(x⊕δ))−2)c(\delta) = \tfrac{1}{16}\sum_{x} (\mathrm{HW}(S(x)) - 2)(\mathrm{HW}(S(x \oplus \delta)) - 2), a finite sum of 16 terms. For example, for δ=6\delta = 6 the products are, for x=0,…,15x = 0, \ldots, 15, 0,0,0,−2,0,−2,0,0,0,−1,−2,−1,−2,−1,0,−10, 0, 0, -2, 0, -2, 0, 0, 0, -1, -2, -1, -2, -1, 0, -1, and the sum is −12-12, so c(6)=−12/16=−0.75c(6) = -12/16 = -0.75. The test file computes all 16 values with statistics.correlation and checks that the noiseless scores of the code equal them, for every key. □\square

Theorem (consistency). In the model, with the PRESENT S-box, the probability that line L9 returns best =k= k tends to 1 as m→∞m \to \infty.

Proof. For a fixed guess and sample, rjr_j is a continuous function of the five sample moments hˉ\bar h, ℓˉ[j]\bar\ell[j], h2‾\overline{h^2}, ℓ[j]2‾\overline{\ell[j]^2} and hℓ[j]‾\overline{h \ell[j]}, wherever the two sample variances are positive. All the variables have finite second moments, so by the strong law of large numbers each sample moment converges with probability 1 to its population value, and both population variances are positive (Var⁡(h)=1\operatorname{Var}(h) = 1 and Var⁡(ℓ[j])≥σ2\operatorname{Var}(\ell[j]) \ge \sigma^2, or ε2\varepsilon^2 at j∗j^\ast). So rjr_j converges with probability 1 to the population correlation of Lemma 3. Line L6 takes a maximum of finitely many absolute values, which is continuous, so

s(g)→∣c(g⊕k)∣ ρ.s(g) \to |c(g \oplus k)| \, \rho .

The limit is ρ\rho for g=kg = k and at most 0.75ρ0.75\rho for g≠kg \ne k, by Lemma 4. There are 16 guesses, so with probability 1 there is an MM such that s(k)>0.875ρ>s(g)s(k) > 0.875\rho > s(g) for all g≠kg \ne k and all m≥Mm \ge M. Then kk is the only guess with the top score, and by Lemma 1 line L9 returns it. Convergence with probability 1 implies convergence in probability. ■\blacksquare

Remark. Without the S-box (the pitfall of line L3), the hypothesis of g=k⊕Fg = k \oplus \texttt{F} is 4−HW(p⊕k)4 - \mathrm{HW}(p \oplus k), whose correlation with HW(p⊕k)\mathrm{HW}(p \oplus k) is −1-1. Its absolute value ties with the right key for every mm, so no number of traces separates the two guesses.

Complexity

For each of the gg guesses, line L3 costs Θ(m)\Theta(m) and lines L4 and L5 cost Θ(mT)\Theta(mT), so the time is Θ(gmT)\Theta(g m T) in every case. The extra space is Θ(m)\Theta(m) for the hypothesis, Θ(T)\Theta(T) for the correlations and Θ(g)\Theta(g) for the scores. For a 4-bit S-box, g=16g = 16; for a byte of AES, g=256g = 256.

The number of traces depends on ρ\rho, the correlation of the right guess. A heuristic from Mangard, Oswald and Popp (Chapter 6) uses the Fisher zz transform to find the mm at which ρ\rho is distinguished from 0 at the error level α\alpha:

m≈3+8 z1−α2ln⁡21+ρ1−ρ.m \approx 3 + 8 \, \frac{z_{1-\alpha}^2}{\ln^2 \frac{1+\rho}{1-\rho}} .

With z1−α=3.719z_{1-\alpha} = 3.719 (α=10−4\alpha = 10^{-4}) this gives 38.6 traces for ρ=0.707\rho = 0.707, 94.7 for ρ=0.5\rho = 0.5 and 2750.8 for ρ=0.1\rho = 0.1. For small ρ\rho, ln⁡1+ρ1−ρ≈2ρ\ln\frac{1+\rho}{1-\rho} \approx 2\rho, and the rule becomes m≈28/ρ2m \approx 28/\rho^2: half the correlation costs four times the traces. The heuristic compares the right key with no correlation; it does not see the wrong keys with ∣c∣=0.75|c| = 0.75. A measurement in the model, with 200 seeded runs for each cell, ε=1\varepsilon = 1, one sample in each trace and a random key in each run:

traces m 10 20 40 80 160 320
success rate, σ = 1 (ρ = 0.707) 0.595 0.825 0.955 1.0 1.0 1.0
success rate, σ = 2 (ρ = 0.447) 0.21 0.405 0.635 0.87 0.99 1.0

At σ=1\sigma = 1, DPA on bit 1 needed about 400 traces for a success rate above 0.9 in the same model; CPA needs about 40.

Properties

  • Invariant to scale and offset. The score does not change under ℓ↦aℓ+c\ell \mapsto a\ell + c with a≠0a \ne 0, so the attacker needs no calibration of the device.
  • Uses all bits. In the Hamming weight model each bit of the value adds to the covariance, so the signal is larger than for a single-bit DPA.
  • Linear. It detects only a linear dependence between the model and the power. If the true leakage is a non-linear function of the model, the correlation can be small even when the leak is large. Mutual information analysis has no such limit.
  • First order. Against Boolean masking, the mean power at each sample is independent of the key, so every ρg\rho_g is 0. A second-order CPA on a combination of two samples is then necessary.
  • Divide and conquer. Each key part is found on its own. The full list of scores can be given to key rank estimation.

Variants and improvements

  • The Hamming distance model. Brier, Clavier and Olivier model the power as a⋅HD(D,R)+ba \cdot \mathrm{HD}(D, R) + b, the number of bits that flip when a register goes from a reference state RR to the data DD. This fits a bus or a register in CMOS hardware better than the Hamming weight.
  • Precomputed classes. Sum the traces and their squares for each of the 16 input values once. Then each guess needs only the 16 class sums, and the time becomes Θ(mT+16gT)\Theta(mT + 16 g T).
  • Incremental CPA. Keep the five running sums ∑h\sum h, ∑h2\sum h^2, ∑ℓ\sum \ell, ∑ℓ2\sum \ell^2 and ∑hℓ\sum h\ell so that new traces can be added one at a time.
  • Linear regression. Fit the power as a linear regression on the bits of the value, so that each bit gets its own weight. This is a step toward a template attack.
  • Second order. Against a first-order masked implementation, correlate the model with the centred product of two samples.

When to use it

Use CPA as the default non-profiled attack when the leakage is close to the Hamming weight or the Hamming distance of a known intermediate value. Use MIA when the shape of the leakage is not known, and a template attack when a copy of the device is available for profiling. To find out only whether a device leaks, with no key recovery, a leakage test is cheaper.

Pitfalls

  • A linear target. If line L3 is hi←HW(pi⊕g)h_i \leftarrow \mathrm{HW}(p_i \oplus g), the hypothesis of g⊕Fg \oplus \texttt{F} is 4−hi4 - h_i, the exact negative, so with line L6 the guesses kk and k⊕Fk \oplus \texttt{F} both score 1 and cannot be told apart. More generally a key addition alone gives a poor separation. Target the output of the S-box, as in line L3 above, where the non-linear map separates the guesses.
  • The signed score with the wrong sign. If line L6 is score(g) ← max over j of rjr_j and the device leaks −HW-\mathrm{HW} (for example a bus that is precharged to ones), the right key scores −1-1 and loses. Use the absolute value of line L6 unless the sign of the leakage is known.
  • The one-pass formula. Computing line L5 as ∑hℓ−mhˉℓˉ\sum h\ell - m \bar h \bar\ell loses precision when the samples carry a large constant offset, because two large numbers that are almost equal are subtracted. Centre the values first, as the code does.
  • A constant column. If all traces have the same value at a sample, or a guess gives the same hypothesis for every trace, the denominator of line L5 is 0. Define rj=0r_j = 0 in that case.

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 table, the exact correlations for every key, the agreement with statistics.correlation on 500 random inputs, the value of ρ\rho at 2000 traces, the success rate, and the rule of thumb.

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.

correlation_power_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/correlation-power-analysis/. The authors are listed in prov/H5FN0Q.jsonl.
"""Correlation power analysis on a synthetic Hamming weight leakage model.

The traces come from a stated statistical model, never from a device:
sample ``leak_sample`` of a trace is ``epsilon * 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

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,
    epsilon: float = 1.0,
    sbox: tuple[int, ...] = PRESENT_SBOX,
) -> list[Trace]:
    """Draw m synthetic traces (input, samples) from the Hamming weight model.

    Each input p is uniform on the S-box domain. Sample ``leak_sample`` is
    epsilon * HW(sbox[p ^ key]) + N(0, sigma^2); the other samples are
    N(0, sigma^2). 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] += epsilon * hamming_weight(sbox[p ^ key])
        out.append((p, row))
    return out


def pearson(xs: list[float], ys: list[float]) -> float:
    """Pearson correlation of two lists of the same length, by two passes.

    Returns 0.0 when either list has zero variance. Cost: O(len(xs)).
    """
    n = len(xs)
    mx = sum(xs) / n
    my = sum(ys) / n
    sxy = sxx = syy = 0.0
    for x, y in zip(xs, ys):
        dx = x - mx
        dy = y - my
        sxy += dx * dy
        sxx += dx * dx
        syy += dy * dy
    if sxx == 0.0 or syy == 0.0:
        return 0.0
    return sxy / math.sqrt(sxx * syy)


def correlation_power_analysis(
    traces: list[Trace],
    sbox: tuple[int, ...] = PRESENT_SBOX,
    signed: bool = False,
) -> tuple[int, list[float]]:
    """Return (best guess, score of each guess) by the attack of Brier et al.

    For each key guess g the hypothesis of trace i is HW(sbox[p_i ^ g]).
    The score of g is the largest absolute Pearson correlation between the
    hypothesis and one sample of the traces (the largest signed value when
    ``signed`` is True). A sample or a hypothesis with zero variance gives
    correlation 0. The first guess with the top score wins; with no trace
    at all the call raises ValueError.

    Precondition: every trace has the same number of samples T >= 1, and
    every input is in range(len(sbox)).
    Cost: Theta(g * m * T) time for g = len(sbox) guesses and m traces,
    and Theta(m + T + g) extra space.
    """
    if not traces:
        raise ValueError("need at least one trace")
    t_len = len(traces[0][1])
    best, top = -1, -math.inf  # @line L1
    scores: list[float] = []
    for g in range(len(sbox)):  # @line L2
        h = [float(hamming_weight(sbox[p ^ g])) for p, _ in traces]  # @line L3
        rs = []
        for j in range(t_len):  # @line L4
            rs.append(pearson(h, [row[j] for _, row in traces]))  # @line L5
        score = max(rs) if signed else max(abs(r) for r in rs)  # @line L6
        scores.append(score)
        if score > top:  # @line L7
            best, top = g, score  # @line L8
    return best, scores  # @line L9


def traces_needed(rho: float, z: float = 3.719016485) -> float:
    """Rule of thumb for the number of traces to detect a correlation rho.

    n = 3 + 8 * z^2 / ln^2((1 + rho) / (1 - rho)), from the Fisher z
    transform (Mangard, Oswald and Popp, Chapter 6). The default z is the
    quantile for alpha = 0.0001. Precondition: 0 < rho < 1. Cost: O(1).
    """
    return 3.0 + 8.0 * (z / math.log((1.0 + rho) / (1.0 - rho))) ** 2
test_correlation_power_analysis.py 121 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/correlation-power-analysis/. The authors are listed in prov/H5FN0Q.jsonl.

import math
import random
import statistics

import pytest
from correlation_power_analysis import (
    PRESENT_SBOX,
    correlation_power_analysis,
    hamming_weight,
    simulate_traces,
    traces_needed,
)

IDENTITY = tuple(range(16))


def oracle_scores(traces, sbox, signed):
    """Scores written out with statistics.correlation."""
    t_len = len(traces[0][1])
    out = []
    for g in range(len(sbox)):
        h = [float(hamming_weight(sbox[p ^ g])) for p, _ in traces]
        rs = []
        for j in range(t_len):
            col = [row[j] for _, row in traces]
            try:
                rs.append(statistics.correlation(h, col))
            except statistics.StatisticsError:
                rs.append(0.0)
        out.append(max(rs) if signed else max(abs(r) for r in rs))
    return out


def exact_correlation(delta):
    """Exact corr(HW(S(X)), HW(S(X ^ delta))) for X uniform on 4 bits."""
    a = [hamming_weight(PRESENT_SBOX[x]) for x in range(16)]
    b = [hamming_weight(PRESENT_SBOX[x ^ delta]) for x in range(16)]
    return statistics.correlation(a, b)


def balanced_traces(key, sbox=PRESENT_SBOX):
    return [(p, [float(hamming_weight(sbox[p ^ key]))]) for p in range(16)]


def test_worked_example() -> None:
    best, scores = correlation_power_analysis(balanced_traces(0xB), signed=True)
    assert best == 0xB
    want = [0.125, 0.5, 0.375, -0.5, -0.625, 0.5, 0.125, -0.5,
            0.25, -0.375, -0.25, 1.0, 0.25, -0.75, -0.25, 0.125]
    assert scores == pytest.approx(want, abs=1e-12)
    _, absolute = correlation_power_analysis(balanced_traces(0xB))
    assert sorted(absolute, reverse=True)[:2] == pytest.approx([1.0, 0.75])


def test_noiseless_scores_are_the_exact_correlations() -> None:
    for key in range(16):
        best, scores = correlation_power_analysis(balanced_traces(key), signed=True)
        assert best == key
        for g in range(16):
            assert scores[g] == pytest.approx(exact_correlation(g ^ key), abs=1e-12)
    assert max(abs(exact_correlation(d)) for d in range(1, 16)) == pytest.approx(0.75)


def test_linear_target_pitfall() -> None:
    # Without the S-box, HW(p ^ g) and HW(p ^ g ^ 0xF) are exact negatives.
    for key in range(16):
        _, scores = correlation_power_analysis(balanced_traces(key, IDENTITY), sbox=IDENTITY)
        assert scores[key] == pytest.approx(1.0)
        assert scores[key ^ 0xF] == pytest.approx(1.0)


def test_edges() -> None:
    with pytest.raises(ValueError):
        correlation_power_analysis([])
    best, scores = correlation_power_analysis([(3, [0.5])])
    assert best == 0 and scores == [0.0] * 16
    best, scores = correlation_power_analysis([(1, [2.0]), (2, [2.0]), (7, [2.0])])
    assert scores == [0.0] * 16


def test_against_oracle_random() -> None:
    rng = random.Random(20240502)
    for _ in range(500):
        m = rng.randrange(2, 12)
        t_len = rng.randrange(1, 4)
        signed = rng.random() < 0.5
        traces = [(rng.randrange(16), [rng.uniform(-3, 3) for _ in range(t_len)]) for _ in range(m)]
        best, scores = correlation_power_analysis(traces, signed=signed)
        want = oracle_scores(traces, PRESENT_SBOX, signed)
        assert scores == pytest.approx(want, abs=1e-9)
        assert want[best] == pytest.approx(max(want), abs=1e-9)


def test_correlation_of_the_right_key() -> None:
    # rho = 1 / sqrt(1 + sigma^2) for epsilon = 1, since Var(HW) = 1.
    rng = random.Random(3)
    rho = 1.0 / math.sqrt(2.0)
    for _ in range(3):
        traces = simulate_traces(rng, 5, m=2000, sigma=1.0, samples=1, leak_sample=0)
        _, scores = correlation_power_analysis(traces)
        assert abs(scores[5] - rho) < 0.05


def test_success_rate_with_noise() -> None:
    rng = random.Random(9)
    runs = 20
    hits = 0
    for _ in range(runs):
        key = rng.randrange(16)
        best, _ = correlation_power_analysis(simulate_traces(rng, key, m=200, sigma=1.0))
        hits += best == key
    assert hits >= runs - 1


def test_rule_of_thumb() -> None:
    assert traces_needed(1.0 / math.sqrt(2.0)) == pytest.approx(38.61, abs=0.01)
    assert traces_needed(0.5) == pytest.approx(94.7, abs=0.1)
    assert traces_needed(0.1) == pytest.approx(2750.8, abs=0.5)

History

Brier, Clavier and Olivier presented CPA at CHES 2004. They replaced the difference of means of Kocher, Jaffe and Jun (1999) by a correlation with a Hamming distance model. The book of Mangard, Oswald and Popp (2007) describes the correlation attack in its chapter on DPA, together with the rule of thumb for the number of traces. Gierlichs, Batina, Tuyls and Preneel (2008) proposed mutual information as a generic replacement for the correlation.

References

  1. Eric Brier, Christophe Clavier and Francis Olivier, Correlation power analysis with a leakage model, CHES 2004, LNCS 3156, pages 16 to 29, the linear leakage model in the Hamming distance, the correlation coefficient as the distinguisher, and the comparison with DPA
  2. Stefan Mangard, Elisabeth Oswald and Thomas Popp, Power Analysis Attacks, Springer, 2007, ISBN 978-0-387-30857-9, Chapter 3 (the Hamming weight and Hamming distance models), Chapter 4 (the statistics of power traces) and Chapter 6, pages 119 to 165 (the correlation attack and the rule of thumb for the number of traces)
  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 definitions of the success rate and the guessing entropy

Where this leads

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