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
- Model
- Real RAM
- Evidence
- Proof sketchCode in 1 languages
- 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 pairs . Here is a known input nibble and is a trace of real samples. The device holds a fixed key nibble . The page uses the stated leakage model of the area:
where is the 4-bit S-box of PRESENT, is the Hamming weight, is the leakage per bit, the noise values are independent with law , and the inputs are independent and uniform. The sample is not known to the attacker. The goal is to output . 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 of . The page uses , for the reason given in the pitfalls.
DPA(traces (p_1, l_1) .. (p_m, l_m), S-box S, bit b) ▷ each l_i has T samples- 1
best ← none, top ← -∞ - 2
for each key guess g = 0 .. |S| - 1 do - 3
for each trace (p, l) do - 4
if bit b of S(p ⊕ g) is 1 then add l to group G1 - 5
else add l to group G0 - 6
if G1 or G0 is empty then score(g) ← -∞ - 7
else Δ ← mean(G1) - mean(G0) ▷ the differential trace, T values - 8
score(g) ← max over j of Δ[j] - 9
if score(g) > top then - 10
best ← g, top ← score(g) - 11
return 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 (hex), , 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 , group G1 holds the inputs 1, 2, 3, 4, 6, 8, 9 and D, with mean . Group G0 has mean . The score is . 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 . The guesses 0 and E are its closest rivals. The guess D has the largest absolute value, , but with the wrong sign. With noise, the margin of is what the averages must resolve.
Correctness
The loop of line L2 keeps this loop invariant: after guess , the value top is the largest score of the guesses , 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 grows, by the law of large numbers, the score of a guess tends to , where is the expected difference of between the two groups of bit of . The samples with noise only tend to 0. For and the PRESENT S-box, and for every , 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 for the score that lines L6 to L8 give to the guess , and for the number of guesses.
Lemma 1 (the loop of line L2). After the iteration for guess , the value top is , and best is the smallest with $s(h) = $ top, or none if all these scores are .
Proof. By induction on . Before the loop, line L1 sets best to none and top to , which is the claim for the empty set of guesses. In the iteration for , line L9 compares with the old top, which by the induction hypothesis is . If is larger, line L10 makes the best guess and the top, and is then the only guess with the top score among . If is not larger, nothing changes: the maximum is the same, and the smallest guess that reaches it is still the old best, because is larger than it. A score of is never larger than top, so best stays none while all scores are .
So line L11 returns the first argmax of the scores, and the list of all scores.
The model. Let be the key. The inputs are independent and uniform on . At the leaking sample , , and at every other sample , with all independent of each other and of the inputs, with mean 0 and finite variance. For a fixed bit and define, for uniform,
Both conditions have probability , because is a bijection, so is uniform and each of its bits is 1 for exactly 8 of the 16 values of .
Lemma 2 (the limit of a score). Fix a guess and put . With probability 1, as , the differential trace of line L7 converges to at the sample and to 0 at every other sample. So converges to if , and to if .
Proof. Let if bit of is 1, and if not. The pairs are independent and identically distributed. By the strong law of large numbers, with probability 1,
In particular both groups are not empty for all large , so line L6 does not apply, and the mean of group G1 at sample converges to . The same holds for group G0 with . For , is independent of and has mean 0, so both group means tend to 0 and so does their difference. For , the noise term again has conditional mean 0, and
Put , which is uniform. Then , and the difference of the two group means tends to . Line L8 takes the maximum of finitely many values, and the maximum is continuous, so converges to the maximum of the limits.
Lemma 3 (the right guess). for every bit .
Proof. Put . It is uniform on 4 bits, so its bits are independent and each is uniform on . Then . Under the condition the term is 1, and under it is 0. Each other term is independent of , so its conditional mean is under both conditions. The difference is .
Lemma 4 (the wrong guesses on bit 1). For the PRESENT S-box and , the values for are
So for every .
Proof. Each value is a finite sum over the 16 values of : list the 8 values of with bit 1 of equal to 1, average over them, and subtract the average over the other 8. For example, for the first set is with Hamming weights of , mean , and the other set has mean , so . 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.
Theorem (consistency). In the model, with and the PRESENT S-box, the probability that line L11 returns best tends to 1 as .
Proof. By Lemma 2 and Lemma 3, with probability 1 (for the limit is , since ). By Lemma 2 and Lemma 4, for each , converges to a value of at most . There are finitely many guesses, so with probability 1 there is an such that, for all , for every . For these the key is the only guess with the top score, so by Lemma 1 line L11 returns . Convergence with probability 1 implies convergence in probability, so the probability of success tends to 1.
Remark. The proof uses the sign of the score. With the absolute value in line L8, the limit for is by Lemma 4, so the attack then fails with probability tending to 1. On bit 0 the value equals 1 for as well as for , so the theorem does not hold for .
Complexity
For each of the guesses, lines L3 to L5 add each of the traces of samples to one running sum, which costs . Lines L7 and L8 cost . So the time is in every case, and the extra space is for the two sums and for the list of scores. For a 4-bit S-box, .
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 , because the three other bits of still vary. The difference of two group means of about traces each has a standard deviation of about , and it must resolve the margin . So the number of traces grows as . A measurement in the model, with 200 seeded runs for each cell, , 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 time. Then each guess combines 16 class sums, and the total time becomes .
- 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 scores and beats the right key, which scores . 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 , even with the signed score, so line L4 with cannot tell them apart. Compute the table of the S-box first and choose a bit where the right guess wins by a margin, as does here.
- A bit of the S-box input. If line L4 tests bit of instead of bit of , the split depends on only one bit of , 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 .
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 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.
# 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
- 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)
- 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)
- 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
- 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 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.
| 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 NV7DCA Edit this page History Report an error Markdown