Algorithmresearch
Key rank estimation
Also called key enumeration rank.
Bounds the rank of the true key among all keys from per-byte scores of a side-channel attack, by histogram convolution, without enumerating keys.
- Time
- O(d K + d^2 N min(N, K)) worst · averageΘ(d K + d^2 N) best
- Space
- Θ(d N + d K) extra
- Where
- K = the number of guesses for each part; N = the number of bins in each histogram; d = the number of key parts
- Model
- Real RAM
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Cezary Glowacz, Vincent Grosso, Romain Poussier, Joachim Schüth, François Xavier Standaert, 2015
Key rank estimation tells an evaluator how far a side-channel attack got. A divide-and-conquer attack such as correlation power analysis or a template attack gives a list of scores for each small part of the key, for example 16 lists of 256 scores for AES-128. If the right value is first in every list, the attack is done. If not, the attacker must search the full keys in order of their total score, and the question is how many keys come before the right one. For a 128-bit key that number cannot be found by enumeration. The histogram method of Glowacz, Grosso, Poussier, Schüth and Standaert (2015) gives a lower and an upper bound on it with a few convolutions of small histograms, with no enumeration.
In plain words
An attack on a chip does not find the whole key at once. It looks at one small piece at a time and gives each possible value of the piece a score. To use the result, the attacker tries full keys from the best total score down. The evaluator, who knows the real key, wants to know how many tries that takes. Counting the keys one by one is impossible for a long key. Instead, round each score down to a coarse step and count, for each rounded total, how many keys reach it. This count is a sum over all pieces, and it can be built piece by piece, the same way you count the ways to roll a total with several dice. The rounding blurs each total a little, so you get two numbers that the true count must lie between.
The problem
The key has independent parts. For part there are possible values with real scores , where a higher score means a more likely value. The score of a full key is ; with log-likelihood scores this is the log-likelihood of the full key, because the parts are independent. The evaluator knows the true key . Its rank is
the number of full keys that an optimal enumeration tries up to and including when ties are broken in its favour. The goal is two numbers that are close, at a cost far below the keys. The cost model is the real RAM, with exact integer counts.
The algorithm
KEY-RANK-BOUNDS(scores s_1 .. s_d, true key k*, bin width w > 0)- 1
for i = 1 .. d do - 2
shift the scores of part i so that the smallest one is 0 - 3
H_i[b] ← the number of values x with ⌊s_i(x) / w⌋ = b ▷ the histogram of part i - 4
b*_i ← ⌊s_i(k*_i) / w⌋ ▷ the bin of the true part - 5
H ← H_1 - 6
for i = 2 .. d do H ← H ∗ H_i ▷ convolution - 7
lo ← 1 + Σ of H[b] for b ≥ b* + d, with b* = b*_1 + ... + b*_d - 8
up ← Σ of H[b] for b ≥ b* - d + 1 - 9
return (lo, up)
Line L2 adds a constant to each part. This adds the same constant to every full key, so the order of the keys and the rank do not change. Line L6 is the convolution . After it, is the number of full keys whose bins add up to . This is the dice count of "In plain words", and it is the same as the product of the polynomials , as in polynomial multiplication.
Each bin covers a score interval of width , so the bin sum of a key fixes its total score to within : . A key with has a total score of at least , which is larger than , so it is better than the true key. A key that is better than the true key has , so . Lines L7 and L8 count these two sets.
Example
Take parts with values each, already shifted:
and the true key with . The keys with a larger total are with 11, with 12, with 13, with 11, with 16 and with 17, so the rank is 7.
With , the bins of part 1 are and those of part 2 are :
The true key is in bins 1 and 3, so . Line L7 adds the bins from on: . Line L8 adds the bins from on: . So . The bounds for other widths are:
| width w | 4 | 2 | 1 | 1/2 |
|---|---|---|---|---|
| (lo, up) | (4, 16) | (4, 11) | (5, 8) | (7, 7) |
At the bounds meet in this example. "Properties" gives a width at which they always meet.
Correctness
The bounds hold for every input; this is a theorem, with no model of the scores. The two facts are the bin inequality , which follows from for in each part, and the fact that after line L6, is the exact number of full keys with bin sum , which follows by induction on the number of parts convolved. The true key itself is in the set of line L8, because , and it is not strictly better than itself; this is why line L8 has no "1 +". The proof gives the details, and also proves that the bounds are equal to the rank when is smaller than every gap between distinct totals.
Proof: The histogram bounds always contain the rank of the true keyfull
Fix parts, scores for in a finite nonempty set , a true key and a width . Arithmetic is exact. Write for a full key and .
Lemma 1 (line L2). Shifting part by a constant does not change the rank.
Proof. Every full key gets the same added total , so if and only if .
From now on the scores are the shifted ones, so and every bin index is a non-negative integer. Write and , which is the value of line L7.
Lemma 2 (the bin inequality). For every full key , .
Proof. For a real and , we have . With and this gives . Add the inequalities.
Lemma 3 (lines L5 and L6). After the convolutions of line L6, for every integer .
Proof. By line L3, . Let be the value of after the parts , and claim . For this is line L5. For the step, split the keys of the first parts by the bin of the last part. The number with total is , which is the convolution . The claim for is the lemma.
Theorem. The values of lines L7 and L8 satisfy .
Proof. By Lemma 3, and .
Lower bound. Let . By Lemma 2 for and for ,
So every key counted by lo, apart from the 1, is strictly better than , and .
Upper bound. Let . By Lemma 2,
so , and because both sides are integers, . So every strictly better key is in the set of up. The true key is in that set too, because gives , and it is not strictly better than itself. The two sets are disjoint, so .
Proposition (fine bins). Let be the smallest gap between two distinct values of , and let . Then . If, in addition, no key other than has , then .
Proof. Take a key with , the band between the two sets. By Lemma 2,
So , and so . Hence no key in the band is strictly better than . Every strictly better key has by the theorem, and it is not in the band, so . With the lower bound of the theorem, the strictly better keys are exactly the keys with , and . If no other key ties with , the only key in the band is itself, so .
With floating point scores, Lemma 2 can fail for a score that is rounded across a bin edge, and the theorem then holds only up to the keys in the two bins at that edge. The tests use exact fractions to check the theorem and floating point scores from a continuous model, for which such a rounding is very unlikely.
Complexity
Lines L1 to L4 cost . After parts the histogram has at most bins, and the convolution with visits each bin of once for each nonzero bin of , of which there are at most . The sum over is . Lines L7 and L8 cost . The extra space is for and for the bins.
The counts can be as large as , which is for AES-128, so they need exact big integers; Python integers are exact. With a fast Fourier transform each convolution costs arithmetic operations, but floating point values cannot hold such counts exactly.
The tightness depends on . A measurement on synthetic scores: a 64-bit key of parts of 4 bits, the Gaussian log-likelihood scores of traces for each part with Hamming weight leakage of the PRESENT S-box and , seed 7. The width is the widest score range of a part divided by the number of bins. The table gives and :
| traces for each part | 10 bins | 100 bins | 1000 bins | 5000 bins |
|---|---|---|---|---|
| m = 2 | 0 to 60.25 | 44.14 to 49.60 | 47.02 to 47.56 | 47.22 to 47.33 |
| m = 4 | 0 to 58.11 | 23.98 to 36.21 | 29.80 to 31.02 | 30.29 to 30.53 |
| m = 8 | 0 to 47.02 | 5.49 to 19.25 | 13.35 to 14.63 | 13.85 to 14.11 |
With 10 bins the bounds say almost nothing. With 1000 bins they are within 1.3 bits, and with 5000 bins within 0.3 bits. In this measurement the gap in bits shrinks roughly in proportion to ; a heuristic reason is that the uncertain band of bin sums is always bins wide, and so its width in score units is proportional to .
Properties
- Exact counting, approximate scores. The algorithm counts keys exactly; all the error comes from the rounding of the scores to bins. So the bounds are guaranteed, not statistical.
- Exact at fine resolution. If is smaller than the smallest gap between distinct totals, then , and when no other key ties with the true key. In practice the totals are too dense for this, and the bounds are used at a few thousand bins.
- Needs the true key. The bounds are about the position of a known key. This is an evaluation tool for a designer or a lab, not part of an attack.
- Independent parts. The method assumes that the score of a full key is the sum of the scores of its parts. For log-likelihood scores this is true when the parts leak independently.
- Ties. The rank counts only strictly better keys. A key with the same total is counted by line L8, so ties make the upper bound larger.
Variants and improvements
- Rank of a probability list. If an attack gives probabilities , the scores are . A score of (a probability of 0) must be replaced by a large finite negative value, or the part must be handled apart.
- Merge before the histograms. Combine two parts of 8 bits into one of 16 bits with exact sums, and bin the merged lists. This halves , and so the band of uncertain bins, at the cost of larger lists.
- The rank of a set of keys. The same histogram gives, for any threshold, the number of keys above it. This yields the whole curve of enumeration effort against success probability over many runs of an attack.
- Earlier methods. Veyrat-Charvillon, Gérard and Standaert (2013) gave the first rank estimation with bounds beyond the reach of enumeration. The histogram method is simpler and faster for the same tightness.
- Key enumeration. An enumeration algorithm lists the full keys in order of their total score. It is what an attacker runs when the rank is small enough; rank estimation tells whether it is.
When to use it
Use it in a security evaluation after a divide-and-conquer attack on a key that is too long to enumerate, to report how much computing power would be left to recover the key. Use brute-force search over the full keys only on toy keys, for example to test an implementation, as the tests of this page do with 4096 keys. Report the rank over many runs as a curve, or through statistics such as the success rate and the guessing entropy of Standaert, Malkin and Yung (2009).
Pitfalls
- One bin of slack. The count looks natural but is not a bound in either direction. In the example with it gives 9, which is more than the rank 7. The band of bins on each side is necessary.
- Floating point bins. With floating point scores, a score that lies exactly on a bin edge can be rounded into the wrong bin, and the bound can fail by the keys in that bin. Use exact rational arithmetic when a guarantee matters; with continuous scores this event has probability 0.
- Floating point counts. A histogram of keys in double precision loses the low bits of the counts. Keep the counts as integers, or use a logarithmic scale and accept an error.
- Too few bins. With 10 bins on 16 parts the upper bound is close to and the lower bound is 1. Increase until the bounds stop moving by more than the precision you need.
- Dependent parts. If the leakage of two parts is correlated, the sum of separate log-likelihoods is not the log-likelihood of the full key, and the rank is for the wrong order of keys.
Implementations
The code of this page is an abstract model on synthetic data. The function key_rank_bounds takes lists of scores; the scores in the tests are either random rational numbers or Gaussian log-likelihoods of a stated Hamming weight leakage model of the PRESENT S-box, drawn with a seeded random.Random by synthetic_scores. The code never reads a device, a file or a clock. The tests compare the bounds with the brute-force rank on 500 random inputs with exact fractions and up to 4096 keys, check the example, the exact bounds at fine bins, the pitfall of one bin of slack, and the 64-bit measurement above.
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/side-channel-key-rank-estimation/. The authors are listed in prov/BD5WM2.jsonl.
"""Key rank estimation by histogram convolution (Glowacz et al., FSE 2015).
The input is one list of scores for each independent part of the key, as
a side-channel attack gives them (for example log-likelihoods), and the
true key, which an evaluator knows. The output is a lower and an upper
bound on the rank of the true key in the full key space, with no
enumeration. The demo scores come from a stated synthetic model: Gaussian
log-likelihoods of Hamming weight leakage of the 4-bit PRESENT S-box
(Bogdanov et al., CHES 2007), with a seeded ``random.Random``.
"""
import itertools
import math
import random
PRESENT_SBOX: tuple[int, ...] = (
0xC, 0x5, 0x6, 0xB, 0x9, 0x0, 0xA, 0xD,
0x3, 0xE, 0xF, 0x8, 0x4, 0x7, 0x1, 0x2,
)
def hamming_weight(v: int) -> int:
"""Return the number of 1 bits of a non-negative integer."""
return bin(v).count("1")
def synthetic_scores(
rng: random.Random, key: list[int], m: int, sigma: float
) -> list[list[float]]:
"""Scores for each 4-bit part of the key from m synthetic traces each.
For part i, the traces are HW(S(p xor key[i])) + N(0, sigma^2) for
uniform inputs p, and the score of the guess x is the Gaussian log-
likelihood sum of -(l - HW(S(p xor x)))^2 / (2 sigma^2).
Cost: O(16 * m) for each part.
"""
out = []
for k in key:
obs = []
for _ in range(m):
p = rng.randrange(16)
obs.append((p, hamming_weight(PRESENT_SBOX[p ^ k]) + rng.gauss(0.0, sigma)))
out.append([
-sum((l - hamming_weight(PRESENT_SBOX[p ^ x])) ** 2 for p, l in obs) / (2 * sigma * sigma)
for x in range(16)
])
return out
def convolve(a: list[int], b: list[int]) -> list[int]:
"""Exact convolution of two integer histograms.
out[s] = sum of a[i] * b[s - i]. Python integers do not overflow, so the
counts are exact for any number of keys.
Cost: O(len(a) * z + len(b)), with z the number of nonzero bins of b.
"""
nonzero = [(j, y) for j, y in enumerate(b) if y]
out = [0] * (len(a) + len(b) - 1)
for i, x in enumerate(a):
if x:
for j, y in nonzero:
out[i + j] += x * y
return out
def key_rank_bounds(scores: list[list[float]], key: list[int], width: float) -> tuple[int, int]:
"""Return (lower, upper) with lower <= rank <= upper, by Glowacz et al.
The rank of the key is 1 plus the number of full keys whose total score
(the sum of the scores of their parts) is strictly larger than the
total score of the true key. Each part is shifted so that its smallest
score is 0 and cut into bins of the given width; the histograms are
convolved exactly, and the bounds follow from the bin of the true key.
The bounds are exact for exact arithmetic, for example with
fractions.Fraction scores and width; with floats a score that lies on a
bin edge can be rounded into the next bin.
Precondition: d >= 1 parts, each with at least one score, width > 0,
and key[i] in range(len(scores[i])).
Cost: O(d * K + d^2 * N * min(N, K)) time and O(d * N + d * K) extra
space, for d parts of K scores each and at most N bins in each
histogram.
"""
d = len(scores)
hists: list[list[int]] = []
star = 0
for i in range(d): # @line L1
lo = min(scores[i])
shifted = [s - lo for s in scores[i]] # @line L2
idx = [math.floor(s / width) for s in shifted]
hist = [0] * (max(idx) + 1)
for b in idx:
hist[b] += 1 # @line L3
hists.append(hist)
star += idx[key[i]] # @line L4
total = hists[0] # @line L5
for i in range(1, d): # @line L6
total = convolve(total, hists[i])
lower = 1 + sum(total[max(star + d, 0):]) # @line L7
upper = sum(total[max(star - d + 1, 0):]) # @line L8
return lower, upper # @line L9
def brute_force_rank(scores: list[list[float]], key: list[int]) -> int:
"""Rank by enumeration of all full keys. Cost: Theta(d * K^d)."""
target = sum(scores[i][key[i]] for i in range(len(scores)))
better = 0
for combo in itertools.product(*scores):
if sum(combo) > target:
better += 1
return 1 + better
test_side_channel_key_rank_estimation.py 122 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/side-channel-key-rank-estimation/. The authors are listed in prov/BD5WM2.jsonl.
import math
import random
from fractions import Fraction
from side_channel_key_rank_estimation import (
brute_force_rank,
convolve,
key_rank_bounds,
synthetic_scores,
)
A = [0, 3, 5, 9]
B = [0, 2, 7, 8]
def test_worked_example() -> None:
assert brute_force_rank([A, B], [1, 2]) == 7
assert key_rank_bounds([A, B], [1, 2], 4) == (4, 16)
assert key_rank_bounds([A, B], [1, 2], 2) == (4, 11)
assert key_rank_bounds([A, B], [1, 2], 1) == (5, 8)
assert key_rank_bounds([A, B], [1, 2], Fraction(1, 2)) == (7, 7)
def test_convolve_counts_sums() -> None:
rng = random.Random(11)
for _ in range(200):
a = [rng.randrange(4) for _ in range(rng.randrange(1, 7))]
b = [rng.randrange(4) for _ in range(rng.randrange(1, 7))]
want = [0] * (len(a) + len(b) - 1)
for i in range(len(a)):
for j in range(len(b)):
want[i + j] += a[i] * b[j]
assert convolve(a, b) == want
def test_bounds_against_enumeration_exact() -> None:
# Exact rational scores and widths, so no score is rounded across a bin edge.
rng = random.Random(20240505)
for _ in range(500):
d = rng.randrange(1, 4)
k = rng.randrange(1, 17)
scores = [[Fraction(rng.randrange(-40, 41), rng.randrange(1, 5)) for _ in range(k)] for _ in range(d)]
key = [rng.randrange(k) for _ in range(d)]
width = Fraction(rng.randrange(1, 40), rng.randrange(1, 8))
rank = brute_force_rank(scores, key)
lo, up = key_rank_bounds(scores, key, width)
assert 1 <= lo <= rank <= up <= k ** d
def test_bounds_against_enumeration_synthetic() -> None:
# Three 4-bit parts, 4096 keys, scores from the Gaussian leakage model.
rng = random.Random(3)
for _ in range(12):
key = [rng.randrange(16) for _ in range(3)]
scores = synthetic_scores(rng, key, rng.randrange(1, 4), 1.0)
rank = brute_force_rank(scores, key)
for bins in (5, 50, 500):
width = max(max(p) - min(p) for p in scores) / bins
lo, up = key_rank_bounds(scores, key, width)
assert lo <= rank <= up
def test_fine_bins_give_the_exact_rank() -> None:
# If 2 d w is below the smallest gap between distinct totals, lower = upper = rank.
rng = random.Random(5)
for _ in range(100):
d = rng.randrange(1, 4)
scores = [[Fraction(rng.randrange(1000)) for _ in range(6)] for _ in range(d)]
key = [rng.randrange(6) for _ in range(d)]
totals = sorted({sum(c) for c in _products(scores)})
if len(totals) != 6 ** d:
continue
gap = min(y - x for x, y in zip(totals, totals[1:])) if len(totals) > 1 else Fraction(1)
width = gap / (2 * d + 1)
rank = brute_force_rank(scores, key)
assert key_rank_bounds(scores, key, width) == (rank, rank)
def _products(scores):
out = [[]]
for part in scores:
out = [c + [s] for c in out for s in part]
return out
def test_one_bin_of_slack_is_not_a_bound() -> None:
# The naive count 1 + #{bin sum > bin of the key} overshoots the true rank here.
hists, star = [], 0
for part, k in zip([A, B], [1, 2]):
idx = [s // 4 for s in part]
h = [0] * (max(idx) + 1)
for b in idx:
h[b] += 1
hists.append(h)
star += idx[k]
total = convolve(hists[0], hists[1])
assert 1 + sum(total[star + 1:]) == 9 > brute_force_rank([A, B], [1, 2])
def test_64_bit_key_measurement() -> None:
rng = random.Random(7)
key = [rng.randrange(16) for _ in range(16)]
for m in (2, 3):
synthetic_scores(rng, key, m, 1.0)
scores = synthetic_scores(rng, key, 4, 1.0)
span = max(max(p) - min(p) for p in scores)
got = []
for bins in (10, 100, 1000):
lo, up = key_rank_bounds(scores, key, span / bins)
assert lo <= up <= 16 ** 16
got.append((round(math.log2(lo), 2), round(math.log2(up), 2)))
assert got == [(0.0, 58.11), (23.98, 36.21), (29.8, 31.02)]
def test_one_part() -> None:
scores = [[0.5, 2.5, 1.5, 4.0]]
assert brute_force_rank(scores, [2]) == 3
assert key_rank_bounds(scores, [2], 0.25) == (3, 3)
assert key_rank_bounds(scores, [3], 1.0) == (1, 1)
History
The rank of the key as a measure of side-channel security comes from the framework of Standaert, Malkin and Yung (2009), where the success rate and the guessing entropy are statistics of it. Veyrat-Charvillon, Gérard and Standaert (2013) showed how to bound the rank of a key that is far beyond enumeration, so that an evaluator can analyse attacks that cannot be mounted in full. Glowacz, Grosso, Poussier, Schüth and Standaert (2015) replaced that method by the histogram convolution on this page.
References
- Cezary Glowacz, Vincent Grosso, Romain Poussier, Joachim Schüth and François-Xavier Standaert, Simpler and more efficient rank estimation for side-channel security assessment, FSE 2015, LNCS 9054, pages 117 to 129, the histogram construction, the convolution of the histograms and the lower and upper bounds on the rank
- Nicolas Veyrat-Charvillon, Benoît Gérard and François-Xavier Standaert, Security evaluations beyond computing power, EUROCRYPT 2013, LNCS 7881, pages 126 to 141, the definition of the rank of the key beyond the reach of enumeration and the first rank estimation algorithm with bounds
- 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, which are statistics of the rank
- 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 synthetic scores of this page)
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 BD5WM2 Edit this page History Report an error Markdown