Algorithm Search⌘K

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
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 dd independent parts. For part ii there are KK possible values with real scores si(0),…,si(K−1)s_i(0), \ldots, s_i(K - 1), where a higher score means a more likely value. The score of a full key x=(x1,…,xd)x = (x_1, \ldots, x_d) is S(x)=∑isi(xi)S(x) = \sum_i s_i(x_i); with log-likelihood scores this is the log-likelihood of the full key, because the parts are independent. The evaluator knows the true key k∗k^\ast. Its rank is

rank(k∗)=1+#{x:S(x)>S(k∗)},\mathrm{rank}(k^\ast) = 1 + \#\{x : S(x) > S(k^\ast)\},

the number of full keys that an optimal enumeration tries up to and including k∗k^\ast when ties are broken in its favour. The goal is two numbers lo≤rank(k∗)≤up\mathrm{lo} \le \mathrm{rank}(k^\ast) \le \mathrm{up} that are close, at a cost far below the KdK^d keys. The cost model is the real RAM, with exact integer counts.

The algorithm

  1. KEY-RANK-BOUNDS(scores s_1 .. s_d, true key k*, bin width w > 0)
  2. 1for i = 1 .. d do
  3. 2shift the scores of part i so that the smallest one is 0
  4. 3H_i[b] ← the number of values x with ⌊s_i(x) / w⌋ = b ▷ the histogram of part i
  5. 4b*_i ← ⌊s_i(k*_i) / w⌋ ▷ the bin of the true part
  6. 5H ← H_1
  7. 6for i = 2 .. d do H ← H ∗ H_i ▷ convolution
  8. 7lo ← 1 + Σ of H[b] for b ≥ b* + d, with b* = b*_1 + ... + b*_d
  9. 8up ← Σ of H[b] for b ≥ b* - d + 1
  10. 9return (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 (H∗Hi)[b]=∑jH[j] Hi[b−j](H \ast H_i)[b] = \sum_j H[j] \, H_i[b - j]. After it, H[b]H[b] is the number of full keys whose bins add up to bb. This is the dice count of "In plain words", and it is the same as the product of the polynomials ∑bHi[b]zb\sum_b H_i[b] z^b, as in polynomial multiplication.

Each bin covers a score interval of width ww, so the bin sum B(x)B(x) of a key fixes its total score to within dwd w: wB(x)≤S(x)<w(B(x)+d)w B(x) \le S(x) < w (B(x) + d). A key with B(x)≥b∗+dB(x) \ge b^\ast + d has a total score of at least w(b∗+d)w(b^\ast + d), which is larger than S(k∗)S(k^\ast), so it is better than the true key. A key that is better than the true key has w(B(x)+d)>S(x)>S(k∗)≥wb∗w(B(x) + d) > S(x) > S(k^\ast) \ge w b^\ast, so B(x)≥b∗−d+1B(x) \ge b^\ast - d + 1. Lines L7 and L8 count these two sets.

Example

Take d=2d = 2 parts with K=4K = 4 values each, already shifted:

s1=(0,3,5,9),s2=(0,2,7,8),s_1 = (0, 3, 5, 9), \qquad s_2 = (0, 2, 7, 8),

and the true key k∗=(1,2)k^\ast = (1, 2) with S(k∗)=3+7=10S(k^\ast) = 3 + 7 = 10. The keys with a larger total are (1,3)(1, 3) with 11, (2,2)(2, 2) with 12, (2,3)(2, 3) with 13, (3,1)(3, 1) with 11, (3,2)(3, 2) with 16 and (3,3)(3, 3) with 17, so the rank is 7.

With w=2w = 2, the bins of part 1 are 0,1,2,40, 1, 2, 4 and those of part 2 are 0,1,3,40, 1, 3, 4:

H1=(1,1,1,0,1),H2=(1,1,0,1,1),H1∗H2=(1,2,2,2,3,3,1,1,1).H_1 = (1, 1, 1, 0, 1), \qquad H_2 = (1, 1, 0, 1, 1), \qquad H_1 \ast H_2 = (1, 2, 2, 2, 3, 3, 1, 1, 1).

The true key is in bins 1 and 3, so b∗=4b^\ast = 4. Line L7 adds the bins from b∗+2=6b^\ast + 2 = 6 on: lo=1+(1+1+1)=4\mathrm{lo} = 1 + (1 + 1 + 1) = 4. Line L8 adds the bins from b∗−1=3b^\ast - 1 = 3 on: up=2+3+3+1+1+1=11\mathrm{up} = 2 + 3 + 3 + 1 + 1 + 1 = 11. So 4≤7≤114 \le 7 \le 11. The bounds for other widths are:

width w 4 2 1 1/2
(lo, up) (4, 16) (4, 11) (5, 8) (7, 7)

At w=1/2w = 1/2 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 wB(x)≤S(x)<w(B(x)+d)w B(x) \le S(x) < w(B(x) + d), which follows from wb≤s<w(b+1)w b \le s < w (b + 1) for b=⌊s/w⌋b = \lfloor s/w \rfloor in each part, and the fact that after line L6, H[b]H[b] is the exact number of full keys with bin sum bb, which follows by induction on the number of parts convolved. The true key itself is in the set of line L8, because b∗≥b∗−d+1b^\ast \ge b^\ast - d + 1, 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 (2d−1)w(2d - 1) w is smaller than every gap between distinct totals.

Proof: The histogram bounds always contain the rank of the true keyfull

Fix d≥1d \ge 1 parts, scores si(x)s_i(x) for xx in a finite nonempty set XiX_i, a true key k∗=(k1∗,…,kd∗)k^\ast = (k^\ast_1, \ldots, k^\ast_d) and a width w>0w > 0. Arithmetic is exact. Write S(x)=∑isi(xi)S(x) = \sum_i s_i(x_i) for a full key x∈X1×⋯×Xdx \in X_1 \times \cdots \times X_d and rank(k∗)=1+#{x:S(x)>S(k∗)}\mathrm{rank}(k^\ast) = 1 + \#\{x : S(x) > S(k^\ast)\}.

Lemma 1 (line L2). Shifting part ii by a constant cic_i does not change the rank.

Proof. Every full key gets the same added total c=∑icic = \sum_i c_i, so S(x)>S(k∗)S(x) > S(k^\ast) if and only if S(x)+c>S(k∗)+cS(x) + c > S(k^\ast) + c. □\square

From now on the scores are the shifted ones, so si(x)≥0s_i(x) \ge 0 and every bin index bi(x)=⌊si(x)/w⌋b_i(x) = \lfloor s_i(x)/w \rfloor is a non-negative integer. Write B(x)=∑ibi(xi)B(x) = \sum_i b_i(x_i) and b∗=B(k∗)b^\ast = B(k^\ast), which is the value of line L7.

Lemma 2 (the bin inequality). For every full key xx, wB(x)≤S(x)<w(B(x)+d)w B(x) \le S(x) < w (B(x) + d).

Proof. For a real tt and b=⌊t⌋b = \lfloor t \rfloor, we have b≤t<b+1b \le t < b + 1. With t=si(xi)/wt = s_i(x_i)/w and w>0w > 0 this gives wbi(xi)≤si(xi)<w(bi(xi)+1)w b_i(x_i) \le s_i(x_i) < w(b_i(x_i) + 1). Add the dd inequalities. □\square

Lemma 3 (lines L5 and L6). After the convolutions of line L6, H[b]=#{x:B(x)=b}H[b] = \#\{x : B(x) = b\} for every integer b≥0b \ge 0.

Proof. By line L3, Hi[b]=#{y∈Xi:bi(y)=b}H_i[b] = \#\{y \in X_i : b_i(y) = b\}. Let GjG_j be the value of HH after the parts 1,…,j1, \ldots, j, and claim Gj[b]=#{(x1,…,xj):∑i≤jbi(xi)=b}G_j[b] = \#\{(x_1, \ldots, x_j) : \sum_{i \le j} b_i(x_i) = b\}. For j=1j = 1 this is line L5. For the step, split the keys of the first j+1j + 1 parts by the bin cc of the last part. The number with total bb is ∑cGj[b−c] Hj+1[c]\sum_c G_j[b - c] \, H_{j+1}[c], which is the convolution (Gj∗Hj+1)[b](G_j \ast H_{j+1})[b]. The claim for j=dj = d is the lemma. □\square

Theorem. The values of lines L7 and L8 satisfy lo≤rank(k∗)≤up\mathrm{lo} \le \mathrm{rank}(k^\ast) \le \mathrm{up}.

Proof. By Lemma 3, lo=1+#{x:B(x)≥b∗+d}\mathrm{lo} = 1 + \#\{x : B(x) \ge b^\ast + d\} and up=#{x:B(x)≥b∗−d+1}\mathrm{up} = \#\{x : B(x) \ge b^\ast - d + 1\}.

Lower bound. Let B(x)≥b∗+dB(x) \ge b^\ast + d. By Lemma 2 for xx and for k∗k^\ast,

S(x)≥wB(x)≥w(b∗+d)>S(k∗).S(x) \ge w B(x) \ge w (b^\ast + d) > S(k^\ast).

So every key counted by lo, apart from the 1, is strictly better than k∗k^\ast, and lo≤rank(k∗)\mathrm{lo} \le \mathrm{rank}(k^\ast).

Upper bound. Let S(x)>S(k∗)S(x) > S(k^\ast). By Lemma 2,

w(B(x)+d)>S(x)>S(k∗)≥wb∗,w (B(x) + d) > S(x) > S(k^\ast) \ge w b^\ast,

so B(x)+d>b∗B(x) + d > b^\ast, and because both sides are integers, B(x)≥b∗−d+1B(x) \ge b^\ast - d + 1. So every strictly better key is in the set of up. The true key is in that set too, because d≥1d \ge 1 gives b∗≥b∗−d+1b^\ast \ge b^\ast - d + 1, and it is not strictly better than itself. The two sets are disjoint, so up≥#{x:S(x)>S(k∗)}+1=rank(k∗)\mathrm{up} \ge \#\{x : S(x) > S(k^\ast)\} + 1 = \mathrm{rank}(k^\ast). □\square

Proposition (fine bins). Let γ>0\gamma > 0 be the smallest gap between two distinct values of SS, and let (2d−1)w<γ(2d - 1) w < \gamma. Then lo=rank(k∗)\mathrm{lo} = \mathrm{rank}(k^\ast). If, in addition, no key other than k∗k^\ast has S(x)=S(k∗)S(x) = S(k^\ast), then up=rank(k∗)\mathrm{up} = \mathrm{rank}(k^\ast).

Proof. Take a key xx with b∗−d+1≤B(x)≤b∗+d−1b^\ast - d + 1 \le B(x) \le b^\ast + d - 1, the band between the two sets. By Lemma 2,

S(x)−S(k∗)<w(B(x)+d)−wb∗≤w(2d−1),S(x) - S(k^\ast) < w(B(x) + d) - w b^\ast \le w (2d - 1),
S(k∗)−S(x)<w(b∗+d)−wB(x)≤w(2d−1).S(k^\ast) - S(x) < w(b^\ast + d) - w B(x) \le w (2d - 1).

So ∣S(x)−S(k∗)∣<(2d−1)w<γ|S(x) - S(k^\ast)| < (2d - 1)w < \gamma, and so S(x)=S(k∗)S(x) = S(k^\ast). Hence no key in the band is strictly better than k∗k^\ast. Every strictly better key has B(x)≥b∗−d+1B(x) \ge b^\ast - d + 1 by the theorem, and it is not in the band, so B(x)≥b∗+dB(x) \ge b^\ast + d. With the lower bound of the theorem, the strictly better keys are exactly the keys with B(x)≥b∗+dB(x) \ge b^\ast + d, and lo=rank(k∗)\mathrm{lo} = \mathrm{rank}(k^\ast). If no other key ties with k∗k^\ast, the only key in the band is k∗k^\ast itself, so up=lo\mathrm{up} = \mathrm{lo}. ■\blacksquare

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 Θ(dK)\Theta(dK). After ii parts the histogram HH has at most iNiN bins, and the convolution with Hi+1H_{i+1} visits each bin of HH once for each nonzero bin of Hi+1H_{i+1}, of which there are at most min⁡(N,K)\min(N, K). The sum over ii is O(d2Nmin⁡(N,K))O(d^2 N \min(N, K)). Lines L7 and L8 cost O(dN)O(dN). The extra space is O(dN)O(dN) for HH and Θ(dK)\Theta(dK) for the bins.

The counts can be as large as KdK^d, which is 21282^{128} for AES-128, so they need exact big integers; Python integers are exact. With a fast Fourier transform each convolution costs O(dNlog⁡(dN))O(dN \log(dN)) arithmetic operations, but floating point values cannot hold such counts exactly.

The tightness depends on NN. A measurement on synthetic scores: a 64-bit key of d=16d = 16 parts of 4 bits, the Gaussian log-likelihood scores of mm traces for each part with Hamming weight leakage of the PRESENT S-box and σ=1\sigma = 1, seed 7. The width is the widest score range of a part divided by the number of bins. The table gives log⁡2lo\log_2 \mathrm{lo} and log⁡2up\log_2 \mathrm{up}:

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 1/N1/N; a heuristic reason is that the uncertain band of bin sums is always 2d−12d - 1 bins wide, and so its width in score units is proportional to ww.

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 (2d−1)w(2d - 1)w is smaller than the smallest gap between distinct totals, then lo=rank\mathrm{lo} = \mathrm{rank}, and up=rank\mathrm{up} = \mathrm{rank} 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 pi(x)p_i(x), the scores are si(x)=log⁡pi(x)s_i(x) = \log p_i(x). A score of −∞-\infty (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 K=65536K = 65536 exact sums, and bin the merged lists. This halves dd, and so the band of 2d−12d - 1 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 1+#{x:B(x)>b∗}1 + \#\{x : B(x) > b^\ast\} looks natural but is not a bound in either direction. In the example with w=4w = 4 it gives 9, which is more than the rank 7. The band of dd 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 21282^{128} 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 KdK^d and the lower bound is 1. Increase NN 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.

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

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

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