Algorithm Search⌘K

Algorithmcore

Differential power analysis

Also called DPA, Kocher DPA.

Splits many power traces by a predicted intermediate bit under each key guess, and takes the guess whose difference of means shows a peak.

Time
Θ(g m T) worst · average · best
Space
Θ(g + T) extra
Where
T = the number of samples in each trace; g = the number of key guesses; m = the number of traces
Origin
Paul Kocher, Joshua Jaffe, Benjamin Jun, 1999

Differential power analysis (DPA) finds a key from many power traces of a device that uses the key. For each key guess, it splits the traces into two groups by one bit of an intermediate value that the guess predicts, and it subtracts the mean trace of one group from the mean trace of the other. Under the right guess the split follows the real data, so the difference shows a peak; under a wrong guess the split is close to random and the difference is close to zero. Kocher, Jaffe and Jun (1999) used it against DES on smart cards, and it is the reason why masking exists.

In plain words

A chip uses more power when more of its wires carry a one. The attacker cannot read the wires, but can record the power many times while the chip encrypts known inputs. Take one guess for a small part of the key. With that guess, you can compute one bit of a value inside the chip for each input. Put the recordings where that bit is one in a pile, and the others in a second pile. Average each pile and compare the averages. If the guess is right, the piles really differ in that bit, and the averages differ at the moment the chip handles it. If the guess is wrong, the piles are mixed, and the averages are almost the same. Do this for every guess and keep the guess with the largest difference.

The problem

The attacker sees mm pairs (pi,ℓi)(p_i, \ell_i). Here pip_i is a known input nibble and ℓi\ell_i is a trace of TT real samples. The device holds a fixed key nibble kk. The page uses the stated leakage model of the area:

ℓ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, HW\mathrm{HW} is the Hamming weight, ε>0\varepsilon > 0 is the leakage per bit, the noise values NijN_{ij} are independent with law N(0,σ2)N(0, \sigma^2), and the inputs pip_i are independent and uniform. The sample j∗j^\ast is not known to the attacker. The goal is to output kk. The cost model is the real RAM: each addition, division and comparison of two reals costs one unit.

This is a non-profiled attack: the attacker has no copy of the device to learn from, and needs only a guess of what leaks.

The algorithm

The selection function is bit bb of S(p⊕g)S(p \oplus g). The page uses b=1b = 1, for the reason given in the pitfalls.

  1. DPA(traces (p_1, l_1) .. (p_m, l_m), S-box S, bit b) ▷ each l_i has T samples
  2. 1best ← none, top ← -∞
  3. 2for each key guess g = 0 .. |S| - 1 do
  4. 3for each trace (p, l) do
  5. 4if bit b of S(p ⊕ g) is 1 then add l to group G1
  6. 5else add l to group G0
  7. 6if G1 or G0 is empty then score(g) ← -∞
  8. 7else Δ ← mean(G1) - mean(G0) ▷ the differential trace, T values
  9. 8score(g) ← max over j of Δ[j]
  10. 9if score(g) > top then
  11. 10best ← g, top ← score(g)
  12. 11return best and the list of scores

Lines L3 to L5 keep, for each group, a running sum of the traces and a count, so a group never holds the traces themselves. Line L7 divides each sum by its count, sample by sample. Line L8 takes the largest value of the differential trace. It does not take the absolute value: in this model a right guess gives a positive peak, and the sign is part of the signal. Line L9 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 table gives the value in the device and its bit 1.

p 0 1 2 3 4 5 6 7 8 9 A B C D E F
S(p ⊕ B) 8 F E 3 2 1 7 4 B 6 5 C D A 0 9
trace value (HW) 1 4 3 2 1 1 3 1 3 2 2 2 3 2 0 2
bit 1 0 1 1 1 1 0 1 0 1 1 0 0 0 1 0 0

Under the right guess g=Bg = \texttt{B}, group G1 holds the inputs 1, 2, 3, 4, 6, 8, 9 and D, with mean 20/8=2.520/8 = 2.5. Group G0 has mean 12/8=1.512/8 = 1.5. The score is 1.01.0. The other scores are:

guess 0 1 2 3 4 5 6 7 8 9 A B C D E F
score 0.75 0 0.25 -0.25 0 0.5 -1.0 -0.25 -0.5 0.25 0 1.0 -0.25 -1.25 0.75 0

The right guess wins by 0.250.25. The guesses 0 and E are its closest rivals. The guess D has the largest absolute value, 1.251.25, but with the wrong sign. With noise, the margin of 0.25ε0.25 \varepsilon is what the averages must resolve.

Correctness

The loop of line L2 keeps this loop invariant: after guess gg, the value top is the largest score of the guesses 0…g0 \ldots g, and best is the first guess with that score. So line L11 returns the first argmax of the scores. The attack is also consistent in the model: as mm grows, by the law of large numbers, the score of a guess gg tends to ε⋅Db(g⊕k)\varepsilon \cdot D_b(g \oplus k), where Db(δ)D_b(\delta) is the expected difference of HW(S(X))\mathrm{HW}(S(X)) between the two groups of bit bb of S(X⊕δ)S(X \oplus \delta). The samples with noise only tend to 0. For b=1b = 1 and the PRESENT S-box, D1(0)=1D_1(0) = 1 and D1(δ)≤0.75D_1(\delta) \le 0.75 for every δ≠0\delta \ne 0, so the right key wins with a probability that tends to 1. This is a theorem in the stated model. The proof gives both parts in full.

Proof: DPA 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 lines L6 to L8 give to the guess gg, and n=∣S∣n = |S| for the number of guesses.

Lemma 1 (the loop of line L2). After the iteration for guess gg, the value top is max⁡h≤gs(h)\max_{h \le g} s(h), and best is the smallest h≤gh \le g with $s(h) = $ top, or none if all these scores are −∞-\infty.

Proof. By induction on gg. Before the loop, line L1 sets best to none and top to −∞-\infty, which is the claim for the empty set of guesses. In the iteration for gg, line L9 compares s(g)s(g) with the old top, which by the induction hypothesis is max⁡h<gs(h)\max_{h < g} s(h). If s(g)s(g) is larger, line L10 makes gg the best guess and s(g)s(g) the top, and gg is then the only guess with the top score among 0…g0 \ldots g. If s(g)s(g) is not larger, nothing changes: the maximum is the same, and the smallest guess that reaches it is still the old best, because gg is larger than it. A score of −∞-\infty is never larger than top, so best stays none while all scores are −∞-\infty. □\square

So line L11 returns the first argmax of the scores, and the list of all nn scores.

The model. Let kk be the key. The inputs p1,p2,…p_1, p_2, \ldots are independent and uniform on {0,…,15}\{0, \ldots, 15\}. At the leaking sample j∗j^\ast, ℓi[j∗]=ε⋅HW(S(pi⊕k))+Nij∗\ell_i[j^\ast] = \varepsilon \cdot \mathrm{HW}(S(p_i \oplus k)) + N_{ij^\ast}, and at every other sample ℓi[j]=Nij\ell_i[j] = N_{ij}, with all NijN_{ij} independent of each other and of the inputs, with mean 0 and finite variance. For a fixed bit bb and δ∈{0,…,15}\delta \in \{0, \ldots, 15\} define, for XX uniform,

Db(δ)=E[HW(S(X))∣bit b of S(X⊕δ)=1]−E[HW(S(X))∣bit b of S(X⊕δ)=0].D_b(\delta) = E[\mathrm{HW}(S(X)) \mid \text{bit } b \text{ of } S(X \oplus \delta) = 1] - E[\mathrm{HW}(S(X)) \mid \text{bit } b \text{ of } S(X \oplus \delta) = 0].

Both conditions have probability 1/21/2, because SS is a bijection, so S(X⊕δ)S(X \oplus \delta) is uniform and each of its bits is 1 for exactly 8 of the 16 values of XX.

Lemma 2 (the limit of a score). Fix a guess gg and put δ=g⊕k\delta = g \oplus k. With probability 1, as m→∞m \to \infty, the differential trace of line L7 converges to εDb(δ)\varepsilon D_b(\delta) at the sample j∗j^\ast and to 0 at every other sample. So s(g)s(g) converges to εDb(δ)\varepsilon D_b(\delta) if T=1T = 1, and to max⁡(εDb(δ),0)\max(\varepsilon D_b(\delta), 0) if T≥2T \ge 2.

Proof. Let ci=1c_i = 1 if bit bb of S(pi⊕g)S(p_i \oplus g) is 1, and ci=0c_i = 0 if not. The pairs (ci,ℓi)(c_i, \ell_i) are independent and identically distributed. By the strong law of large numbers, with probability 1,

1m∑i≤mci→12,1m∑i≤mci ℓi[j]→E[c1ℓ1[j]].\frac{1}{m}\sum_{i \le m} c_i \to \tfrac12, \qquad \frac{1}{m}\sum_{i \le m} c_i \, \ell_i[j] \to E[c_1 \ell_1[j]].

In particular both groups are not empty for all large mm, so line L6 does not apply, and the mean of group G1 at sample jj converges to E[c1ℓ1[j]]/12=E[ℓ1[j]∣c1=1]E[c_1 \ell_1[j]] / \tfrac12 = E[\ell_1[j] \mid c_1 = 1]. The same holds for group G0 with 1−ci1 - c_i. For j≠j∗j \ne j^\ast, ℓ1[j]=N1j\ell_1[j] = N_{1j} is independent of c1c_1 and has mean 0, so both group means tend to 0 and so does their difference. For j=j∗j = j^\ast, the noise term again has conditional mean 0, and

E[ℓ1[j∗]∣c1=1]=ε E[HW(S(p1⊕k))∣bit b of S(p1⊕g)=1].E[\ell_1[j^\ast] \mid c_1 = 1] = \varepsilon \, E[\mathrm{HW}(S(p_1 \oplus k)) \mid \text{bit } b \text{ of } S(p_1 \oplus g) = 1].

Put X=p1⊕kX = p_1 \oplus k, which is uniform. Then p1⊕g=X⊕δp_1 \oplus g = X \oplus \delta, and the difference of the two group means tends to εDb(δ)\varepsilon D_b(\delta). Line L8 takes the maximum of finitely many values, and the maximum is continuous, so s(g)s(g) converges to the maximum of the limits. □\square

Lemma 3 (the right guess). Db(0)=1D_b(0) = 1 for every bit bb.

Proof. Put Y=S(X)Y = S(X). It is uniform on 4 bits, so its bits Y0,…,Y3Y_0, \ldots, Y_3 are independent and each is uniform on {0,1}\{0, 1\}. Then HW(Y)=∑cYc\mathrm{HW}(Y) = \sum_c Y_c. Under the condition Yb=1Y_b = 1 the term YbY_b is 1, and under Yb=0Y_b = 0 it is 0. Each other term YcY_c is independent of YbY_b, so its conditional mean is 1/21/2 under both conditions. The difference is 1+0=11 + 0 = 1. □\square

Lemma 4 (the wrong guesses on bit 1). 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) and b=1b = 1, the values D1(δ)D_1(\delta) for δ=0,1,…,15\delta = 0, 1, \ldots, 15 are

1, 0, 0.25, −0.5, 0, 0.75, −1.25, −0.25, −0.25, 0.25, 0, 0.75, −0.25, −1, 0.5, 0.1,\ 0,\ 0.25,\ -0.5,\ 0,\ 0.75,\ -1.25,\ -0.25,\ -0.25,\ 0.25,\ 0,\ 0.75,\ -0.25,\ -1,\ 0.5,\ 0 .

So D1(δ)≤0.75D_1(\delta) \le 0.75 for every δ≠0\delta \ne 0.

Proof. Each value is a finite sum over the 16 values of XX: list the 8 values of XX with bit 1 of S(X⊕δ)S(X \oplus \delta) equal to 1, average HW(S(X))\mathrm{HW}(S(X)) over them, and subtract the average over the other 8. For example, for δ=5\delta = 5 the first set is {3,6,7,8,10,12,13,15}\{3, 6, 7, 8, 10, 12, 13, 15\} with Hamming weights 3,2,3,2,4,1,3,13, 2, 3, 2, 4, 1, 3, 1 of S(X)S(X), mean 19/819/8, and the other set has mean 13/813/8, so D1(5)=6/8=0.75D_1(5) = 6/8 = 0.75. The test file computes all 16 values in the same way and compares them with the scores of the code on noiseless balanced traces, for every key. □\square

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

Proof. By Lemma 2 and Lemma 3, s(k)→εs(k) \to \varepsilon with probability 1 (for T≥2T \ge 2 the limit is max⁡(ε,0)=ε\max(\varepsilon, 0) = \varepsilon, since ε>0\varepsilon > 0). By Lemma 2 and Lemma 4, for each g≠kg \ne k, s(g)s(g) converges to a value of at most max⁡(0.75ε,0)=0.75ε\max(0.75\varepsilon, 0) = 0.75\varepsilon. There are finitely many guesses, so with probability 1 there is an MM such that, for all m≥Mm \ge M, s(k)>0.875ε>s(g)s(k) > 0.875\varepsilon > s(g) for every g≠kg \ne k. For these mm the key kk is the only guess with the top score, so by Lemma 1 line L11 returns kk. Convergence with probability 1 implies convergence in probability, so the probability of success tends to 1. ■\blacksquare

Remark. The proof uses the sign of the score. With the absolute value in line L8, the limit for g=k⊕6g = k \oplus 6 is 1.25ε>ε1.25\varepsilon > \varepsilon by Lemma 4, so the attack then fails with probability tending to 1. On bit 0 the value D0(δ)D_0(\delta) equals 1 for δ∈{7,9,E}\delta \in \{7, 9, \texttt{E}\} as well as for δ=0\delta = 0, so the theorem does not hold for b=0b = 0.

Complexity

For each of the gg guesses, lines L3 to L5 add each of the mm traces of TT samples to one running sum, which costs Θ(mT)\Theta(mT). Lines L7 and L8 cost Θ(T)\Theta(T). So the time is Θ(gmT)\Theta(g m T) in every case, and the extra space is Θ(T)\Theta(T) for the two sums and Θ(g)\Theta(g) for the list of scores. For a 4-bit S-box, g=16g = 16.

The number of traces that the attack needs depends on the noise. In the model, the variance of the leaking sample inside one group is ε2⋅3/4+σ2\varepsilon^2 \cdot 3/4 + \sigma^2, because the three other bits of S(p⊕k)S(p \oplus k) still vary. The difference of two group means of about m/2m/2 traces each has a standard deviation of about 2(0.75ε2+σ2)/m2\sqrt{(0.75\varepsilon^2 + \sigma^2)/m}, and it must resolve the margin 0.25ε0.25\varepsilon. So the number of traces grows as σ2/ε2\sigma^2/\varepsilon^2. 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 50 100 200 400 800 1600
success rate, σ = 0.5 0.69 0.79 0.90 0.975 1.0 1.0
success rate, σ = 1 0.555 0.705 0.76 0.925 0.985 1.0

The success rate is the probability that the best guess is the key, as defined by Standaert, Malkin and Yung (2009).

Properties

  • Non-profiled. It needs the inputs (or the outputs) and a selection function, but no model of the exact power of the device.
  • First order. It works on the mean of each group at one sample. If each intermediate value is split into random shares, as in Boolean masking, the mean of each group at each sample is the same for every key, and the attack fails. A higher-order attack that combines samples is then necessary.
  • One bit at a time. Only one bit of the intermediate value sets the groups. The other bits act as noise, so the attack uses the signal less well than correlation power analysis, which uses all bits.
  • Divide and conquer. Each key nibble or byte is found on its own, so the work is a sum and not a product over the parts of the key.
  • Deterministic. For fixed traces, the result does not depend on any random choice.

Variants and improvements

  • Multiple-bit DPA. Messerges, Dabbish and Sloan (2002) set the groups by several bits at a time, for example all bits one against all bits zero, and showed that this raises the signal to noise ratio.
  • Correlation instead of two groups. Correlation power analysis replaces the two groups by the Pearson correlation with the Hamming weight of the whole value. It uses all bits of the value, so in the Hamming weight model it gets a larger signal from the same traces.
  • Mutual information. Mutual information analysis needs no linear relation between the model and the power.
  • Profiling. With a copy of the device, a template attack learns the full distribution of the traces for each value. With exact templates its maximum likelihood decision has the highest success rate of all attacks on the same traces (a theorem).
  • Precomputed classes. Sum the traces for each of the 16 input values once, in Θ(mT)\Theta(mT) time. Then each guess combines 16 class sums, and the total time becomes Θ(mT+16gT)\Theta(mT + 16 g T).
  • Key rank instead of the top guess. Keep the full list of scores and give it to key rank estimation, which tells how much search remains after a partial success.

When to use it

DPA is the simplest attack that shows whether a device leaks in a way that depends on the data, and it is the standard first example in a course or in a design review. For a real evaluation, use CPA when the leakage is close to the Hamming weight, a template attack when a profiling device exists, and a leakage test when the question is only "does it leak", with no key recovery.

Pitfalls

  • Taking the absolute value. If line L8 is score(g) ← max over j of |Δ[j]|, then on bit 1 of the PRESENT S-box the guess k⊕6k \oplus 6 scores 1.251.25 and beats the right key, which scores 11. This happens with no noise at all, so more traces do not help. Keep line L8 signed, as above, when the sign of the leakage is known.
  • A bad selection bit. On bit 0, three wrong guesses tie with the right one at D0=1D_0 = 1, even with the signed score, so line L4 with b=0b = 0 cannot tell them apart. Compute the table Db(δ)D_b(\delta) of the S-box first and choose a bit where the right guess wins by a margin, as b=1b = 1 does here.
  • A bit of the S-box input. If line L4 tests bit bb of p⊕gp \oplus g instead of bit bb of S(p⊕g)S(p \oplus g), the split depends on only one bit of gg, and 8 guesses give the same groups. The selection function must pass through the nonlinear S-box.
  • An empty group. With few traces, a group can be empty for some guess, and line L7 then divides by zero. Line L6 gives that guess the score −∞-\infty.

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 above, the exact table DbD_b for every key and bit, the agreement with a direct difference of means on 500 random inputs, and the success rate with noise.

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.

differential_power_analysis.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/differential-power-analysis/. The authors are listed in prov/NV7DCA.jsonl.
"""Differential power analysis (difference of means) on a synthetic 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 differential_power_analysis(
    traces: list[Trace],
    sbox: tuple[int, ...] = PRESENT_SBOX,
    bit: int = 1,
    signed: bool = True,
) -> tuple[int, list[float]]:
    """Return (best guess, score of each guess) by Kocher's difference of means.

    For each key guess g, the traces are split by bit ``bit`` of
    sbox[p ^ g]. The differential trace is the mean of the 1 group minus
    the mean of the 0 group, sample by sample. The score of g is the
    largest value of the differential trace (its largest absolute value
    when ``signed`` is False). A guess with an empty group scores -inf.
    The first guess with the top score wins. If no guess has a finite
    score (for example with one trace), the best guess is -1.

    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(g + T) 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
        sum1 = [0.0] * t_len
        sum0 = [0.0] * t_len
        n1 = n0 = 0
        for p, row in traces:  # @line L3
            if (sbox[p ^ g] >> bit) & 1:  # @line L4
                n1 += 1
                for j in range(t_len):
                    sum1[j] += row[j]
            else:
                n0 += 1  # @line L5
                for j in range(t_len):
                    sum0[j] += row[j]
        if n1 == 0 or n0 == 0:  # @line L6
            score = -math.inf
        else:
            delta = [sum1[j] / n1 - sum0[j] / n0 for j in range(t_len)]  # @line L7
            score = max(delta) if signed else max(abs(x) for x in delta)  # @line L8
        scores.append(score)
        if score > top:  # @line L9
            best, top = g, score  # @line L10
    return best, scores  # @line L11
test_differential_power_analysis.py 132 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/differential-power-analysis/. The authors are listed in prov/NV7DCA.jsonl.

import math
import random
import statistics

import pytest
from differential_power_analysis import (
    PRESENT_SBOX,
    differential_power_analysis,
    hamming_weight,
    simulate_traces,
)


def oracle_scores(traces, sbox, bit, signed):
    """Difference of means written out directly with statistics.mean."""
    t_len = len(traces[0][1])
    out = []
    for g in range(len(sbox)):
        ones = [row for p, row in traces if (sbox[p ^ g] >> bit) & 1]
        zeros = [row for p, row in traces if not (sbox[p ^ g] >> bit) & 1]
        if not ones or not zeros:
            out.append(-math.inf)
            continue
        delta = [
            statistics.mean(r[j] for r in ones) - statistics.mean(r[j] for r in zeros)
            for j in range(t_len)
        ]
        out.append(max(delta) if signed else max(abs(x) for x in delta))
    return out


def expected_difference(delta, bit):
    """Exact E[HW(S(X)) | bit of S(X ^ delta) = 1] - E[... = 0] for uniform X."""
    s = PRESENT_SBOX
    one = [hamming_weight(s[x]) for x in range(16) if (s[x ^ delta] >> bit) & 1]
    zero = [hamming_weight(s[x]) for x in range(16) if not (s[x ^ delta] >> bit) & 1]
    return sum(one) / len(one) - sum(zero) / len(zero)


def balanced_traces(key, epsilon=1.0):
    """Each of the 16 inputs once, no noise, one sample."""
    return [(p, [epsilon * hamming_weight(PRESENT_SBOX[p ^ key])]) for p in range(16)]


def test_worked_example() -> None:
    # Key 0xB, one noiseless trace for each input: the page's example.
    best, scores = differential_power_analysis(balanced_traces(0xB))
    assert best == 0xB
    assert scores[0xB] == pytest.approx(1.0)
    assert scores[0xB ^ 0x5] == pytest.approx(0.75)
    assert scores[0xB ^ 0x6] == pytest.approx(-1.25)
    assert scores[0xB ^ 0xB] == pytest.approx(0.75)
    assert sorted(scores, reverse=True)[1] == pytest.approx(0.75)


def test_balanced_noiseless_equals_exact_expectation() -> None:
    for key in range(16):
        for bit in range(4):
            _, scores = differential_power_analysis(balanced_traces(key), bit=bit)
            for g in range(16):
                assert scores[g] == pytest.approx(expected_difference(g ^ key, bit))


def test_signed_bit1_recovers_every_key_without_noise() -> None:
    for key in range(16):
        best, _ = differential_power_analysis(balanced_traces(key), bit=1)
        assert best == key


def test_absolute_value_pitfall() -> None:
    # With |delta|, the guess key ^ 6 scores 1.25 > 1 on bit 1.
    for key in range(16):
        best, scores = differential_power_analysis(balanced_traces(key), bit=1, signed=False)
        assert best == key ^ 6
        assert scores[key ^ 6] == pytest.approx(1.25)
    # On bit 0, seven wrong guesses tie with the right one at |delta| = 1.
    _, scores = differential_power_analysis(balanced_traces(0), bit=0, signed=False)
    assert sum(1 for s in scores if abs(s - 1.0) < 1e-12) == 8


def test_edges() -> None:
    with pytest.raises(ValueError):
        differential_power_analysis([])
    best, scores = differential_power_analysis([(3, [0.5, 1.0])])
    assert best == -1 and all(s == -math.inf for s in scores)
    # Two traces: some guesses split them, some do not.
    tr = [(0, [1.0]), (1, [0.0])]
    assert differential_power_analysis(tr)[1] == oracle_scores(tr, PRESENT_SBOX, 1, True)


def test_against_oracle_random() -> None:
    rng = random.Random(20240501)
    for _ in range(500):
        m = rng.randrange(1, 12)
        t_len = rng.randrange(1, 4)
        bit = rng.randrange(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 = differential_power_analysis(traces, bit=bit, signed=signed)
        want = oracle_scores(traces, PRESENT_SBOX, bit, signed)
        for a, b in zip(scores, want):
            assert a == b or a == pytest.approx(b, abs=1e-9)
        finite = [i for i, s in enumerate(want) if s != -math.inf]
        if finite:
            top = max(want[i] for i in finite)
            assert want[best] == pytest.approx(top, abs=1e-9)
        else:
            assert best == -1


def test_success_rate_with_noise() -> None:
    rng = random.Random(7)
    hits = 0
    runs = 12
    for r in range(runs):
        key = rng.randrange(16)
        traces = simulate_traces(rng, key, m=800, sigma=0.5)
        best, _ = differential_power_analysis(traces)
        hits += best == key
    assert hits >= runs - 1


def test_too_few_traces_often_fail() -> None:
    rng = random.Random(11)
    hits = sum(
        differential_power_analysis(simulate_traces(rng, k, m=8, sigma=2.0))[0] == k
        for k in range(16)
    )
    assert hits <= 8

History

Kocher, Jaffe and Jun described simple and differential power analysis in a paper at CRYPTO 1999 and showed DES keys recovered from smart cards with a selection function on one S-box output bit. Messerges, Dabbish and Sloan studied the signal to noise ratio of the attack and its multiple-bit form (2002). Brier, Clavier and Olivier replaced the difference of means by a correlation with a leakage model (2004). The countermeasures of the same years, masking (Chari, Jutla, Rao and Rohatgi 1999; Goubin and Patarin 1999), were made to remove exactly the first-order difference that DPA measures.

References

  1. Paul Kocher, Joshua Jaffe and Benjamin Jun, Differential power analysis, CRYPTO 1999, LNCS 1666, pages 388 to 397, the sections on DPA (the selection function on one bit of a DES S-box output, and the difference of the two mean traces)
  2. Stefan Mangard, Elisabeth Oswald and Thomas Popp, Power Analysis Attacks, Springer, 2007, ISBN 978-0-387-30857-9, Chapter 6, Differential Power Analysis, pages 119 to 165 (the attack, the leakage models and the number of traces)
  3. Thomas S. Messerges, Ezzat A. Dabbish and Robert H. Sloan, Examining smart-card security under the threat of power analysis attacks, IEEE Transactions on Computers 51(5), 2002, the signal to noise model of DPA and the multiple-bit attack
  4. 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)
  5. 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