tfhe 1.7.0

TFHE-rs is a fully homomorphic encryption (FHE) library that implements Zama's variant of TFHE.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
//! TFHE implementation of the Kreyvium Algorithm

use crate::shortint::ciphertext::NoiseLevel;
use crate::shortint::{Ciphertext, ServerKey};
use crate::transciphering::ciphers::shift_register::ShiftRegister;
use crate::transciphering::{FheKeyStream, StreamCipherKind, Transcipherer};

use super::{
    collect_boxed_array, KreyviumBackwardRoundOutput, KreyviumIV, KreyviumRound,
    KreyviumRoundInput, KreyviumRoundOutput, KreyviumState,
};

/// A kreyvium key encrypted in LWE, one ciphertext per bit
pub struct KreyviumFheKey {
    cts: Box<[Ciphertext; 128]>,
}

impl KreyviumFheKey {
    pub(super) fn new(cts: Box<[Ciphertext; 128]>) -> Self {
        for (i, ct) in cts.iter().enumerate() {
            assert!(
                ct.degree.get() <= 1,
                "kreyvium key ciphertext {i} is not a single bit (degree {})",
                ct.degree.get(),
            );
            assert!(
                ct.noise_level() <= NoiseLevel::NOMINAL,
                "kreyvium key ciphertext {i} exceeds nominal noise (level {:?})",
                ct.noise_level(),
            );
        }
        Self { cts }
    }

    pub fn init_state(self, iv: KreyviumIV, sk: &ServerKey) -> KreyviumFheState {
        KreyviumFheState::new(self, iv, sk)
    }
}

pub type KreyviumFheState = KreyviumState<Ciphertext>;

impl KreyviumFheState {
    /// Constructor for `KreyviumFheState`: arguments are the secret key, the input vector,
    /// and a `ServerKey` reference. Outputs a state object already initialized
    /// (1152 steps have been run before returning).
    pub fn new(key: KreyviumFheKey, iv: impl Into<KreyviumIV>, sk: &ServerKey) -> Self {
        let mut key = key.cts;
        let mut iv = iv.into().expand().map(|b| b as u64);

        // Initialization of Kreyvium registers: a has the secret key, b the beginning of the IV,
        // c the end of the iv and padding 1s.
        let mut a_register: Box<[Ciphertext; 93]> =
            collect_boxed_array((0..93).map(|_| sk.create_trivial(0)))
                .expect("array and iter size match");
        let mut b_register: Box<[Ciphertext; 84]> =
            collect_boxed_array((0..84).map(|_| sk.create_trivial(0)))
                .expect("array and iter size match");
        let mut c_register: Box<[Ciphertext; 111]> =
            collect_boxed_array((0..111).map(|_| sk.create_trivial(0)))
                .expect("array and iter size match");

        for i in 0..93 {
            a_register[i].clone_from(&key[128 - 93 + i]);
        }
        for i in 0..84 {
            b_register[i] = sk.create_trivial(iv[128 - 84 + i]);
        }
        for i in 0..44 {
            c_register[111 - 44 + i] = sk.create_trivial(iv[i]);
        }
        for i in 0..66 {
            c_register[i + 1] = sk.create_trivial(1);
        }

        key.reverse();
        iv.reverse();
        let iv: Box<[Ciphertext; 128]> =
            collect_boxed_array(iv.iter().map(|&x| sk.create_trivial(x)))
                .expect("array and iter size match");

        let mut state = Self {
            a: ShiftRegister::new(a_register),
            b: ShiftRegister::new(b_register),
            c: ShiftRegister::new(c_register),
            k: ShiftRegister::new(key),
            iv: ShiftRegister::new(iv),
            counter: 0,
        };
        state.warmup(sk);
        state
    }
}

impl Transcipherer for KreyviumFheState {
    fn kind(&self) -> StreamCipherKind {
        StreamCipherKind::Kreyvium
    }

    fn next_keystream_bits(&mut self, sks: &ServerKey, n_bits: usize) -> FheKeyStream {
        FheKeyStream(self.next_n(sks, n_bits))
    }

    fn seek(&mut self, sks: &ServerKey, target_counter: u64) {
        self.seek_to(sks, target_counter)
    }

    fn current_counter(&self) -> u64 {
        self.counter
    }
}

type KreyviumFheRoundInput<'a> = KreyviumRoundInput<'a, Ciphertext>;

impl KreyviumRound for KreyviumFheRoundInput<'_> {
    type AuxData = ServerKey;
    type Bit = Ciphertext;

    /// Kreyvium round. Output keystream bit is a clean single-bit ciphertext
    /// (degree 1, value in {0, 1}).
    fn round(self, sk: &Self::AuxData) -> KreyviumRoundOutput<Self::Bit> {
        if sk.message_modulus.0 == 4 && sk.carry_modulus.0 == 4 {
            round_2_2(&self, sk)
        } else {
            round_naive(&self, sk)
        }
    }

    fn backward_round(self, sk: &Self::AuxData) -> KreyviumBackwardRoundOutput<Self::Bit> {
        if sk.message_modulus.0 == 4 && sk.carry_modulus.0 == 4 {
            backward_round_2_2(&self, sk)
        } else {
            backward_round_naive(&self, sk)
        }
    }
}

/// Kreyvium round optimized for MESSAGE_2_CARRY_2.
fn round_2_2(input: &KreyviumFheRoundInput<'_>, sk: &ServerKey) -> KreyviumRoundOutput<Ciphertext> {
    // Peak noise of the algo is 4 (new_b).
    // Regarding degree: `unchecked_bitand` in the next round is a bivariate PBS and requires
    // carry-empty operands, so register updates end with `message_extract`.
    // We don't need anything stricter (e.g. masking to a single bit): the
    // cipher reads only the low bit of each cell, so the high message bit is
    // free to hold whatever `message_extract` leaves there.
    assert!(
        sk.max_noise_level.get() >= 4,
        "round_2_2 needs max_noise_level >= 4, got {}",
        sk.max_noise_level.get(),
    );

    let KreyviumRoundInput {
        a: (a1, a2, a3, a4, a5),
        b: (b1, b2, b3, b4, b5),
        c: (c1, c2, c3, c4, c5),
        k,
        iv,
    } = input;

    for (l, r) in [(a3, a4), (b3, b4), (c3, c4)] {
        sk.is_functional_bivariate_pbs_possible(l.noise_degree(), r.noise_degree(), None)
            .expect("bivariate bitand precondition violated for kreyvium round_2_2");
    }

    let temp_a = sk.unchecked_add(a1, a2);
    let temp_b = sk.unchecked_add(b1, b2);
    let mut temp_c = sk.unchecked_add(c1, c2);
    sk.unchecked_add_assign(&mut temp_c, k);

    let ((a, b), (c, output)) = rayon::join(
        || {
            rayon::join(
                || {
                    let mut new_a = sk.unchecked_bitand(c3, c4);
                    sk.unchecked_add_assign(&mut new_a, a5);
                    sk.unchecked_add_assign(&mut new_a, &temp_c);
                    sk.message_extract_assign(&mut new_a);
                    new_a
                },
                || {
                    let mut new_b = sk.unchecked_bitand(a3, a4);
                    sk.unchecked_add_assign(&mut new_b, b5);
                    sk.unchecked_add_assign(&mut new_b, &temp_a);
                    sk.unchecked_add_assign(&mut new_b, iv);
                    sk.message_extract_assign(&mut new_b);
                    new_b
                },
            )
        },
        || {
            rayon::join(
                || {
                    let mut new_c = sk.unchecked_bitand(b3, b4);
                    sk.unchecked_add_assign(&mut new_c, c5);
                    sk.unchecked_add_assign(&mut new_c, &temp_b);
                    sk.message_extract_assign(&mut new_c);
                    new_c
                },
                || {
                    let lhs = sk.unchecked_add(&temp_a, &temp_b);
                    let xor_low_bit = sk.generate_lookup_table_bivariate(|x, y| (x ^ y) & 1);
                    sk.apply_lookup_table_bivariate(&lhs, &temp_c, &xor_low_bit)
                },
            )
        },
    );
    KreyviumRoundOutput { output, a, b, c }
}

/// Param-agnostic fallback round, assuming tight params
/// (e.g. 1_1: `max_noise_level = 3`, `MSG_MOD*CARRY_MOD = 4`)
/// Costs 3 extra PBS per round versus `round_2_2`.
fn round_naive(
    input: &KreyviumFheRoundInput<'_>,
    sk: &ServerKey,
) -> KreyviumRoundOutput<Ciphertext> {
    // Peak noise of the algo is 3 (temp_c and new_b).
    // Regarding degree: `unchecked_bitand` in the next round is a bivariate PBS and requires
    // carry-empty operands, so register updates end with `message_extract`.
    // We don't need anything stricter (e.g. masking to a single bit): the
    // cipher reads only the low bit of each cell, so the high message bit is
    // free to hold whatever `message_extract` leaves there.
    assert!(
        sk.max_noise_level.get() >= 3,
        "round_naive needs max_noise_level >= 3, got {}",
        sk.max_noise_level.get(),
    );

    let KreyviumRoundInput {
        a: (a1, a2, a3, a4, a5),
        b: (b1, b2, b3, b4, b5),
        c: (c1, c2, c3, c4, c5),
        k,
        iv,
    } = input;

    for (l, r) in [(a3, a4), (b3, b4), (c3, c4)] {
        sk.is_functional_bivariate_pbs_possible(l.noise_degree(), r.noise_degree(), None)
            .expect("bivariate bitand precondition violated for kreyvium round_naive");
    }

    let (temp_a, (temp_b, temp_c)) = rayon::join(
        || {
            let mut t = sk.unchecked_add(a1, a2);
            sk.message_extract_assign(&mut t);
            t
        },
        || {
            rayon::join(
                || {
                    let mut t = sk.unchecked_add(b1, b2);
                    sk.message_extract_assign(&mut t);
                    t
                },
                || {
                    let mut t = sk.unchecked_add(c1, c2);
                    sk.unchecked_add_assign(&mut t, k);
                    sk.message_extract_assign(&mut t);
                    t
                },
            )
        },
    );

    let ((a, b), (c, output)) = rayon::join(
        || {
            rayon::join(
                || {
                    let mut new_a = sk.unchecked_bitand(c3, c4);
                    sk.unchecked_add_assign(&mut new_a, a5);
                    sk.add_assign(&mut new_a, &temp_c);
                    new_a
                },
                || {
                    let mut new_b = sk.unchecked_bitand(a3, a4);
                    sk.unchecked_add_assign(&mut new_b, b5);
                    sk.unchecked_add_assign(&mut new_b, &temp_a);
                    sk.add_assign(&mut new_b, iv);
                    new_b
                },
            )
        },
        || {
            rayon::join(
                || {
                    let mut new_c = sk.unchecked_bitand(b3, b4);
                    sk.unchecked_add_assign(&mut new_c, c5);
                    sk.add_assign(&mut new_c, &temp_b);
                    new_c
                },
                || {
                    let lhs = sk.unchecked_add(&temp_a, &temp_b);
                    let xor_low_bit = sk.generate_lookup_table_bivariate(|x, y| (x ^ y) & 1);
                    sk.apply_lookup_table_bivariate(&lhs, &temp_c, &xor_low_bit)
                },
            )
        },
    );
    KreyviumRoundOutput { output, a, b, c }
}

/// Backward Kreyvium round optimized for MESSAGE_2_CARRY_2.
fn backward_round_2_2(
    input: &KreyviumFheRoundInput<'_>,
    sk: &ServerKey,
) -> KreyviumBackwardRoundOutput<Ciphertext> {
    assert!(
        sk.max_noise_level.get() >= 4,
        "backward_round_2_2 needs max_noise_level >= 4, got {}",
        sk.max_noise_level.get(),
    );

    let KreyviumRoundInput {
        a: (new_a, a1, a3, a4, a5),
        b: (new_b, b1, b3, b4, b5),
        c: (new_c, c1, c3, c4, c5),
        k,
        iv,
    } = input;

    for (l, r) in [(a3, a4), (b3, b4), (c3, c4)] {
        sk.is_functional_bivariate_pbs_possible(l.noise_degree(), r.noise_degree(), None)
            .expect("bivariate bitand precondition violated for kreyvium backward_round_2_2");
    }

    let (a, (b, c)) = rayon::join(
        || {
            // new_b = a1 ^ a2 ^ (a3 & a4) ^ iv ^ b5
            // so
            // a2 = (a3 & a4) ^ new_b ^ a1 ^ b5 ^ iv
            let mut a2 = sk.unchecked_bitand(a3, a4);
            sk.unchecked_add_assign(&mut a2, new_b);
            sk.unchecked_add_assign(&mut a2, a1);
            sk.unchecked_add_assign(&mut a2, b5);
            sk.unchecked_add_assign(&mut a2, iv);
            sk.message_extract_assign(&mut a2);
            a2
        },
        || {
            rayon::join(
                || {
                    // new_c = b1 ^ b2 ^ (b3 & b4) ^ c5
                    // so
                    // b2 = (b3 & b4) ^ new_c ^ b1 ^ c5
                    let mut b2 = sk.unchecked_bitand(b3, b4);
                    sk.unchecked_add_assign(&mut b2, new_c);
                    sk.unchecked_add_assign(&mut b2, b1);
                    sk.unchecked_add_assign(&mut b2, c5);
                    sk.message_extract_assign(&mut b2);
                    b2
                },
                || {
                    // new_a = c1 ^ c2 ^ (c3 & c3) ^ a5 ^ k
                    // so
                    // c2 = (c3 & c4) ^ new_a ^ c1 ^ a5 ^ k
                    let mut c2 = sk.unchecked_bitand(c3, c4);
                    sk.unchecked_add_assign(&mut c2, new_a);
                    sk.unchecked_add_assign(&mut c2, c1);
                    sk.unchecked_add_assign(&mut c2, a5);
                    sk.unchecked_add_assign(&mut c2, k);
                    sk.message_extract_assign(&mut c2);
                    c2
                },
            )
        },
    );

    KreyviumBackwardRoundOutput { a, b, c }
}

/// Param-agnostic fallback backward round, mirroring [`round_naive`]
fn backward_round_naive(
    input: &KreyviumFheRoundInput<'_>,
    sk: &ServerKey,
) -> KreyviumBackwardRoundOutput<Ciphertext> {
    assert!(
        sk.max_noise_level.get() >= 3,
        "backward_round_naive needs max_noise_level >= 3, got {}",
        sk.max_noise_level.get(),
    );

    let KreyviumRoundInput {
        a: (new_a, a1, a3, a4, a5),
        b: (new_b, b1, b3, b4, b5),
        c: (new_c, c1, c3, c4, c5),
        k,
        iv,
    } = input;

    for (l, r) in [(a3, a4), (b3, b4), (c3, c4)] {
        sk.is_functional_bivariate_pbs_possible(l.noise_degree(), r.noise_degree(), None)
            .expect("bivariate bitand precondition violated for kreyvium backward_round_naive");
    }

    let (a, (b, c)) = rayon::join(
        || {
            // new_b = a1 ^ a2 ^ (a3 & a4) ^ iv ^ b5
            // so
            // a2 = (a3 & a4) ^ new_b ^ a1 ^ b5 ^ iv
            let mut a2 = sk.unchecked_bitand(a3, a4);
            sk.unchecked_add_assign(&mut a2, new_b);
            sk.unchecked_add_assign(&mut a2, a1);
            sk.add_assign(&mut a2, b5);
            sk.add_assign(&mut a2, iv);
            sk.message_extract_assign(&mut a2);
            a2
        },
        || {
            rayon::join(
                || {
                    // new_c = b1 ^ b2 ^ (b3 & b4) ^ c5
                    // so
                    // b2 = (b3 & b4) ^ new_c ^ b1 ^ c5
                    let mut b2 = sk.unchecked_bitand(b3, b4);
                    sk.unchecked_add_assign(&mut b2, new_c);
                    sk.unchecked_add_assign(&mut b2, b1);
                    sk.add_assign(&mut b2, c5);
                    sk.message_extract_assign(&mut b2);
                    b2
                },
                || {
                    // new_a = c1 ^ c2 ^ (c3 & c4) ^ a5 ^ k
                    // so
                    // c2 = (c3 & c4) ^ new_a ^ c1 ^ a5 ^ k
                    let mut c2 = sk.unchecked_bitand(c3, c4);
                    sk.unchecked_add_assign(&mut c2, new_a);
                    sk.unchecked_add_assign(&mut c2, c1);
                    sk.add_assign(&mut c2, a5);
                    sk.add_assign(&mut c2, k);
                    sk.message_extract_assign(&mut c2);
                    c2
                },
            )
        },
    );

    KreyviumBackwardRoundOutput { a, b, c }
}