Algorithm Search⌘K

Algorithmadvanced

ISW private circuits

Also called Ishai-Sahai-Wagner construction.

Compiles any circuit into one secure against t probes by masking each wire with 2t+1 shares and a randomized AND gadget; later work showed t+1 shares suffice for the gadget.

Time
Θ(n^2) worst · average · best
Space
Θ(n^2) extra
Where
n = the number of shares of each wire; t = the number of probes
Origin
Yuval Ishai, Amit Sahai, David Wagner, 2003

The ISW construction of Ishai, Sahai and Wagner (2003) turns any Boolean circuit into a circuit that computes the same function but is secure against an attacker who can read the values of up to tt wires. Each bit is carried as nn random shares whose XOR is the bit, as in Boolean masking. XOR and NOT gates work on each share apart. The AND gate is replaced by a gadget that multiplies every share of one input with every share of the other and mixes in fresh random bits so that no small set of wires depends on the secret. The original theorem uses n=2t+1n = 2t + 1 shares; Rivain and Prouff (2010) proved that the AND gadget is secure against tt probes with t+1t + 1 shares. The model of the attacker is the probing model.

In plain words

Split each secret bit into several random bits that combine back into the secret, so that a spy who sees fewer than all of them learns nothing. Adding two split bits is easy: add the matching pieces. Multiplying is harder, because each piece of the result must depend on pieces of both inputs. The ISW method multiplies every piece of one input with every piece of the other, and adds a fresh random bit to each cross product before it is combined. The random bits cancel when the result is put back together, but they hide each partial result. The order of the additions is part of the method: adding the cross products before the random bit gives a wire that shows part of the secret.

The problem

A circuit has XOR, NOT and AND gates on bits. A tt-probing attacker chooses, before the run, a set of at most tt wires of the circuit and sees their values in one run (Ishai, Sahai and Wagner). A circuit with random input sharings and random bits is tt-probing secure if, for every set PP of at most tt wires, the joint distribution of the values on PP is the same for every value of the secret inputs.

The goal is a compiler that maps a circuit CC to a circuit C′C' that computes the shares of C(x)C(x) from shares of xx, and that is tt-probing secure. This page gives the AND gadget, which is the core of the compiler, and its check for t=1t = 1 and t=2t = 2. The cost model is the word RAM, with one step for each AND, XOR or random bit on single bits; the cost of a defense is counted in gates and random bits.

The algorithm

Inputs are a1,…,ana_1, \ldots, a_n with ⨁iai=a\bigoplus_i a_i = a and b1,…,bnb_1, \ldots, b_n with ⨁ibi=b\bigoplus_i b_i = b.

  1. ISW-AND(a_1 .. a_n, b_1 .. b_n)
  2. 1for i = 1 .. n do
  3. 2for j = i + 1 .. n do
  4. 3r_ij ← a fresh uniform random bit
  5. 4r_ji ← (r_ij ⊕ a_i b_j) ⊕ a_j b_i ▷ in this order
  6. 5for i = 1 .. n do
  7. 6c_i ← a_i b_i
  8. 7for each j ≠ i do c_i ← c_i ⊕ r_ij
  9. 8return c_1 .. c_n

The output shares satisfy ⨁ici=ab\bigoplus_i c_i = a b. A full circuit is compiled gate by gate: an XOR of two sharings is the XOR of the matching shares, a NOT flips the first share, and each AND is one call of ISW-AND with fresh random bits.

Line L4 is where the order matters. In the order shown, the first intermediate value is rij⊕aibjr_{ij} \oplus a_i b_j, which is hidden by the fresh bit rijr_{ij}. If the code computes aibj⊕ajbia_i b_j \oplus a_j b_i first, that wire is not hidden by any random bit, and with two shares it shows whether a=b=0a = b = 0 (see Pitfalls).

Example

Take n=2n = 2, a=1a = 1 with shares (1,0)(1, 0), b=1b = 1 with shares (0,1)(0, 1), and the random bit r12=1r_{12} = 1. Line L4 computes a1b2=1a_1 b_2 = 1, then r12⊕1=0r_{12} \oplus 1 = 0, then a2b1=0a_2 b_1 = 0, so r21=0r_{21} = 0. Lines L5 to L7 give c1=a1b1⊕r12=0⊕1=1c_1 = a_1 b_1 \oplus r_{12} = 0 \oplus 1 = 1 and c2=a2b2⊕r21=0⊕0=0c_2 = a_2 b_2 \oplus r_{21} = 0 \oplus 0 = 0. The output (1,0)(1, 0) is a sharing of 1=ab1 = a b.

The gadget for n=2n = 2 has 13 wires: the 4 input shares, the 5 wires of line L4, and the 4 wires of lines L6 and L7. With 2 shares for each input and 1 random bit, each secret (a,b)(a, b) has 8 runs of equal probability. Each of the 13 wires alone has the same distribution for the 4 secrets, so the gadget is 1-probing secure. With 2 probes it is not: 22 of the 78 pairs of wires depend on the secret, for example (a1,a2)(a_1, a_2), which gives aa.

For n=3n = 3 the gadget has 30 wires and each secret has 128 runs. All 30 single wires and all 435 pairs have a distribution independent of the secret, so the gadget is 2-probing secure with t+1=3t + 1 = 3 shares; 197 of the 4060 sets of 3 wires depend on the secret. These are exhaustive enumerations, made by the tests.

Correctness

Correct output. For each pair i<ji < j, lines L4 give rij⊕rji=aibj⊕ajbir_{ij} \oplus r_{ji} = a_i b_j \oplus a_j b_i. The XOR of all outputs is

⨁ici=⨁iaibi⊕⨁i<j(rij⊕rji)=⨁i,jaibj=(⨁iai)(⨁jbj)=ab.\bigoplus_i c_i = \bigoplus_i a_i b_i \oplus \bigoplus_{i < j} (r_{ij} \oplus r_{ji}) = \bigoplus_{i, j} a_i b_j = \Big(\bigoplus_i a_i\Big)\Big(\bigoplus_j b_j\Big) = a b .

Probing security. If the input sharings are uniform and independent and n≥2t+1n \ge 2t + 1, every set of at most tt wires of the gadget has a distribution that does not depend on (a,b)(a, b). The proof is a simulation: each probe names at most 2 share indices, so the probes depend on at most 2t<n2t < n shares of each input, and any n−1n - 1 shares of a uniform sharing are uniform and independent of the secret. The random bit of a pair with only one probed index hides the partial sums that use it. Both claims are theorems, proved in the proof. The stronger statement with n=t+1n = t + 1 shares is a theorem of Rivain and Prouff (2010); the tests verify it by exhaustive enumeration for t=1t = 1 and t=2t = 2. The theorem for a whole compiled circuit, where gadgets share wires, is the theorem of Ishai, Sahai and Wagner with 2t+12t + 1 shares and their refresh of the sharings; it is cited, not proved here.

Proof: The ISW AND gadget is correct, and secure against t probes with 2t + 1 sharesfull

All values are bits and ⊕\oplus is XOR. The inputs are a=(a1,…,an)a = (a_1, \ldots, a_n) and b=(b1,…,bn)b = (b_1, \ldots, b_n) with ⨁iai=a\bigoplus_i a_i = a and ⨁ibi=b\bigoplus_i b_i = b, where we use the same letter for the sharing and the secret when no confusion is possible. For each pair i<ji < j, line L3 draws a bit rijr_{ij}, and line L4 makes the wires wij1=aibjw^1_{ij} = a_i b_j, wij2=rij⊕aibjw^2_{ij} = r_{ij} \oplus a_i b_j, wij3=ajbiw^3_{ij} = a_j b_i and rji=wij2⊕wij3r_{ji} = w^2_{ij} \oplus w^3_{ij}. Lines L6 and L7 make the partial sums pi,0=aibip_{i,0} = a_i b_i and pi,qp_{i,q}, the XOR of aibia_i b_i and the first qq bits rijr_{ij} with j≠ij \ne i in increasing order of jj; the output is ci=pi,n−1c_i = p_{i, n-1}.

Theorem 1 (correct output). For every choice of the random bits, ⨁ici=ab\bigoplus_i c_i = a b.

Proof. Fix i<ji < j. By line L4, rji=rij⊕aibj⊕ajbir_{ji} = r_{ij} \oplus a_i b_j \oplus a_j b_i, so rij⊕rji=aibj⊕ajbir_{ij} \oplus r_{ji} = a_i b_j \oplus a_j b_i. Each rijr_{ij} with i≠ji \ne j appears in exactly one output, cic_i. So

⨁ici=⨁iaibi⊕⨁i<j(rij⊕rji)=⨁iaibi⊕⨁i<j(aibj⊕ajbi)=⨁i,jaibj.\bigoplus_i c_i = \bigoplus_i a_i b_i \oplus \bigoplus_{i < j} (r_{ij} \oplus r_{ji}) = \bigoplus_i a_i b_i \oplus \bigoplus_{i < j} (a_i b_j \oplus a_j b_i) = \bigoplus_{i, j} a_i b_j .

AND distributes over XOR on bits, so the last sum is (⨁iai)(⨁jbj)=ab(\bigoplus_i a_i)(\bigoplus_j b_j) = a b. □\square

Corollary (compiled circuits). If each AND gate of a circuit is replaced by the gadget, each XOR by the share-wise XOR and each NOT by a flip of the first share, then the output shares XOR to the output of the circuit, for every choice of random bits. Proof. By induction on the gates: share-wise XOR gives ⨁i(xi⊕yi)=x⊕y\bigoplus_i (x_i \oplus y_i) = x \oplus y, a flip of one share gives x⊕1x \oplus 1, and Theorem 1 covers AND. □\square

Lemma 2. Let x1,…,xnx_1, \ldots, x_n be a uniform sharing of a bit xx: the bits x1,…,xn−1x_1, \ldots, x_{n-1} are uniform and independent, and xn=x⊕x1⊕⋯⊕xn−1x_n = x \oplus x_1 \oplus \cdots \oplus x_{n-1}. For every set II of indices with ∣I∣≤n−1|I| \le n - 1, the bits (xi)i∈I(x_i)_{i \in I} are uniform and independent, whatever xx is.

Proof. If n∉In \notin I the claim is the definition. If n∈In \in I, pick an index u∉Iu \notin I, which exists because ∣I∣<n|I| < n. The map that sends (x1,…,xn−1)(x_1, \ldots, x_{n-1}) to the values (xi)i∈I(x_i)_{i \in I} together with (xi)i∉I,i≠u,i<n(x_i)_{i \notin I, i \ne u, i < n} is a bijection of {0,1}n−1\{0,1\}^{n-1}, because xnx_n determines xux_u given the other bits. A bijection maps the uniform distribution to the uniform distribution, so the values on II are uniform and independent. □\square

Theorem 3 (probing security). Let the sharings of aa and bb be uniform and independent, let the random bits be uniform and independent of them, and let n≥2t+1n \ge 2t + 1. Then for every set PP of at most tt wires of the gadget, the joint distribution of the values on PP is the same for all four values of (a,b)(a, b).

Proof. We build a set II of indices from PP and a simulator that computes the values on PP from (ai,bi)i∈I(a_i, b_i)_{i \in I} and fresh random bits only. For each wire in PP:

  • if it is aia_i, bib_i or a partial sum pi,qp_{i,q} (including cic_i), add ii to II;
  • if it is rijr_{ij}, wij1w^1_{ij}, wij2w^2_{ij}, wij3w^3_{ij} or rjir_{ji} for a pair i<ji < j, add ii and jj to II.

Then ∣I∣≤2t≤n−1|I| \le 2t \le n - 1. By Lemma 2, applied to each input, and by the independence of the two sharings, the values (ai,bi)i∈I(a_i, b_i)_{i \in I} are uniform and independent bits, with the same distribution for every (a,b)(a, b).

The simulator. For each pair i<ji < j with both i,j∈Ii, j \in I, it draws rijr_{ij} uniformly and computes wij1,wij2,wij3,rjiw^1_{ij}, w^2_{ij}, w^3_{ij}, r_{ji} from the definitions. For each pair with exactly one index in II, say e∈Ie \in I and f∉If \notin I, it draws a uniform bit ρef\rho_{ef} and uses it as refr_{ef}, the bit that appears in the partial sums of cec_e. Then it computes each probed pe,qp_{e,q} with e∈Ie \in I from aebea_e b_e and the bits refr_{ef} it has.

The simulation is exact. Fix the input shares. The probed wires use only the bits refr_{ef} with e∈Ie \in I: the wires of a pair with an index outside II are not probed, by the rule above, and pe,qp_{e,q} uses only bits refr_{ef}. For a pair with both indices in II, the simulator computes the real functions of the real distribution. For a pair {e,f}\{e, f\} with only e∈Ie \in I, the bit refr_{ef} is either the random bit of the pair, if e<fe < f, or that bit XOR afbe⊕aebfa_f b_e \oplus a_e b_f, if e>fe > f. In both cases it is uniform given everything else that is probed, because the random bit of the pair appears in no other probed wire: the only other wire that uses it is rfer_{fe} or the partial sums of cfc_f, and those are not probed because f∉If \notin I. Different pairs have independent random bits. So, given the input shares on II, the probed values in the real gadget and in the simulation have the same joint distribution.

The simulator never uses aa, bb or a share outside II. So the distribution of the values on PP is a function of the distribution of (ai,bi)i∈I(a_i, b_i)_{i \in I}, which does not depend on (a,b)(a, b). ■\blacksquare

Remarks. The bound n≥2t+1n \ge 2t + 1 comes from the second rule, which adds two indices for one probe. Rivain and Prouff (2010) refine the assignment of indices and prove the same conclusion with n≥t+1n \ge t + 1; this page does not reproduce that proof, and the tests check that conclusion by exhaustive enumeration for (n,t)=(2,1)(n, t) = (2, 1) and (3,2)(3, 2), which is a complete proof for those two cases. With n≥2t+1n \ge 2t + 1 the order of line L4 does not matter for this proof: the wire aibj⊕ajbia_i b_j \oplus a_j b_i of the wrong order would add ii and jj to II, like the other wires of the pair. The order matters for the tight bound n=t+1n = t + 1. There the wrong order leaks with tt probes, as the tests show for n=2n = 2 and n=3n = 3, and it is still secure with n=2t+1n = 2t + 1, as the tests show for n=3n = 3 and t=1t = 1.

Complexity

One AND gadget computes n2n^2 products aibja_i b_j, draws n(n−1)/2n(n - 1)/2 random bits, and does 2n(n−1)2n(n - 1) XORs: two for each pair in line L4 and n−1n - 1 for each output in line L7. So the time is Θ(n2)\Theta(n^2) and the extra space is Θ(n2)\Theta(n^2) for the bits rijr_{ij}; the bits can be used as soon as they are made, which brings the space down to Θ(n)\Theta(n). XOR and NOT gates cost Θ(n)\Theta(n). A circuit with ss AND gates and uu other gates costs Θ(sn2+un)\Theta(s n^2 + u n). With n=t+1n = t + 1 the cost of a gadget grows as t2t^2; with n=2t+1n = 2t + 1 it is about four times larger for large tt.

The tests count the gates for n=1n = 1 to 66 and find exactly n2n^2, n(n−1)/2n(n-1)/2 and 2n(n−1)2n(n-1).

Properties

  • Correct for every choice of random bits. The output is a sharing of aba b whatever the random bits are; the random bits only affect security.
  • Linear gates are free of randomness. XOR and NOT need no random bits, so the cost of a masked circuit is in its AND gates. This is why masked ciphers are designed or written with few non-linear operations.
  • Uniform outputs. For fixed input shares, the output cc is a uniform sharing of abab: each cic_i with i<ni < n contains the random bit rinr_{in}, which no other cjc_j with j<nj < n contains, so c1,…,cn−1c_1, \ldots, c_{n-1} are uniform and independent. The tests check this for n≤4n \le 4. A uniform output is still not enough for composition, because the probes inside two gadgets can be combined.
  • Order of operations. Security depends on the exact order of the XORs in line L4. A compiler that reorders XORs as if they were free can break it.
  • A model, not a device. The theorem is about wires in the probing model. A real device leaks noisy functions of many values at once, and its glitches can combine shares. The reduction of Duc, Dziembowski and Faust (2014) links the probing model to noisy leakage; for glitches, see threshold implementations.

Variants and improvements

  • t + 1 shares. Rivain and Prouff (2010) proved the gadget secure with n=t+1n = t + 1 and used it over the field of 256 elements to mask the AES S-box at any order. The product aibja_i b_j becomes a field product and ⊕\oplus the field addition.
  • Refresh. Between gadgets that use the same sharing twice, a refresh adds fresh random sharings of 0. Coron, Prouff, Rivain and Roche (2013) showed that with the simple refresh of Rivain and Prouff, the masked AES S-box is not secure at the claimed order, and proposed a refresh based on the ISW gadget.
  • Strong non-interference. Barthe and others (2016) defined strong non-interference, a property of a gadget that makes compositions tt-probing secure without a global proof. The ISW multiplication has it, and their tool places refresh gadgets automatically.
  • Noisy leakage. Prouff and Rivain (2013) proved security of masking in a model of noisy leakage of every value, and Duc, Dziembowski and Faust (2014) reduced that model to the probing model.
  • Hardware with glitches. In hardware, a glitch can make a gate briefly show a function of several shares. Threshold implementations use non-completeness to stay secure with glitches.

When to use it

Use the ISW gadget, or a variant, when a cipher must be protected against higher-order side-channel attacks with a proof. Choose n=t+1n = t + 1 for a software implementation with a refresh strategy proved by strong non-interference. Use first-order Boolean masking with table recomputation when t=1t = 1 is enough, and a threshold implementation in hardware. Check the result with a leakage test, because the proof holds in the model and not for every effect of the device.

Pitfalls

  • No random bits. The gadget ci=⨁jaibjc_i = \bigoplus_j a_i b_j is correct but ci=aibc_i = a_i b, so the last partial sum of c1c_1 shows bb whenever a1=1a_1 = 1. The tests find it with one probe, for 2 and 3 shares.
  • The wrong order in line L4. Computing rji=rij⊕(aibj⊕ajbi)r_{ji} = r_{ij} \oplus (a_i b_j \oplus a_j b_i) gives the wire a1b2⊕a2b1=a1b⊕ab1a_1 b_2 \oplus a_2 b_1 = a_1 b \oplus a b_1 for 2 shares. It is always 0 when a=b=0a = b = 0, and it is 1 with probability 1/21/2 for the other three secrets, so one probe leaks. For 3 shares the same mistake leaks with 2 probes, for example on a3a_3 and a1b2⊕a2b1a_1 b_2 \oplus a_2 b_1: the tests find 9 such pairs, and none for the correct order.
  • Reused random bits. If two gadgets use the same rijr_{ij}, a probe on one gadget and a probe on the other can cancel it.
  • Composition without refresh. A gadget that is tt-probing secure on its own can fail when its two inputs are not independent sharings, for example aa and a linear function of aa. Refresh one input, or use gadgets with strong non-interference.
  • Too few shares in the claim. With nn shares, the nn input shares of one input together give the secret, so no gadget is nn-probing secure. The tests find (a1,a2)(a_1, a_2) for n=2n = 2.

Implementations

The code of this page is an abstract model of a circuit. It works on bits in Python lists, draws the random bits from a seeded random.Random, and never reads a device, a file or a clock. The function isw_and_wires returns the output and every intermediate wire of the gadget. The tests enumerate all input sharings and all random bits for each of the 4 secrets and compare the distributions of every set of 1 probe for n=2n = 2 and of every set of at most 2 probes for n=3n = 3. They also show the leaks of the gadget without random bits and of the wrong order, count the gates, and compare a masked evaluation of 500 random circuits with the plain evaluation.

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.

isw_private_circuits.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/isw-private-circuits/. The authors are listed in prov/F6CSK5.jsonl.
"""The ISW private circuit construction over GF(2) (Ishai, Sahai, Wagner, CRYPTO 2003).

Each bit x of a circuit is carried as n shares x_1 .. x_n with
x_1 xor .. xor x_n = x. XOR and NOT gates work on each share. The AND gate
is the randomized ISW gadget. The module also lists every intermediate
wire of the gadget, so that a test can check the probing model by
exhaustive enumeration. This is a model of a circuit, not of a device:
the randomness comes from a seeded ``random.Random``.
"""

import random

Wire = tuple[str, int]


def share(rng: random.Random, x: int, n: int) -> list[int]:
    """Return n uniform bits whose XOR is the bit x. Cost: Theta(n)."""
    s = [rng.randrange(2) for _ in range(n - 1)]
    last = x
    for v in s:
        last ^= v
    return s + [last]


def unshare(s: list[int]) -> int:
    """Return the XOR of the shares. Cost: Theta(n)."""
    x = 0
    for v in s:
        x ^= v
    return x


def isw_and_wires(
    a: list[int], b: list[int], r: dict[tuple[int, int], int]
) -> tuple[list[int], list[Wire]]:
    """The ISW AND gadget with given random bits, and the list of its wires.

    Precondition: len(a) == len(b) == n >= 1, and r[(i, j)] is a bit for
    each 0 <= i < j < n. Returns the n output shares and every value the
    gadget computes, in order, with a name. The input shares are wires too.
    Cost: n^2 ANDs, n(n-1)/2 random bits and 2n(n-1) XORs.
    """
    n = len(a)
    wires: list[Wire] = [(f"a{i}", a[i]) for i in range(n)] + [(f"b{i}", b[i]) for i in range(n)]
    rr: dict[tuple[int, int], int] = {}
    for i in range(n):  # @line L1
        for j in range(i + 1, n):  # @line L2
            rr[(i, j)] = r[(i, j)]  # @line L3
            wires.append((f"r{i}{j}", rr[(i, j)]))
            t1 = a[i] & b[j]
            t2 = rr[(i, j)] ^ t1
            t3 = a[j] & b[i]
            rr[(j, i)] = t2 ^ t3  # @line L4
            wires += [(f"a{i}b{j}", t1), (f"r{i}{j}+a{i}b{j}", t2), (f"a{j}b{i}", t3), (f"r{j}{i}", rr[(j, i)])]
    c = []
    for i in range(n):  # @line L5
        acc = a[i] & b[i]  # @line L6
        wires.append((f"a{i}b{i}", acc))
        for j in range(n):  # @line L7
            if j != i:
                acc ^= rr[(i, j)]
                wires.append((f"c{i} after r{i}{j}", acc))
        c.append(acc)
    return c, wires  # @line L8


def isw_and(rng: random.Random, a: list[int], b: list[int]) -> list[int]:
    """Return n shares of AND(unshare(a), unshare(b)), with fresh random bits.

    Precondition: len(a) == len(b) == n >= 1. Cost: Theta(n^2).
    """
    n = len(a)
    if len(b) != n or n < 1:
        raise ValueError("the two sharings must have the same number n >= 1 of shares")
    r = {(i, j): rng.randrange(2) for i in range(n) for j in range(i + 1, n)}
    return isw_and_wires(a, b, r)[0]


def naive_and_wires(a: list[int], b: list[int]) -> tuple[list[int], list[Wire]]:
    """A wrong gadget with no randomness: c_i = XOR over j of a_i b_j.

    The output is a correct sharing of a AND b, but c_i = a_i AND b, which
    a single probe can read.
    """
    n = len(a)
    wires: list[Wire] = [(f"a{i}", a[i]) for i in range(n)] + [(f"b{i}", b[i]) for i in range(n)]
    c = []
    for i in range(n):
        acc = 0
        for j in range(n):
            acc ^= a[i] & b[j]
            wires.append((f"c{i} after a{i}b{j}", acc))
        c.append(acc)
    return c, wires


def wrong_order_wires(
    a: list[int], b: list[int], r: dict[tuple[int, int], int]
) -> tuple[list[int], list[Wire]]:
    """ISW with line L4 bracketed as r_ij xor (a_i b_j xor a_j b_i).

    The output is still correct, but the wire a_i b_j xor a_j b_i is not
    masked by r_ij.
    """
    n = len(a)
    wires: list[Wire] = [(f"a{i}", a[i]) for i in range(n)] + [(f"b{i}", b[i]) for i in range(n)]
    rr: dict[tuple[int, int], int] = {}
    for i in range(n):
        for j in range(i + 1, n):
            rr[(i, j)] = r[(i, j)]
            t = (a[i] & b[j]) ^ (a[j] & b[i])
            rr[(j, i)] = rr[(i, j)] ^ t
            wires += [(f"r{i}{j}", rr[(i, j)]), (f"a{i}b{j}+a{j}b{i}", t), (f"r{j}{i}", rr[(j, i)])]
    c = []
    for i in range(n):
        acc = a[i] & b[i]
        for j in range(n):
            if j != i:
                acc ^= rr[(i, j)]
                wires.append((f"c{i} after r{i}{j}", acc))
        c.append(acc)
    return c, wires


Gate = tuple[str, int, int]


def eval_plain(gates: list[Gate], inputs: list[int]) -> int:
    """Evaluate a circuit of ("xor"|"and", i, j) and ("not", i, 0) gates on bits.

    Wire k < len(inputs) is input k; gate g writes wire len(inputs) + g.
    The result is the last wire. Cost: Theta(len(inputs) + len(gates)).
    """
    w = list(inputs)
    for op, i, j in gates:
        if op == "xor":
            w.append(w[i] ^ w[j])
        elif op == "and":
            w.append(w[i] & w[j])
        else:
            w.append(w[i] ^ 1)
    return w[-1]


def eval_masked(rng: random.Random, gates: list[Gate], inputs: list[list[int]]) -> list[int]:
    """Evaluate the same circuit on sharings with n shares each.

    XOR works share by share, NOT flips the first share, and AND is the ISW
    gadget. Returns the n shares of the result.
    Cost: Theta(n) for each XOR or NOT gate and Theta(n^2) for each AND gate.
    """
    w = [list(s) for s in inputs]
    for op, i, j in gates:
        if op == "xor":
            w.append([x ^ y for x, y in zip(w[i], w[j])])
        elif op == "and":
            w.append(isw_and(rng, w[i], w[j]))
        else:
            w.append([w[i][0] ^ 1] + w[i][1:])
    return w[-1]
test_isw_private_circuits.py 145 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/isw-private-circuits/. The authors are listed in prov/F6CSK5.jsonl.

import itertools
import random
from collections import Counter

import pytest
from isw_private_circuits import (
    eval_masked,
    eval_plain,
    isw_and,
    isw_and_wires,
    naive_and_wires,
    share,
    unshare,
    wrong_order_wires,
)


def all_runs(gadget, n, randomized=True):
    """For each secret (a, b), the list of wire vectors over all shares and random bits."""
    pairs = [(i, j) for i in range(n) for j in range(i + 1, n)]
    runs = {}
    for a, b in itertools.product((0, 1), repeat=2):
        vecs = []
        for sa in itertools.product((0, 1), repeat=n - 1):
            for sb in itertools.product((0, 1), repeat=n - 1):
                xa = list(sa) + [a ^ (sum(sa) & 1)]
                xb = list(sb) + [b ^ (sum(sb) & 1)]
                for rb in itertools.product((0, 1), repeat=len(pairs) if randomized else 0):
                    if randomized:
                        c, w = gadget(xa, xb, dict(zip(pairs, rb)))
                    else:
                        c, w = gadget(xa, xb)
                    assert unshare(c) == a & b
                    vecs.append(w)
        runs[(a, b)] = vecs
    return runs


def leaking_sets(runs, t):
    """Every set of at most t wires whose joint distribution depends on (a, b)."""
    names = [name for name, _ in runs[(0, 0)][0]]
    out = []
    for size in range(1, t + 1):
        for probe in itertools.combinations(range(len(names)), size):
            dists = [Counter(tuple(w[p][1] for p in probe) for w in vecs) for vecs in runs.values()]
            if any(d != dists[0] for d in dists[1:]):
                out.append(tuple(names[p] for p in probe))
    return out


def test_worked_example() -> None:
    c, wires = isw_and_wires([1, 0], [0, 1], {(0, 1): 1})
    assert c == [1, 0]
    assert dict(wires)["r10"] == 0
    assert len(wires) == 13


def test_one_probe_two_shares_is_secure() -> None:
    assert leaking_sets(all_runs(isw_and_wires, 2), 1) == []


def test_two_probes_three_shares_is_secure() -> None:
    # t + 1 = 3 shares are enough against t = 2 probes (Rivain and Prouff 2010).
    runs = all_runs(isw_and_wires, 3)
    assert len(runs[(0, 0)][0]) == 30
    assert leaking_sets(runs, 2) == []


def test_t_probes_on_t_shares_leak() -> None:
    assert ("a0", "a1") in leaking_sets(all_runs(isw_and_wires, 2), 2)


def test_naive_gadget_leaks_with_one_probe() -> None:
    for n in (2, 3):
        leaks = leaking_sets(all_runs(naive_and_wires, n, randomized=False), 1)
        # The last partial sum of c_0 is a_0 AND b.
        assert (f"c0 after a0b{n - 1}",) in leaks


def test_wrong_order_leaks() -> None:
    assert ("a0b1+a1b0",) in leaking_sets(all_runs(wrong_order_wires, 2), 1)
    runs3 = all_runs(wrong_order_wires, 3)
    assert leaking_sets(runs3, 1) == []
    leaks = leaking_sets(runs3, 2)
    assert len(leaks) == 9 and ("a2", "a0b1+a1b0") in leaks
    runs = all_runs(wrong_order_wires, 2)
    k = [name for name, _ in runs[(0, 0)][0]].index("a0b1+a1b0")
    assert all(w[k][1] == 0 for w in runs[(0, 0)])
    assert sum(w[k][1] for w in runs[(1, 1)]) * 2 == len(runs[(1, 1)])


def test_output_is_a_uniform_sharing() -> None:
    for n in range(1, 5):
        pairs = [(i, j) for i in range(n) for j in range(i + 1, n)]
        rng = random.Random(n)
        a = [rng.randrange(2) for _ in range(n)]
        b = [rng.randrange(2) for _ in range(n)]
        outs = Counter()
        for rb in itertools.product((0, 1), repeat=len(pairs)):
            outs[tuple(isw_and_wires(a, b, dict(zip(pairs, rb)))[0])] += 1
        assert len(outs) == 2 ** (n - 1)
        assert len(set(outs.values())) == 1
        assert all(unshare(list(c)) == unshare(a) & unshare(b) for c in outs)


def test_cost_counts() -> None:
    for n in range(1, 7):
        a, b = [0] * n, [0] * n
        r = {(i, j): 0 for i in range(n) for j in range(i + 1, n)}
        _, wires = isw_and_wires(a, b, r)
        names = [name for name, _ in wires][2 * n:]
        ands = [x for x in names if x.startswith("a") and "+" not in x]
        rand = [x for x in names if x.startswith("r") and "+" not in x and int(x[1]) < int(x[2])]
        xors = [x for x in names if "+" in x or "after" in x or (x.startswith("r") and int(x[1]) > int(x[2]))]
        assert len(ands) == n * n
        assert len(rand) == n * (n - 1) // 2
        assert len(xors) == 2 * n * (n - 1)


def test_and_against_oracle() -> None:
    rng = random.Random(20240506)
    for _ in range(500):
        n = rng.randrange(1, 7)
        x, y = rng.randrange(2), rng.randrange(2)
        c = isw_and(rng, share(rng, x, n), share(rng, y, n))
        assert len(c) == n and unshare(c) == x & y
    with pytest.raises(ValueError):
        isw_and(rng, [0, 1], [1])


def test_masked_circuit_against_plain() -> None:
    rng = random.Random(7)
    for _ in range(500):
        k = rng.randrange(1, 5)
        gates = []
        for g in range(rng.randrange(1, 9)):
            op = rng.choice(["xor", "and", "not"])
            gates.append((op, rng.randrange(k + g), rng.randrange(k + g)))
        bits = [rng.randrange(2) for _ in range(k)]
        n = rng.randrange(1, 5)
        out = eval_masked(rng, gates, [share(rng, v, n) for v in bits])
        assert unshare(out) == eval_plain(gates, bits)

History

Ishai, Sahai and Wagner presented private circuits at CRYPTO 2003. They defined the tt-probing model, gave the AND gadget, and proved that 2t+12t + 1 shares give tt-probing security for any circuit. Masking itself was older: Chari, Jutla, Rao and Rohatgi (1999) and Goubin and Patarin (1999) proposed secret sharing of intermediate values against power analysis. Rivain and Prouff (2010) proved the gadget with t+1t + 1 shares and applied it to AES. Coron, Prouff, Rivain and Roche (2013) found a flaw in the composition with refresh, and Barthe and others (2016) gave strong non-interference as a rule for composition.

References

  1. Yuval Ishai, Amit Sahai and David Wagner, Private circuits: securing hardware against probing attacks, CRYPTO 2003, LNCS 2729, pages 463 to 481, the definition of the t-probing model, the AND gadget with its random bits, and the theorem for circuits with 2t + 1 shares
  2. Matthieu Rivain and Emmanuel Prouff, Provably secure higher-order masking of AES, CHES 2010, LNCS 6225, pages 413 to 427, the proof that the ISW multiplication is secure against t probes with t + 1 shares, and its use over the field of 256 elements for the AES S-box
  3. Jean-Sébastien Coron, Emmanuel Prouff, Matthieu Rivain and Thomas Roche, Higher-order side channel security and mask refreshing, FSE 2013, LNCS 8424, pages 410 to 424, the flaw in the composition of gadgets with the refresh of Rivain and Prouff, and the corrected refresh
  4. Gilles Barthe and others, Strong non-interference and type-directed higher-order masking, CCS 2016, pages 116 to 129, the definition of strong non-interference and the proof that the ISW multiplication has it, which makes gadgets compose
  5. Alexandre Duc, Stefan Dziembowski and Sebastian Faust, Unifying leakage models: from probing attacks to noisy leakage, EUROCRYPT 2014, LNCS 8441, pages 423 to 440, the reduction from security in the noisy leakage model to security in the probing model
  6. Emmanuel Prouff and Matthieu Rivain, Masking against side-channel attacks: a formal security proof, EUROCRYPT 2013, LNCS 7881, pages 142 to 159, the noisy leakage model and the security proof of masked computation in it

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