tfhe 1.6.1

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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
use crate::integer::ciphertext::compressed_ciphertext_list::*;
use crate::integer::ciphertext::{ReRandomizationContext, ReRandomizationKey};
use crate::integer::key_switching_key::{KeySwitchingKeyBuildHelper, KeySwitchingKeyMaterial};
use crate::integer::{
    gen_keys, BooleanBlock, CompactPrivateKey, CompactPublicKey, IntegerKeyKind, RadixCiphertext,
    SignedRadixCiphertext,
};
use crate::shortint::parameters::test_params::{
    TEST_COMP_PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128,
    TEST_PARAM_KEYSWITCH_PKE_TO_BIG_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128,
    TEST_PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128,
    TEST_PARAM_PKE_TO_BIG_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128_ZKV2,
};
use crate::shortint::parameters::{
    CompactPublicKeyEncryptionParameters, CompressionParameters, ReRandomizationParameters,
};
use crate::shortint::ShortintParameterSet;
use itertools::Itertools;
use rand::Rng;

const NB_TESTS: usize = 10;
const NUM_BLOCKS: usize = 32;

#[test]
fn test_ciphertext_re_randomization_after_compression_with_dedicated_cpk() {
    let params = TEST_PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
    let comp_params = TEST_COMP_PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
    let cpk_params = TEST_PARAM_PKE_TO_BIG_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128_ZKV2;
    let rerand_ksk_params = TEST_PARAM_KEYSWITCH_PKE_TO_BIG_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;

    let rerand_params =
        ReRandomizationParameters::LegacyDedicatedCPKWithKeySwitch { rerand_ksk_params };

    test_ciphertext_re_randomization_after_compression_impl(
        params.into(),
        comp_params,
        Some(cpk_params),
        rerand_params,
    );
}

#[test]
fn test_ciphertext_re_randomization_after_compression_with_derived_cpk() {
    let params = TEST_PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
    let comp_params = TEST_COMP_PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
    let rerand_params = ReRandomizationParameters::DerivedCPKWithoutKeySwitch;

    test_ciphertext_re_randomization_after_compression_impl(
        params.into(),
        comp_params,
        None,
        rerand_params,
    );
}

fn test_ciphertext_re_randomization_after_compression_impl(
    params: ShortintParameterSet,
    comp_params: CompressionParameters,
    cpk_params: Option<CompactPublicKeyEncryptionParameters>,
    rerand_params: ReRandomizationParameters,
) {
    let (cks, sks) = gen_keys::<ShortintParameterSet>(params, IntegerKeyKind::Radix);

    let private_compression_key = cks.new_compression_private_key(comp_params);

    let (compression_key, decompression_key) =
        cks.new_compression_decompression_keys(&private_compression_key);

    let cpk;
    let rerand_ksk: KeySwitchingKeyMaterial;
    let re_randomization_key = match (cpk_params, rerand_params) {
        (
            Some(cpk_params),
            ReRandomizationParameters::LegacyDedicatedCPKWithKeySwitch { rerand_ksk_params },
        ) => {
            let dedicated_compact_private_key = CompactPrivateKey::new(cpk_params);
            cpk = CompactPublicKey::new(&dedicated_compact_private_key);
            rerand_ksk = KeySwitchingKeyBuildHelper::new(
                (&dedicated_compact_private_key, None),
                (&cks, &sks),
                rerand_ksk_params,
            )
            .into();
            ReRandomizationKey::LegacyDedicatedCPK {
                cpk: &cpk,
                ksk: rerand_ksk.as_view(),
            }
        }
        // For this test we use the cks directly which is instantiated from the compute
        // params, we need the secret key to be the same otherwise we would have
        // inconsistencies in the encryptions being used
        (None, ReRandomizationParameters::DerivedCPKWithoutKeySwitch) => {
            let derived_compact_private_key: CompactPrivateKey<&[u64]> = (&cks).try_into().unwrap();
            cpk = CompactPublicKey::new(&derived_compact_private_key);
            ReRandomizationKey::DerivedCPKWithoutKeySwitch { cpk: &cpk }
        }
        _ => panic!("Inconsistent rerand test setup"),
    };

    let rerand_domain_separator = *b"TFHE_Rrd";
    let compact_public_encryption_domain_separator = *b"TFHE_Enc";
    let metadata = b"lol".as_slice();

    let mut rng = rand::thread_rng();

    let message_modulus: u128 = cks.parameters().message_modulus().0 as u128;

    // Unsigned
    let modulus = message_modulus.pow(NUM_BLOCKS as u32);
    for _ in 0..NB_TESTS {
        let message = rng.gen::<u128>() % modulus;

        let ct = cks.encrypt_radix(message, NUM_BLOCKS);

        let mut builder = CompressedCiphertextListBuilder::new();

        builder.push(ct);

        let compressed = builder.build(&compression_key);

        let decompressed: RadixCiphertext = compressed.get(0, &decompression_key).unwrap().unwrap();

        let mut re_randomizer_context = ReRandomizationContext::new(
            rerand_domain_separator,
            [metadata],
            compact_public_encryption_domain_separator,
        );

        re_randomizer_context.add_ciphertext(&decompressed);

        let mut seed_gen = re_randomizer_context.finalize();

        let mut re_randomized = decompressed.clone();
        re_randomized
            .re_randomize(re_randomization_key, seed_gen.next_seed().unwrap())
            .unwrap();

        assert_ne!(decompressed, re_randomized);

        let decrypted: u128 = cks.decrypt_radix(&re_randomized);
        assert_eq!(decrypted, message);
    }

    // Signed
    let modulus = message_modulus.pow((NUM_BLOCKS - 1) as u32) as i128;
    for _ in 0..NB_TESTS {
        let message = rng.gen::<i128>() % modulus;

        let ct = cks.encrypt_signed_radix(message, NUM_BLOCKS);

        let mut builder = CompressedCiphertextListBuilder::new();

        builder.push(ct);

        let compressed = builder.build(&compression_key);

        let decompressed: SignedRadixCiphertext =
            compressed.get(0, &decompression_key).unwrap().unwrap();

        let mut re_randomizer_context = ReRandomizationContext::new(
            rerand_domain_separator,
            [metadata],
            compact_public_encryption_domain_separator,
        );

        re_randomizer_context.add_ciphertext(&decompressed);

        let mut seed_gen = re_randomizer_context.finalize();

        let mut re_randomized = decompressed.clone();
        re_randomized
            .re_randomize(re_randomization_key, seed_gen.next_seed().unwrap())
            .unwrap();

        assert_ne!(decompressed, re_randomized);

        let decrypted: i128 = cks.decrypt_signed_radix(&re_randomized);
        assert_eq!(decrypted, message);
    }

    // Boolean
    for _ in 0..NB_TESTS {
        let messages = [false, true];

        let cts = messages
            .iter()
            .map(|message| cks.encrypt_bool(*message))
            .collect_vec();

        let mut builder = CompressedCiphertextListBuilder::new();

        builder.extend(cts.into_iter());

        let compressed = builder.build(&compression_key);

        for (i, message) in messages.iter().enumerate() {
            let decompressed: BooleanBlock =
                compressed.get(i, &decompression_key).unwrap().unwrap();

            let mut re_randomizer_context = ReRandomizationContext::new(
                rerand_domain_separator,
                [metadata],
                compact_public_encryption_domain_separator,
            );

            re_randomizer_context.add_ciphertext(&decompressed);

            let mut seed_gen = re_randomizer_context.finalize();

            let mut re_randomized = decompressed.clone();
            re_randomized
                .re_randomize(re_randomization_key, seed_gen.next_seed().unwrap())
                .unwrap();

            assert_ne!(decompressed, re_randomized);

            let decrypted = cks.decrypt_bool(&re_randomized);
            assert_eq!(decrypted, *message);
        }
    }
}

#[cfg(feature = "zk-pok")]
mod zk {
    use crate::core_crypto::prelude::LweCiphertextCount;
    use crate::integer::ciphertext::{ProvenCompactCiphertextList, ReRandomizationContext};
    use crate::integer::key_switching_key::KeySwitchingKey;
    use crate::integer::parameters::IntegerCompactCiphertextListExpansionMode;
    use crate::integer::{
        BooleanBlock, ClientKey, CompactPrivateKey, CompactPublicKey, RadixCiphertext, ServerKey,
        SignedRadixCiphertext,
    };
    use crate::shortint::parameters::test_params::{
        TEST_PARAM_KEYSWITCH_PKE_TO_BIG_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128,
        TEST_PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128,
        TEST_PARAM_PKE_TO_BIG_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128_ZKV2,
    };
    use crate::zk::{CompactPkeCrs, ZkComputeLoad};
    use rand::Rng;

    #[test]
    fn test_proven_compact_ciphertext_list_re_randomization() {
        let pke_params = TEST_PARAM_PKE_TO_BIG_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128_ZKV2;
        let ksk_params = TEST_PARAM_KEYSWITCH_PKE_TO_BIG_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;
        let fhe_params = TEST_PARAM_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128;

        let num_blocks = 4usize;
        let metadata = [b't', b'e', b's', b't'];
        let rerand_domain_separator = *b"TFHE_Rrd";
        let compact_public_encryption_domain_separator = *b"TFHE_Enc";

        let cks = ClientKey::new(fhe_params);
        let sks = ServerKey::new_radix_server_key(&cks);
        let compact_private_key = CompactPrivateKey::new(pke_params);
        let ksk = KeySwitchingKey::new((&compact_private_key, None), (&cks, &sks), ksk_params);
        let pk = CompactPublicKey::new(&compact_private_key);

        let crs = CompactPkeCrs::from_shortint_params(pke_params, LweCiphertextCount(512)).unwrap();

        let mut rng = rand::thread_rng();
        let message_modulus = pke_params.message_modulus.0 as u128;

        // Unsigned
        {
            let modulus = message_modulus.pow(num_blocks as u32);
            let message = rng.gen::<u128>() % modulus;

            let mut builder = ProvenCompactCiphertextList::builder(&pk);
            builder.push_with_num_blocks(message, num_blocks);

            let proven_ct = builder
                .build_with_proof_packed(&crs, &metadata, ZkComputeLoad::Proof)
                .unwrap();

            let mut re_rand_context = ReRandomizationContext::new(
                rerand_domain_separator,
                [metadata.as_slice()],
                compact_public_encryption_domain_separator,
            );

            re_rand_context.add_proven_ciphertext_list(&proven_ct);

            let mut seed_gen = re_rand_context.finalize();

            let mut re_randomized = proven_ct.clone();
            re_randomized
                .re_randomize(&pk, seed_gen.next_seed().unwrap())
                .unwrap();

            assert!(proven_ct != re_randomized);

            let expander = re_randomized
                .expand_without_verification(
                    IntegerCompactCiphertextListExpansionMode::CastAndUnpackIfNecessary(
                        ksk.as_view(),
                    ),
                )
                .unwrap();

            let expanded: RadixCiphertext = expander.get(0).unwrap().unwrap();
            let decrypted: u128 = cks.decrypt_radix(&expanded);
            assert_eq!(decrypted, message);
        }

        // Signed
        {
            let modulus = message_modulus.pow((num_blocks - 1) as u32) as i128;
            let message = rng.gen::<i128>() % modulus;

            let mut builder = ProvenCompactCiphertextList::builder(&pk);
            builder.push_with_num_blocks(message, num_blocks);

            let proven_ct = builder
                .build_with_proof_packed(&crs, &metadata, ZkComputeLoad::Proof)
                .unwrap();

            let mut re_rand_context = ReRandomizationContext::new(
                rerand_domain_separator,
                [metadata.as_slice()],
                compact_public_encryption_domain_separator,
            );

            re_rand_context.add_proven_ciphertext_list(&proven_ct);

            let mut seed_gen = re_rand_context.finalize();

            let mut re_randomized = proven_ct.clone();
            re_randomized
                .re_randomize(&pk, seed_gen.next_seed().unwrap())
                .unwrap();

            assert!(proven_ct != re_randomized);

            let expander = re_randomized
                .expand_without_verification(
                    IntegerCompactCiphertextListExpansionMode::CastAndUnpackIfNecessary(
                        ksk.as_view(),
                    ),
                )
                .unwrap();

            let expanded: SignedRadixCiphertext = expander.get(0).unwrap().unwrap();
            let decrypted: i128 = cks.decrypt_signed_radix(&expanded);
            assert_eq!(decrypted, message);
        }

        // Boolean
        {
            for message in [false, true] {
                let mut builder = ProvenCompactCiphertextList::builder(&pk);
                builder.push(message);

                let proven_ct = builder
                    .build_with_proof_packed(&crs, &metadata, ZkComputeLoad::Proof)
                    .unwrap();

                let mut re_rand_context = ReRandomizationContext::new(
                    rerand_domain_separator,
                    [metadata.as_slice()],
                    compact_public_encryption_domain_separator,
                );

                re_rand_context.add_proven_ciphertext_list(&proven_ct);

                let mut seed_gen = re_rand_context.finalize();

                let mut re_randomized = proven_ct.clone();
                re_randomized
                    .re_randomize(&pk, seed_gen.next_seed().unwrap())
                    .unwrap();

                assert!(proven_ct != re_randomized);

                let expander = re_randomized
                    .expand_without_verification(
                        IntegerCompactCiphertextListExpansionMode::CastAndUnpackIfNecessary(
                            ksk.as_view(),
                        ),
                    )
                    .unwrap();

                let expanded: BooleanBlock = expander.get(0).unwrap().unwrap();
                let decrypted = cks.decrypt_bool(&expanded);
                assert_eq!(decrypted, message);
            }
        }
    }

    #[cfg(feature = "gpu")]
    #[test]
    fn test_proven_compact_ciphertext_list_re_rand_cpu_gpu_compatibility() {
        use crate::core_crypto::gpu::CudaStreams;
        use crate::integer::gpu::zk::CudaProvenCompactCiphertextList;
        use crate::shortint::parameters::test_params::TEST_PARAM_PKE_TO_SMALL_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128_ZKV2;

        let pke_params = TEST_PARAM_PKE_TO_SMALL_MESSAGE_2_CARRY_2_KS_PBS_TUNIFORM_2M128_ZKV2;

        let compact_private_key = CompactPrivateKey::new(pke_params);
        let pk = CompactPublicKey::new(&compact_private_key);

        let compact_public_encryption_domain_separator = *b"TFHE_Enc";
        let rerand_domain_separator = *b"TFHE_Rrd";

        // Intentionally low so that we test when multiple lists and proofs are needed
        let crs = CompactPkeCrs::from_shortint_params(pke_params, LweCiphertextCount(8)).unwrap();
        let metadata = [b'r', b'e', b'r', b'a', b'n', b'd'];

        let clear_a = rand::random::<u64>();
        let clear_b = rand::random::<i8>();

        let proven_ct = ProvenCompactCiphertextList::builder(&pk)
            .push(clear_a)
            .push(clear_b)
            .push(false)
            .build_with_proof_packed(&crs, &metadata, ZkComputeLoad::Proof)
            .unwrap();

        // Clone the list so both CPU and GPU start from the same state
        let mut cpu_list = proven_ct.clone();

        // Simulate a 256 bits nonce
        let nonce: [u8; 256 / 8] = core::array::from_fn(|_| rand::random());

        // Create two identical seeds from the same context inputs
        let cpu_seed = {
            let mut ctx = ReRandomizationContext::new(
                rerand_domain_separator,
                [b"expand".as_slice(), nonce.as_slice()],
                compact_public_encryption_domain_separator,
            );
            ctx.add_proven_ciphertext_list(&proven_ct);
            ctx.finalize().next_seed().unwrap()
        };

        let gpu_seed = {
            let mut ctx = ReRandomizationContext::new(
                rerand_domain_separator,
                [b"expand".as_slice(), nonce.as_slice()],
                compact_public_encryption_domain_separator,
            );
            ctx.add_proven_ciphertext_list(&proven_ct);
            ctx.finalize().next_seed().unwrap()
        };

        // Re-randomize on CPU
        cpu_list.re_randomize(&pk, cpu_seed).unwrap();

        // Re-randomize on GPU
        let streams = CudaStreams::new_multi_gpu();
        let mut gpu_list = CudaProvenCompactCiphertextList::from_proven_compact_ciphertext_list(
            &proven_ct, &streams,
        );
        gpu_list.re_randomize(&pk, gpu_seed, &streams).unwrap();

        // Read ciphertext data back from GPU and reconstruct an integer proven list
        let gpu_compact_lists = gpu_list
            .d_flattened_compact_lists
            .to_vec_shortint_compact_ciphertext_list(&streams)
            .unwrap();

        let gpu_proved_lists: Vec<_> = gpu_compact_lists
            .into_iter()
            .zip(gpu_list.h_proved_lists.ct_list.proved_lists.iter())
            .map(|(ct, (_, proof))| (ct, proof.clone()))
            .collect();

        let gpu_on_cpu = ProvenCompactCiphertextList {
            ct_list: crate::shortint::ciphertext::ProvenCompactCiphertextList {
                proved_lists: gpu_proved_lists,
            },
            info: gpu_list.h_proved_lists.info.clone(),
        };

        assert!(cpu_list == gpu_on_cpu);
    }
}