Techniquecore
Boolean masking
Also called masking countermeasure, secret sharing countermeasure.
Splits each secret intermediate value into random shares whose XOR is the value, so that no single leaking point depends on the secret.
Boolean masking is a countermeasure against side-channel attacks such as DPA. The implementation never stores or computes a secret intermediate value directly. It stores shares with , where all shares but one are fresh uniform random values, and it computes on the shares. Any shares are then uniform and independent of , as in the one-time pad and in additive secret sharing. Goubin and Patarin (1999) proposed the idea for DES as the duplication method. Chari, Jutla, Rao and Rohatgi (1999) showed that, when each share leaks with Gaussian noise, the number of traces that an attack needs grows exponentially in the number of shares. Linear operations are easy on shares; the nonlinear parts, such as an S-box, need a special gadget, and that is where most of the work and most of the errors are.
In plain words
A device leaks a little about each value it handles, for example its Hamming weight. If the value is the secret, the leak is about the secret. Masking replaces the secret by two or more random-looking pieces that combine to the secret by XOR. Each piece alone is a random number, so a leak of one piece tells nothing. The device must do all its work on the pieces and never put them back together before the end. An attacker who can see two pieces at the same time can still combine them, so the protection is only against attacks that look at fewer pieces than there are. Two pieces protect against first-order attacks; more pieces protect against higher-order attacks, at a higher cost.
When it applies
- Leakage of each value, not of the whole computation. Masking helps when the leak at each moment depends on a small number of intermediate values. An attacker who combines moments, or who has a leak that depends on shares at once, defeats masking with shares.
- Enough noise. The security against an attacker with many traces comes from the noise. With low noise, a higher-order attack needs few traces; the exponential growth of Chari and others assumes that each share is hidden in noise.
- A source of randomness. The masks must be fresh, uniform and secret for each run. A weak random number generator, or a mask that is reused across runs, removes the protection.
- Software and hardware. In software, one instruction usually handles one share, and the leak is close to the probing model. In hardware, glitches and transitions can combine shares in one wire, and the plain scheme needs the extra rules of a threshold implementation.
The template
The template masks one S-box lookup with two shares, for a public input and a key . It is first-order masking by table recomputation, the classic method for software.
MASKED-SBOX(p, k, S) ▷ S is a table of 2^w entries- 1
m_in, m_out ← SHARE: two fresh uniform w-bit masks - 2
a ← p ⊕ m_in ▷ mask before the key enters - 3
x' ← a ⊕ k ▷ LINEAR: x' ⊕ m_in = p ⊕ k - 4
for u = 0 .. 2^w - 1 do T[u] ← S(u ⊕ m_in) ⊕ m_out ▷ NONLINEAR - 5
y' ← T[x'] ▷ y' ⊕ m_out = S(p ⊕ k) - 6
return (y', m_out) ▷ REFRESH before the next use
The holes are:
- SHARE. How to split a value into shares. With shares, draw uniform values and set the last share to .
- LINEAR. A function that is linear over GF(2), such as XOR with a key, a bit permutation or the MixColumns step of the AES, is applied to each share separately, because . XOR with a constant goes into one share only.
- NONLINEAR. A nonlinear function does not split into shares. Line L4 builds a masked table with , at a cost of lookups. For higher orders, the S-box is written as a polynomial or a circuit of AND gates and each multiplication uses a gadget such as ISW.
- REFRESH. When one sharing is used twice, or before two sharings are combined, XOR fresh randomness into the shares so that no two wires share a mask.
Line L5 is correct because . Each wire alone is uniform or does not depend on : , and do not contain ; is uniform because is; each entry of is uniform because is, and it does not depend on ; and is uniform because is. So one probe gives nothing. A pair of wires can leak: gives , gives , and gives . The proof file shows this, and the tests check all 210 pairs of the 21 wires.
The cost of the template is time and space for each fresh pair of masks, against for an unmasked lookup.
Classic examples
The code of this page is a small abstract model of a masked computation. It uses the 4-bit PRESENT S-box, draws the masks from a seeded random.Random or takes them from the caller, and returns every intermediate value as a list of named wires. It never reads a device, a file or a clock. The tests check the claims below by exhaustive enumeration of the masks, for all 16 keys.
One masked S-box lookup. Take , , and . Then and . The table entry is . So , and . Over all 256 pairs of masks, each of the 21 wires has the same distribution for every key, and exactly the 3 pairs above out of 210 depend on the key.
First-order DPA fails, second-order DPA works. Against the unmasked lookup, a differential power analysis or a correlation power analysis on finds the key. With masking, the mean leak of each wire is the same for every key: for a uniform 4-bit and every . But the centred product of the leaks of and has the mean
which depends on the key. A second-order attack correlates this product with a guess, and the TVLA second-order test detects it.
Masking a linear layer with three shares. For a linear map on 4 bits and the key in three shares , the device computes and for each share, as in a substitution-permutation network. The tests enumerate all 256 pairs and show that every set of at most 2 of the 7 wires has the same distribution for every key, and that the 3 shares together give the key. This is second-order security for the linear part; the nonlinear part needs ISW or a similar gadget.
Hardware with glitches. In a circuit, a wire can take several values during one clock cycle before it settles, and a glitch can depend on two shares that enter the same gate. A threshold implementation avoids this with three or more shares and the rule that no function sees all shares of a value.
Variations
- Arithmetic masking. Share , which fits additions modulo in ciphers that use them and in some public key code. Conversions between Boolean and arithmetic sharings exist, and they are a common source of leaks.
- Multiplicative masking. Share a field element as with , so that inversion in GF() for the AES S-box is easy. The value stays 0 under every mask, so this masking leaks whether unless it is treated apart.
- Higher-order masking. Use shares for security against probes. Linear parts work share by share; multiplications use the ISW gadget with random bits and operations.
- Threshold implementations. Shares chosen so that each component function misses at least one share, which gives security with glitches in hardware (threshold implementation).
- Shuffling. Not a sharing, but often used with masking: the device does independent operations, such as the 16 S-box lookups of an AES round, in a random order, so that the leak of one value is spread over several moments.
Pitfalls
- The wrong order. If the device computes before it adds the mask, that wire is not masked and one probe gives the key. The tests show that the reordered gadget leaks at exactly that wire.
- Transitions. Many devices leak the Hamming distance between the old and the new value of a register. If a register holds and then , the leak is , at first order. Clear the register, or schedule the shares so that two shares of one value never follow each other in the same register.
- Reused masks. Software often recomputes one table for each encryption and uses it for all the S-box lookups. Then two outputs and have the same mask, and their XOR, or a transition between them, does not depend on the mask.
- The compiler. An optimizing compiler can simplify to , or keep two shares in one register. Check the machine code, not only the source.
- Weak masks. Masks from a biased or predictable generator, or masks that are not fresh in each run, break the argument that each share is uniform.
- Glitches in hardware. Two-share masking of a nonlinear function in hardware can leak at first order because of glitches. Use a threshold implementation or a gadget with registers that stop the glitches.
- Low noise. Masking makes an attack need more traces. The growth in the number of traces comes from the noise, so with little noise a second-order attack needs not many more traces than a first-order attack on the unmasked device.
Code
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/boolean-masking/. The authors are listed in prov/H7YXSN.jsonl.
"""First-order Boolean masking of a 4-bit S-box lookup by table recomputation.
The S-box is the 4-bit PRESENT S-box (Bogdanov et al., CHES 2007). Each
function returns, next to its result, the list of every intermediate
value it computes, so that a test can check the probing model by
exhaustive enumeration of the masks. This is a model of a computation, not
of a device: the masks come from a seeded ``random.Random`` or from the
caller.
"""
import random
PRESENT_SBOX: tuple[int, ...] = (
0xC, 0x5, 0x6, 0xB, 0x9, 0x0, 0xA, 0xD,
0x3, 0xE, 0xF, 0x8, 0x4, 0x7, 0x1, 0x2,
)
Wire = tuple[str, int]
def masked_sbox_wires(
p: int, k: int, m_in: int, m_out: int, sbox: tuple[int, ...] = PRESENT_SBOX
) -> tuple[tuple[int, int], list[Wire]]:
"""Compute the shares (S(p xor k) xor m_out, m_out) with masks m_in and m_out.
Precondition: sbox is a table of 2^w entries and p, k, m_in, m_out are
w-bit values. Returns the two output shares and every intermediate wire.
Cost: Theta(2^w) for the table and Theta(1) for the lookup.
"""
wires: list[Wire] = [("m_in", m_in), ("m_out", m_out)] # @line L1
a = p ^ m_in # @line L2
wires.append(("p+m_in", a))
x_masked = a ^ k # @line L3
wires.append(("x'", x_masked))
table = [0] * len(sbox)
for u in range(len(sbox)): # @line L4
table[u] = sbox[u ^ m_in] ^ m_out
wires.append((f"T[{u}]", table[u]))
y_masked = table[x_masked] # @line L5
wires.append(("y'", y_masked))
return (y_masked, m_out), wires # @line L6
def wrong_order_wires(
p: int, k: int, m_in: int, m_out: int, sbox: tuple[int, ...] = PRESENT_SBOX
) -> tuple[tuple[int, int], list[Wire]]:
"""The same computation with the key added before the mask (a pitfall).
The wire p xor k is not masked, so one probe gives the key.
"""
wires: list[Wire] = [("m_in", m_in), ("m_out", m_out)]
a = p ^ k
wires.append(("p+k", a))
x_masked = a ^ m_in
wires.append(("x'", x_masked))
table = [sbox[u ^ m_in] ^ m_out for u in range(len(sbox))]
wires += [(f"T[{u}]", table[u]) for u in range(len(sbox))]
y_masked = table[x_masked]
wires.append(("y'", y_masked))
return (y_masked, m_out), wires
def masked_sbox(rng: random.Random, p: int, k: int, sbox: tuple[int, ...] = PRESENT_SBOX) -> tuple[int, int]:
"""Masked lookup with fresh uniform masks. Returns (y', m_out) with y' xor m_out = S(p xor k)."""
m_in = rng.randrange(len(sbox))
m_out = rng.randrange(len(sbox))
return masked_sbox_wires(p, k, m_in, m_out, sbox)[0]
def gf2_linear(rows: tuple[int, ...], v: int) -> int:
"""Apply the GF(2)-linear map whose output bit i is the parity of v AND rows[i]."""
out = 0
for i, r in enumerate(rows):
out |= (bin(v & r).count("1") & 1) << i
return out
def three_share_linear_wires(
p: int, k_shares: tuple[int, int, int], rows: tuple[int, ...]
) -> tuple[list[int], list[Wire]]:
"""Second-order masking of y = L(p xor k) with k in three shares.
The public p is added to the first share only; the linear map L is
applied to each share. Returns the output shares and every wire.
Cost: Theta(1) for each share.
"""
k1, k2, k3 = k_shares
wires: list[Wire] = [("k1", k1), ("k2", k2), ("k3", k3)]
x = [k1 ^ p, k2, k3]
wires.append(("x1", x[0]))
y = [gf2_linear(rows, v) for v in x]
wires += [("y1", y[0]), ("y2", y[1]), ("y3", y[2])]
return y, wires
test_boolean_masking.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/boolean-masking/. The authors are listed in prov/H7YXSN.jsonl.
import itertools
import random
from collections import Counter
from boolean_masking import (
PRESENT_SBOX,
gf2_linear,
masked_sbox,
masked_sbox_wires,
three_share_linear_wires,
wrong_order_wires,
)
# An invertible GF(2)-linear map on 4 bits: output bit i is the parity of v AND ROWS[i].
ROWS = (0b0011, 0b0110, 0b1100, 0b1001 ^ 0b0001)
def runs_first_order(gadget, p):
"""For each key k, the wire vectors over all 256 pairs of masks."""
return {
k: [gadget(p, k, mi, mo)[1] for mi in range(16) for mo in range(16)]
for k in range(16)
}
def leaking(runs, t):
"""The sets of at most t wires whose joint distribution depends on the key."""
names = [n for n, _ in next(iter(runs.values()))[0]]
# cols[key][q] lists the values of wire q over all runs for that key.
cols = [[[w[q][1] for w in vecs] for q in range(len(names))] for vecs in runs.values()]
out = []
for size in range(1, t + 1):
for probe in itertools.combinations(range(len(names)), size):
first = Counter(zip(*(cols[0][q] for q in probe)))
if any(Counter(zip(*(c[q] for q in probe))) != first for c in cols[1:]):
out.append(tuple(names[q] for q in probe))
return out
def test_worked_example() -> None:
(y, mo), wires = masked_sbox_wires(0x3, 0xB, 0x5, 0x9)
w = dict(wires)
assert w["p+m_in"] == 0x6 and w["x'"] == 0xD
assert y == 0xA and mo == 0x9
assert y ^ mo == PRESENT_SBOX[0x3 ^ 0xB] == 0x3
def test_correct_for_all_inputs_and_masks() -> None:
for p, k, mi, mo in itertools.product(range(16), repeat=4):
(y, m), _ = masked_sbox_wires(p, k, mi, mo)
assert y ^ m == PRESENT_SBOX[p ^ k]
def test_random_oracle() -> None:
rng = random.Random(20240508)
for _ in range(500):
p, k = rng.randrange(16), rng.randrange(16)
y, m = masked_sbox(rng, p, k)
assert y ^ m == PRESENT_SBOX[p ^ k]
def test_first_order_secure() -> None:
# Every single wire, for three public inputs, over all keys and all 256 pairs of masks.
for p in (0x0, 0x3, 0xC):
assert leaking(runs_first_order(masked_sbox_wires, p), 1) == []
def test_second_order_leaks() -> None:
# All 210 pairs of the 21 wires: exactly three pairs depend on the key.
leaks = leaking(runs_first_order(masked_sbox_wires, 0x3), 2)
assert sorted(leaks) == sorted([("m_in", "x'"), ("p+m_in", "x'"), ("m_out", "y'")])
def test_wrong_order_leaks_with_one_probe() -> None:
assert leaking(runs_first_order(wrong_order_wires, 0x3), 1) == [("p+k",)]
def test_linear_map_is_invertible() -> None:
assert sorted(gf2_linear(ROWS, v) for v in range(16)) == list(range(16))
def test_three_shares_resist_two_probes() -> None:
for p in (0x0, 0x7):
runs = {}
for k in range(16):
vecs = []
for k1, k2 in itertools.product(range(16), repeat=2):
y, w = three_share_linear_wires(p, (k1, k2, k ^ k1 ^ k2), ROWS)
assert y[0] ^ y[1] ^ y[2] == gf2_linear(ROWS, p ^ k)
vecs.append(w)
runs[k] = vecs
assert leaking(runs, 2) == []
assert ("k1", "k2", "k3") in leaking(runs, 3)
def test_second_order_leakage_expectation() -> None:
hw = lambda v: bin(v).count("1") # noqa: E731
for x in range(16):
assert sum(hw(x ^ m) for m in range(16)) == 32
e = sum((hw(x ^ m) - 2) * (hw(m) - 2) for m in range(16)) / 16
assert e == 1 - hw(x) / 2
Exercises
- Show that for two shares and with a uniform , each share alone is uniform, whatever is.
- Show that with three shares made by line SHARE, any two shares are uniform and independent of .
- In the example, which pairs of the 21 wires give information about ? Explain why the pair does not, for every .
- Prove that for a uniform 4-bit . For which is the product blind?
- Explain why the AND of two bits and cannot be computed share by share as .
Proof: The masked S-box lookup is correct and secure against one probe, and the three-share linear map is secure against two probesfull
Let be a permutation of , let be public and secret, and let and be independent and uniform on . The wires of MASKED-SBOX are and (line L1), (L2), (L3), the table entries for every (L4) and (L5). A set of wires is secure if its joint distribution is the same for every .
Lemma 1. If is uniform on and independent of a random variable , then for every function , the value is uniform and independent of .
Proof. For each value of , the map is a bijection of , so given the value is uniform. The conditional law does not depend on , so it is also the law without the condition, and the two are independent.
Theorem 1 (correctness). Line L6 returns with for all values of the masks.
Proof. , so . Then .
Theorem 2 (one probe). Every single wire is secure.
Proof. The wires , and do not depend on . The entry is a function of and only, so it does not depend on either. By Lemma 1 with and , the wire is uniform for every . By Lemma 1 with and , the wire is uniform for every .
Proposition 3 (two probes). The pairs , and are not secure if is not constant on the key space, which holds for a permutation. The pairs and are secure for every .
Proof. , and ; each pair determines a value that takes different values for different keys, so the joint law depends on . For : write and . Then is a bijective image of . Since is a permutation and is uniform, is uniform and independent of ; by Lemma 1 the second component is uniform for every and independent of , and then by Lemma 1 again the first component is uniform and independent of the second. So the pair is uniform on for every . For : contains , which appears in no other wire of the pair, so by Lemma 1 the pair is , and is uniform for every by Theorem 2.
The tests check all 210 pairs of the 21 wires for the PRESENT S-box and and find exactly the three pairs above.
Proposition 4 (second-order leakage). For a uniform and every , and .
Proof. By Lemma 1, is uniform, and each of its 4 bits is 1 with probability . Write for the bits of . A bit of equal to 1 flips the bit of , so . The are independent with mean 0 and , so the expectation of the product of and is .
Lemma 5. Let and be independent and uniform on and . Then any two of are independent and uniform, for every .
Proof. For this is the assumption. For : with uniform and independent of , so by Lemma 1 is uniform and independent of . The pair is the same with and exchanged.
Theorem 6 (three shares, linear map). Let be a GF(2)-linear map. The wires , , , and satisfy , and every set of at most two wires is secure.
Proof. By linearity, . Each wire is a function of one share and the public : , and of , the wires and of , and and of . So a set of at most two wires is a function of at most two shares, and by Lemma 5 those shares have a law that does not depend on . A function of them also has a law that does not depend on .
The bound is tight: the three wires give . The code applies the same operations, and its tests enumerate all masks to confirm Theorems 1, 2 and 6 and Proposition 3 for the stated S-box and map.
References
- Suresh Chari, Charanjit S. Jutla, Josyula R. Rao and Pankaj Rohatgi, Towards sound approaches to counteract power-analysis attacks, CRYPTO 1999, LNCS 1666, pages 398 to 412, the model in which each share leaks with Gaussian noise, and the result that the number of traces for an attack grows exponentially in the number of shares
- Louis Goubin and Jacques Patarin, DES and differential power analysis, the duplication method, CHES 1999, LNCS 1717, pages 158 to 172, the duplication method, which splits each variable of DES into two shares and computes on the shares
- Stefan Mangard, Elisabeth Oswald and Thomas Popp, Power Analysis Attacks, Springer, 2007, ISBN 978-0-387-30857-9, Chapter 9, Masking, pages 223 to 244
- Yuval Ishai, Amit Sahai and David Wagner, Private circuits: securing hardware against probing attacks, CRYPTO 2003, LNCS 2729, pages 463 to 481, the t-probing model and the masking of every wire with several shares
- 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)
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 | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag H7YXSN Edit this page History Report an error Markdown