arrow-left

Only this pageAll pages
gitbookPowered by GitBook
1 of 27

0.1

Loading...

Getting Started

Loading...

Loading...

Loading...

Loading...

Loading...

Boolean

Loading...

Loading...

Loading...

Loading...

Shortint

Loading...

Loading...

Loading...

Loading...

C API

Loading...

JS on WASM API

Loading...

Low-Level Core Cryptography

Loading...

Loading...

Developers

Loading...

API references

What is TFHE-rs?

⭐️ Star the repo on Githubarrow-up-right | 🗣 Community support forum arrow-up-right| 📁 Contribute to the projectarrow-up-right

TFHE-rs is a pure Rust implementation of TFHE for boolean and small integer arithmetics over encrypted data. It includes a Rust and C API, as well as a client-side WASM API.

TFHE-rs is meant for developers and researchers who want full control over what they can do with TFHE, while not having to worry about the low level implementation.

The goal is to have a stable, simple, high-performance, and production-ready library for all the advanced features of TFHE.

hashtag
Key cryptographic concepts

The TFHE-rs library implements Zama’s variant of Fully Homomorphic Encryption over the Torus (TFHE). TFHE is based on Learning With Errors (LWE), a well-studied cryptographic primitive believed to be secure even against quantum computers.

In cryptography, a raw value is called a message (also sometimes called a cleartext), while an encoded message is called a plaintext and an encrypted plaintext is called a ciphertext.

The idea of homomorphic encryption is that you can compute on ciphertexts while not knowing messages encrypted within them. A scheme is said to be fully homomorphic, meaning any program can be evaluated with it, if at least two of the following operations are supported (is a plaintext and is the corresponding ciphertext):

  • homomorphic univariate function evaluation:

  • homomorphic addition:

  • homomorphic multiplication:

Zama's variant of TFHE is fully homomorphic and deals with fixed-precision numbers as messages. It implements all needed homomorphic operations, such as addition and function evaluation via Programmable Bootstrapping. You can read more about Zama's TFHE variant in the .

Using FHE in a Rust program with TFHE-rs consists in:

  • generating a client key and a server key using secure parameters:

    • a client key encrypts/decrypts data and must be kept secret

    • a server key is used to perform operations on encrypted data and could be public (also called an evaluation key)

If you would like to know more about the problems that FHE solves, we suggest you review our .

encrypting plaintexts using the client key to produce ciphertexts

  • operating homomorphically on ciphertexts with the server key

  • decrypting the resulting ciphertexts into plaintexts using the client key

  • xxx
    E[x]E[x]E[x]
    f(E[x])=E[f(x)]f(E[x]) = E[f(x)]f(E[x])=E[f(x)]
    E[x]+E[y]=E[x+y]E[x] + E[y] = E[x + y]E[x]+E[y]=E[x+y]
    E[x]∗E[y]=E[x∗y]E[x] * E[y] = E[x * y]E[x]∗E[y]=E[x∗y]
    preliminary whitepaperarrow-up-right
    6 minute introduction to homomorphic encryptionarrow-up-right

    Quick Start

    This library makes it possible to execute homomorphic operations over encrypted data, where the data are either Booleans or short integers (named shortint in the rest of this documentation). It allows one to execute a circuit on an untrusted server because both circuit inputs and outputs are kept private. Data are indeed encrypted on the client side, before being sent to the server. On the server side, every computation is performed on ciphertexts.

    The server, however, has to know the circuit to be evaluated. At the end of the computation, the server returns the encryption of the result to the user. She can then decrypt it with her secret key.

    hashtag
    General method to write an homomorphic circuit program

    The overall process to write an homomorphic program is the same for both Boolean and shortint types. In a nutshell, the basic steps for using the TFHE-rs library are the following:

    • Choose a data type (Boolean or shortint)

    • Import the library

    • Create client and server keys

    hashtag
    Boolean example.

    Here is an example to illustrate how the library can be used to evaluate a Boolean circuit:

    hashtag
    Shortint example.

    And here is a full example using shortint:

    The library is pretty simple to use, and can evaluate homomorphic circuits of arbitrary length. The description of the algorithms can be found in the paper (also available as ).

    Benchmarks

    Due to their nature, homomorphic operations are obviously slower than their clear equivalent. In what follows, some timings are exposed for basic operations. For completeness, some benchmarks of other libraries are also given.

    All the benchmarks had been launched on an AWS m6i.metal with the following specifications: Intel(R) Xeon(R) Platinum 8375C CPU @ 2.90GHz and 512GB of RAM.

    hashtag
    Boolean

    This measures the execution time of a single binary boolean gate.

    hashtag
    tfhe.rs::boolean.

    Parameter set
    concrete-fft
    concrete-fft + avx512

    hashtag
    tfhe-lib.

    Parameter set
    fftw
    spqlios-fma

    hashtag
    OpenFHE.

    Parameter set
    GINX
    GINX (Intel HEXL)

    hashtag
    Shortint

    This measures the execution time for some operations and some parameter sets of shortint.

    hashtag
    tfhe.rs::shortint.

    This uses the concrete-fft + avx512 configuration.

    Parameter set
    unchecked_add
    unchecked_mul_lsb
    keyswitch_programmable_bootstrap

    3.06 µs

    134 ms

    134 ms

    PARAM_MESSAGE_4_CARRY_4

    11.7 µs

    854 ms

    945 ms

    DEFAULT_PARAMETERS

    8.8ms

    6.8ms

    TFHE_LIB_PARAMETERS

    13.6ms

    10.9ms

    default_128bit_gate_bootstrapping_parameters

    28.9ms

    15.7ms

    STD_128

    172ms

    78ms

    MEDIUM

    113ms

    50.2ms

    PARAM_MESSAGE_1_CARRY_1

    338 ns

    8.3 ms

    8.1 ms

    PARAM_MESSAGE_2_CARRY_2

    406 ns

    18.4 ms

    18.4 ms

    PARAM_MESSAGE_3_CARRY_3

    Contributing

    There are two ways to contribute to TFHE-rs:

    • you can open issues to report bugs and typos and to suggest ideas

    • you can ask to become an official contributor by emailing [email protected]. Only approved contributors can end pull requests, so please make sure to get in touch before you do!

    Encrypt data with the client key
  • Compute over encrypted data using the server key

  • Decrypt data with the client key

  • TFHEarrow-up-right
    ePrint 2018/421arrow-up-right
    use tfhe::boolean::prelude::*;
    
    fn main() {
    // We generate a set of client/server keys, using the default parameters:
        let (client_key, server_key) = gen_keys();
    
    // We use the client secret key to encrypt two messages:
        let ct_1 = client_key.encrypt(true);
        let ct_2 = client_key.encrypt(false);
    
    // We use the server public key to execute a boolean circuit:
    // if ((NOT ct_2) NAND (ct_1 AND ct_2)) then (NOT ct_2) else (ct_1 AND ct_2)
        let ct_3 = server_key.not(&ct_2);
        let ct_4 = server_key.and(&ct_1, &ct_2);
        let ct_5 = server_key.nand(&ct_3, &ct_4);
        let ct_6 = server_key.mux(&ct_5, &ct_3, &ct_4);
    
    // We use the client key to decrypt the output of the circuit:
        let output = client_key.decrypt(&ct_6);
        assert_eq!(output, true);
    }
    use tfhe::shortint::prelude::*;
    
    fn main() {
        // We generate a set of client/server keys, using the default parameters:
        let (client_key, server_key) = gen_keys(Parameters::default());
    
        let msg1 = 1;
        let msg2 = 0;
    
        let modulus = client_key.parameters.message_modulus.0;
    
        // We use the client key to encrypt two messages:
        let ct_1 = client_key.encrypt(msg1);
        let ct_2 = client_key.encrypt(msg2);
    
        // We use the server public key to execute an integer circuit:
        let ct_3 = server_key.unchecked_add(&ct_1, &ct_2);
    
        // We use the client key to decrypt the output of the circuit:
        let output = client_key.decrypt(&ct_3);
        assert_eq!(output, (msg1 + msg2) % modulus as u64);
    }

    Installation

    hashtag
    Importing into your project

    To use TFHE-rs in your project, you first need to add it as a dependency in your Cargo.toml:

    Serialization/Deserialization

    As explained in the introduction, some types (Serverkey, Ciphertext) are meant to be shared with the server that performs the computations.

    The easiest way to send these data to a server is to use the serialization and deserialization features. tfhe::shortint uses the serdearrow-up-right framework. Serde's Serialize and Deserialize are then implemented on tfhe::shortint's types.

    To be able to serialize our data, we need to pick a data formatarrow-up-right. For our use case, bincodearrow-up-right is a good choice, mainly because it is binary format.

    # Cargo.toml
    
    [dependencies]
    # ...
    bincode = "1.3.3"
    hashtag
    Choosing your features

    TFHE-rs exposes different cargo features to customize the types and features used.

    hashtag
    Kinds.

    This crate exposes two kinds of data types. Each kind is enabled by activating its corresponding feature in the TOML line. Each kind may have multiple types:

    Kind
    Features
    Type(s)

    Booleans

    boolean

    Booleans

    ShortInts

    shortint

    Short unsigned integers

    hashtag
    Serialization.

    The different data types and keys exposed by the crate can be serialized / deserialized.

    More information can be found here for boolean and here for shortint.

    hashtag
    Supported platforms

    TFHE-rs is supported on Linux (x86, aarch64), macOS (x86, aarch64) and Windows (x86 with RDSEED instruction).

    OS
    x86
    aarch64

    Linux

    x86_64-unix

    aarch64-unix*

    macOS

    x86_64-unix

    aarch64-unix*

    Windows

    x86_64

    Unsupported

    circle-info

    Users who have ARM devices can use TFHE-rs by compiling using the nightly toolchain.

    hashtag
    Using TFHE-rs with nightly toolchain.

    First, install the needed Rust toolchain:

    Then, you can either:

    • Manually specify the toolchain to use in each of the cargo commands:

    For example:

    • Or override the toolchain to use for the current project:

    To check the toolchain that Cargo will use by default, you can use the following command:

    // main.rs
    
    use bincode;
    use std::io::Cursor;
    use tfhe::shortint::prelude::*;
    
    
    fn main() -> Result<(), Box<dyn std::error::Error>> {
        let (client_key, server_key) = gen_keys(Parameters::default());
    
        let msg1 = 1;
        let msg2 = 0;
    
        let ct_1 = client_key.encrypt(msg1);
        let ct_2 = client_key.encrypt(msg2);
    
        let mut serialized_data = Vec::new();
        bincode::serialize_into(&mut serialized_data, &server_key)?;
        bincode::serialize_into(&mut serialized_data, &ct_1)?;
        bincode::serialize_into(&mut serialized_data, &ct_2)?;
    
        // Simulate sending serialized data to a server and getting
        // back the serialized result
        let serialized_result = server_function(&serialized_data)?;
        let result: Ciphertext = bincode::deserialize(&serialized_result)?;
    
        let output = client_key.decrypt(&result);
        assert_eq!(output, msg1 + msg2);
        Ok(())
    }
    
    
    fn server_function(serialized_data: &[u8]) -> Result<Vec<u8>, Box<dyn std::error::Error>> {
        let mut serialized_data = Cursor::new(serialized_data);
        let server_key: ServerKey = bincode::deserialize_from(&mut serialized_data)?;
        let ct_1: Ciphertext = bincode::deserialize_from(&mut serialized_data)?;
        let ct_2: Ciphertext = bincode::deserialize_from(&mut serialized_data)?;
    
        let result = server_key.unchecked_add(&ct_1, &ct_2);
    
        let serialized_result = bincode::serialize(&result)?;
    
        Ok(serialized_result)
    }
    tfhe = { version = "0.1.12", features = [ "boolean", "shortint", "x86_64-unix" ] }
    rustup toolchain install nightly
    cargo +nightly build
    cargo +nightly test
    rustup override set nightly
    # cargo will use the `nightly` toolchain.
    cargo build
    rustup show

    Quick Start

    The core_crypto module from TFHE-rs is dedicated to the implementation of the cryptographic tools related to TFHE. To construct an FHE application, the and/or modules (based on this one) are recommended.

    The core_crypto module offers an API to low-level cryptographic primitives and objects, like lwe_encryption or rlwe_ciphertext. Its goal is to propose an easy-to-use API for cryptographers.

    The overall code architecture is split in two parts: one for the entity definitions, and another one focused on the algorithms. For instance, the entities contain the definition of useful types, like LWE ciphertext or bootstrapping keys. The algorithms are then naturally defined to work using these entities.

    Serialization/Deserialization

    Since the ServerKey and ClientKey types both implement the Serialize and Deserialize traits, you are free to use any serializer that suits you to save and load the keys to disk.

    Here is an example using the bincode serialization library, which serializes to a binary format:

    Cryptographic Parameters

    hashtag
    Default parameters

    The TFHE cryptographic scheme relies on a variant of , and is based on a problem so hard to solve that it is even post-quantum resistant.

    In practice, you need to tune some cryptographic parameters in order to ensure both the correctness of the result and the security of the computation.

    To make it simpler, we provide two sets of parameters, which ensure correct computations for a certain probability with the standard security of 128 bits. There exists an error probability due to the probabilistic nature of the encryption, which requires adding randomness (called noise) following a Gaussian distribution. If this noise is too large, the decryption will not give a correct result. There is a trade-off between efficiency and correctness: generally, using a less efficient parameter set (in terms of computation time) leads to a smaller risk of having an error during homomorphic evaluation.

    use std::fs::File;
    use std::io::{Write, Read};
    use tfhe::boolean::prelude::*;
    
    fn main() {
    // We generate a set of client/server keys, using the default parameters:
        let (client_key, server_key) = gen_keys();
    
    // We serialize the keys to bytes:
        let encoded_server_key: Vec<u8> = bincode::serialize(&server_key).unwrap();
        let encoded_client_key: Vec<u8> = bincode::serialize(&client_key).unwrap();
    
        let server_key_file = "/tmp/ser_example_server_key.bin";
        let client_key_file = "/tmp/ser_example_client_key.bin";
    
    // We write the keys to files:
        let mut file = File::create(server_key_file)
            .expect("failed to create server key file");
        file.write_all(encoded_server_key.as_slice()).expect("failed to write key to file");
        let mut file = File::create(client_key_file)
            .expect("failed to create client key file");
        file.write_all(encoded_client_key.as_slice()).expect("failed to write key to file");
    
    // We retrieve the keys:
        let mut file = File::open(server_key_file)
            .expect("failed to open server key file");
        let mut encoded_server_key: Vec<u8> = Vec::new();
        file.read_to_end(&mut encoded_server_key).expect("failed to read the key");
    
        let mut file = File::open(client_key_file)
            .expect("failed to open client key file");
        let mut encoded_client_key: Vec<u8> = Vec::new();
        file.read_to_end(&mut encoded_client_key).expect("failed to read the key");
    
    // We deserialize the keys:
        let loaded_server_key: ServerKey = bincode::deserialize(&encoded_server_key[..])
            .expect("failed to deserialize");
        let loaded_client_key: ClientKey = bincode::deserialize(&encoded_client_key[..])
            .expect("failed to deserialize");
    
    
        let ct_1 = client_key.encrypt(false);
    
    // We check for equality:
        assert_eq!(false, loaded_client_key.decrypt(&ct_1));
    }
    The API is convenient to easily add or modify existing algorithms or to have direct access to the raw data. For instance, even if the LWE ciphertext object is defined along with functions giving access to he body, this is also possible to bypass these to get directly the ithi^{th}ith element of LWE mask.

    For instance, the code to encrypt and then decrypt a message looks like:

    shortint
    Boolean
    use tfhe::core_crypto::prelude::*;
    
    // DISCLAIMER: these toy example parameters are not guaranteed to be secure or yield correct
    // computations
    // Define parameters for LweCiphertext creation
    let lwe_dimension = LweDimension(742);
    let lwe_modular_std_dev = StandardDev(0.000007069849454709433);
    
    // Create the PRNG
    let mut seeder = new_seeder();
    let seeder = seeder.as_mut();
    let mut encryption_generator =
        EncryptionRandomGenerator::<ActivatedRandomGenerator>::new(seeder.seed(), seeder);
    let mut secret_generator =
        SecretRandomGenerator::<ActivatedRandomGenerator>::new(seeder.seed());
    
    // Create the LweSecretKey
    let lwe_secret_key =
        allocate_and_generate_new_binary_lwe_secret_key(lwe_dimension, &mut secret_generator);
    
    // Create the plaintext
    let msg = 3u64;
    let plaintext = Plaintext(msg << 60);
    
    // Create a new LweCiphertext
    let mut lwe = LweCiphertext::new(0u64, lwe_dimension.to_lwe_size());
    
    encrypt_lwe_ciphertext(
        &lwe_secret_key,
        &mut lwe,
        plaintext,
        lwe_modular_std_dev,
        &mut encryption_generator,
    );
    
    let decrypted_plaintext = decrypt_lwe_ciphertext(&lwe_secret_key, &lwe);
    
    // Round and remove encoding
    // First create a decomposer working on the high 4 bits corresponding to our encoding.
    let decomposer = SignedDecomposer::new(DecompositionBaseLog(4), DecompositionLevelCount(1));
    let rounded = decomposer.closest_representable(decrypted_plaintext.0);
    
    // Remove the encoding
    let cleartext = rounded >> 60;
    
    // Check we recovered the original message
    assert_eq!(cleartext, msg);

    In the two proposed sets of parameters, the only difference lies in this probability error. The default parameter set ensures a probability error of at most 2−402^{-40}2−40 when computing a programmable bootstrapping (i.e., any gates but the not). The other one is closer to the error probability claimed into the original TFHE paperarrow-up-right, namely 2−1652^{-165}2−165, but it is up-to-date regarding security requirements.

    The following array summarizes this:

    Parameter set
    Error probability

    DEFAULT_PARAMETERS

    TFHE_LIB_PARAMETERS

    hashtag
    User-defined parameters

    Note that, if you desire, you can also create your own set of parameters. This is an unsafe operation as failing to properly fix the parameters will potentially result in an incorrect and/or insecure computation:

    Regev cryptosystemarrow-up-right

    Supported Operations

    hashtag
    Boolean

    The list of supported operations by the homomorphic Booleans is:

    Operation Name
    type

    not

    A walk-through using homomorphic Booleans can be found .

    hashtag
    ShortInt

    In TFHE-rs, shortint represents short unsigned integers encoded over a maximum of 8 bits. A complete homomorphic arithmetic is provided, along with the possibility to compute univariate and bi-variate functions. Some operations are only available for integers up to 4 bits. More technical details can be found .

    The list of supported operations is:

    Operation name
    Type
    circle-info

    * The division operation implements a subtlety: since data is encrypted, it might be possible to compute a division by 0. In this case, the division is tweaked so that dividing by 0 returns 0.

    A walk-through example can be found , and more examples and explanations can be found .

    Operations

    In tfhe::boolean, the available operations are mainly related to their equivalent Boolean gates (i.e., AND, OR... etc). What follows is an example of a unary gate (NOT) and one about a binary gate (XOR). The last one is about the ternary MUX gate, which gives the possibility to homomorphically compute conditional statements of the form If..Then..Else.

    hashtag
    The NOT unary gate

    Cryptographic Parameters

    All parameter sets provide at least 128-bits of security according to the , with an error probability equal to when computing a programmable bootstrapping. This error probability is due to the randomness added at each encryption (see for more details about the encryption process).

    hashtag
    Parameters and message precision

    shortint comes with sets of parameters that permit the use of the library functionalities securely and efficiently. Each parameter set is associated to the message and carry precisions. Thus, each key pair is entangled to precision.

    Tutorial

    hashtag
    Writing an homomorphic circuit using shortint

    hashtag
    Key Generation

    use tfhe::boolean::prelude::*;
    
    fn main() {
    // WARNING: might be insecure and/or incorrect
    // You can create your own set of parameters
        let parameters = unsafe {
            BooleanParameters::new(
                LweDimension(586),
                GlweDimension(2),
                PolynomialSize(512),
                StandardDev(0.00008976167396834998),
                StandardDev(0.00000002989040792967434),
                DecompositionBaseLog(8),
                DecompositionLevelCount(2),
                DecompositionBaseLog(2),
                DecompositionLevelCount(5),
            )
        };
    }
    2−402^{-40}2−40
    2−1652^{-165}2−165

    Binary

    Comparisons

    Binary

    Left/Right Shift

    Binary

    And

    Binary

    Or

    Binary

    Xor

    Binary

    Exact Function Evaluation

    Unary/Binary

    Unary

    and

    Binary

    or

    Binary

    xor

    Binary

    nor

    Binary

    xnor

    Binary

    cmux

    Ternary

    Negation

    Unary

    Addition

    Binary

    Subtraction

    Binary

    Multiplication

    Binary

    Division*

    Binary

    here
    here
    here
    here

    Modular reduction

    hashtag
    Binary gates

    hashtag
    The MUX ternary gate

    Let ct_1, ct_2, ct_3 be three Boolean ciphertexts. Then, the MUX gate (abbreviation of MUltipleXer) is equivalent to the operation:

    This example shows how to use the MUX ternary gate:

    use tfhe::boolean::prelude::*;
    
    fn main() {
    // We generate a set of client/server keys, using the default parameters:
        let (client_key, server_key) = gen_keys();
    
    // We use the client secret key to encrypt a message:
        let ct_1 = client_key.encrypt(true);
    
    // We use the server public key to execute the NOT gate:
        let ct_not = server_key.not(&ct_1);
    
    // We use the client key to decrypt the output of the circuit:
        let output = client_key.decrypt(&ct_not);
        assert_eq!(output, false);
    }

    The user is allowed to choose which set of parameters to use when creating the pair of keys.

    The difference between the parameter sets is the total amount of space dedicated to the plaintext and how it is split between the message buffer and the carry buffer. The syntax chosen for the name of a parameter is: PARAM_MESSAGE_{number of message bits}_CARRY_{number of carry bits}. For example, the set of parameters for a message buffer of 5 bits and a carry buffer of 2 bits is PARAM_MESSAGE_5_CARRY_2.

    In what follows, there is an example where keys are generated to have messages encoded over 2 bits i.e., computations are done modulus 22=42^2 = 422=4), with 2 bits of carry.

    Note that the PARAM_MESSAGE_2_CARRY_2 parameter set is the default shortint parameter set that you can also use through the tfhe::shortint::prelude::DEFAULT_PARAMETERS constant.

    hashtag
    Impact of parameters on the operations

    As shown here, the choice of the parameter set impacts the operations available and their efficiency.

    hashtag
    Generic bi-variate functions.

    The computations of bi-variate functions is based on a trick, concatenating two ciphertexts into one. In the case where the carry buffer is not at least as large as the message one, this trick no longer works. Then, many bi-variate operations, such as comparisons cannot be correctly computed. The only exception concerns the multiplication.

    hashtag
    Multiplication.

    In the case of the multiplication, two algorithms are implemented: the first one relies on the bi-variate function trick, where the other one is based on the quarter square methodarrow-up-right. In order to correctly compute a multiplication, the only requirement is to have at least one bit of carry (i.e., using parameter sets PARAM_MESSAGE_X_CARRY_Y with Y>=1). This method is, in general, slower than using the other one. Note that using the smart version of the multiplication automatically chooses which algorithm is used depending on the chosen parameters.

    hashtag
    User-defined parameter sets

    Beyond the predefined parameter sets, it is possible to define new parameter sets. To do so, it is sufficient to use the function unsecure_parameters() or to manually fill the Parameter structure fields.

    For instance:

    2−402^{-40}2−40
    Lattice-Estimatorarrow-up-right
    here
    tfhe::shortint provides 2 key types:
    • ClientKey

    • ServerKey

    The ClientKey is the key that encrypts and decrypts messages (integer values up to 8 bits here), thus this key is meant to be kept private and should never be shared. This key is created from parameter values that will dictate both the security and efficiency of computations. The parameters also set the maximum number of bits of message encrypted in a ciphertext.

    The ServerKey is the key that is used to actually do the FHE computations. It contains (among other things) a bootstrapping key and a keyswitching key. This key is created from a ClientKey that needs to be shared to the server, therefore it is not meant to be kept private. A user with a ServerKey can compute on the encrypted data sent by the owner of the associated ClientKey.

    To reflect that, computation/operation methods are tied to the ServerKey type.

    hashtag
    Encrypting values

    Once the keys have been generated, the client key is used to encrypt data:

    hashtag
    Encrypting values using a public key

    Once the keys have been generated, the client key is used to encrypt data:

    hashtag
    Computing and decrypting

    With our server_key and encrypted values, we can now do an addition and then decrypt the result.

    use tfhe::boolean::prelude::*;
    
    fn main() {
    // We generate a set of client/server keys, using the default parameters:
        let (client_key, server_key) = gen_keys();
    
    // We use the client secret key to encrypt a message:
        let ct_1 = client_key.encrypt(true);
        let ct_2 = client_key.encrypt(false);
    
    // We use the server public key to execute the XOR gate:
        let ct_xor = server_key.xor(&ct_1, &ct_2);
    
    // We use the client key to decrypt the output of the circuit:
        let output = client_key.decrypt(&ct_xor);
        assert_eq!(output, true^false);
    }
    if ct_1 {
        return ct_2
    } else {
        return ct_3
    }
    use tfhe::boolean::prelude::*;
    
    fn main() {
    // We generate a set of client/server keys, using the default parameters:
        let (client_key, server_key) = gen_keys();
    
        let bool1 = true;
        let bool2 = false;
        let bool3 = true;
    
    // We use the client secret key to encrypt a message:
        let ct_1 = client_key.encrypt(true);
        let ct_2 = client_key.encrypt(false);
        let ct_3 = client_key.encrypt(false);
    
    
    // We use the server public key to execute the NOT gate:
        let ct_xor = server_key.mux(&ct_1, &ct_2, &ct_3);
    
    // We use the client key to decrypt the output of the circuit:
        let output = client_key.decrypt(&ct_xor);
        assert_eq!(output, if bool1 {bool2} else {bool3});
    }
    use tfhe::shortint::prelude::*;
    
    fn main() {
        // We generate a set of client/server keys, using the default parameters:
       let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
    
        let msg1 = 3;
        let msg2 = 2;
    
        // We use the client key to encrypt two messages:
        let ct_1 = client_key.encrypt(msg1);
        let ct_2 = client_key.encrypt(msg2);
    }
    use tfhe::shortint::prelude::*;
    
    fn main() {
        let param = unsafe {
            Parameters::new(
                LweDimension(656),
                GlweDimension(2),
                PolynomialSize(512),
                StandardDev(0.000034119201269311964),
                StandardDev(0.00000004053919869756513),
                DecompositionBaseLog(8),
                DecompositionLevelCount(2),
                DecompositionBaseLog(3),
                DecompositionLevelCount(4),
                StandardDev(0.00000000037411618952047216),
                DecompositionBaseLog(15),
                DecompositionLevelCount(1),
                DecompositionLevelCount(0),
                DecompositionBaseLog(0),
                MessageModulus(4),
                CarryModulus(1),
            )
        };
    }
    use tfhe::shortint::prelude::*;
    
    fn main()  {
        // We generate a set of client/server keys, using the default parameters:
        let (client_key, server_key) = gen_keys(Parameters::default());
    }
    use tfhe::shortint::prelude::*;
    
    fn main() {
        // We generate a set of client/server keys, using the default parameters:
       let (client_key, server_key) = gen_keys(Parameters::default());
    
        let msg1 = 1;
        let msg2 = 0;
    
        // We use the client key to encrypt two messages:
        let ct_1 = client_key.encrypt(msg1);
        let ct_2 = client_key.encrypt(msg2);
    }
    use tfhe::shortint::prelude::*;
    
    fn main() {
        // We generate a set of client/server keys, using the default parameters:
       let (client_key, _) = gen_keys(Parameters::default());
       let public_key = PublicKey::new(&client_key);
    
        let msg1 = 1;
        let msg2 = 0;
    
        // We use the client key to encrypt two messages:
        let ct_1 = public_key.encrypt(msg1);
        let ct_2 = public_key.encrypt(msg2);
    }
    use tfhe::shortint::prelude::*;
    
    fn main() {
        // We generate a set of client/server keys, using the default parameters:
        let (client_key, server_key) = gen_keys(Parameters::default());
    
        let msg1 = 1;
        let msg2 = 0;
    
        let modulus = client_key.parameters.message_modulus.0;
    
        // We use the client key to encrypt two messages:
        let ct_1 = client_key.encrypt(msg1);
        let ct_2 = client_key.encrypt(msg2);
    
        // We use the server public key to execute an integer circuit:
        let ct_3 = server_key.unchecked_add(&ct_1, &ct_2);
    
        // We use the client key to decrypt the output of the circuit:
        let output = client_key.decrypt(&ct_3);
        assert_eq!(output, (msg1 + msg2) % modulus as u64);
    }

    Security and Cryptography

    hashtag
    TFHE

    TFHE-rs is a cryptographic library dedicated to Fully Homomorphic Encryption. As its name suggests, it is based on the TFHE scheme.

    It is interesting to understand some basics about TFHE in order to comprehend where the limitations are coming from, both in terms of precision (number of bits used to represent the plaintext values) and execution time (why TFHE operations are slower than native operations).

    hashtag
    LWE ciphertexts

    Although there are many kinds of ciphertexts in TFHE, all the encrypted values in TFHE-rs are mainly stored as LWE ciphertexts.

    The security of TFHE relies on the LWE problem, which stands for Learning With Errors. The problem is believed to be secure against quantum attacks.

    An LWE Ciphertext is a collection of 32-bit or 64-bit unsigned integers. Before encrypting a message in an LWE ciphertext, one must first encode it as a plaintext. This is done by shifting the message to the most significant bits of the unsigned integer type used.

    Then, a little random value called noise is added to the least significant bits. This noise (also called error for Learning With Errors) is crucial to the security of the ciphertext.

    To go from a plaintext to a ciphertext, one must encrypt the plaintext using a secret key.

    An LWE secret key is a list of n random integers: . is called the

    A LWE ciphertext, is composed of two parts:

    • The mask

    • The body

    The mask of a fresh ciphertext (one that is the result of an encryption and not an operation, such as ciphertext addition) is a list of n uniformly random values.

    The body is computed as follows:

    Now that the encryption scheme is defined, to illustrate why it is slower to compute over encrypted data, let us show the example of the addition between ciphertexts.

    To add two ciphertexts, we must add their $mask$ and $body$, as is done below.

    To add ciphertexts, it is sufficient to add their masks and bodies. Instead of just adding 2 integers, one needs to add elements. The addition is an intuitive example to show the slowdown of FHE computation compared to plaintext computation, but other operations are far more expensive (e.g., the computation of a lookup table using the Programmable Bootstrapping).

    hashtag
    Understanding noise and padding

    In FHE, there are two types of operations that can be applied to ciphertexts:

    • leveled operations, which increase the noise in the ciphertext

    • bootstrapped operations, which reduce the noise in the ciphertext

    In FHE, the noise must be tracked and managed in order to guarantee the correctness of the computation.

    Bootstrapping operations are used across the computation to decrease the noise in the ciphertexts, preventing it from tampering the message. The rest of the operations are called leveled because they do not need bootstrapping operations and, thus, are usually really fast.

    The following sections explain the concept of noise and padding in ciphertexts.

    hashtag
    Noise.

    For it to be secure, LWE requires random noise to be added to the message at encryption time.

    In TFHE, this random noise is drawn from a Centered Normal Distribution parameterized by a standard deviation. This standard deviation is a security parameter. With all other security parameters set, the larger the standard deviation is, the more secure the encryption is.

    In TFHE-rs, the noise is encoded in the least significant bits of the plaintexts. Each leveled computation will increase the noise. Thus, if too many computations are performed, the noise will eventually overflow onto the significant data bits of the message and lead to an incorrect result.

    The figure below illustrates this problem in case of an addition, where an extra bit of noise is incurred as a result.

    TFHE-rs offers the ability to automatically manage noise by performing bootstrapping operations to reset the noise when needed.

    hashtag
    Padding.

    Since encoded values have a fixed precision, operating on them can sometimes produce results that are outside the original interval. To avoid losing precision or wrapping around the interval, TFHE-rs uses additional bits by defining bits of padding on the most significant bits.

    As an example, consider adding two ciphertexts. Adding two values could end up outside the range of either ciphertext, and thus necessitate a carry, which would then be carried onto the first padding bit. In the figure below, each plaintext over 32 bits has one bit of padding on its left (i.e., the most significant bit). After the addition, the padding bit is no longer available, as it has been used in order for the carry. This is referred to as consuming bits of padding. Since no padding is left, there is no guarantee that further additions would yield correct results.

    If you would like to know more about TFHE, you can find more information in our .

    hashtag
    Security.

    By default, the cryptographic parameters provided by TFHE-rs ensure at least 128 bits of security. The security has been evaluated using the latest versions of the Lattice Estimator () with red_cost_model = reduction.RC.BDGL16.

    For all sets of parameters, the error probability when computing a univariate function over one ciphertext is . Note that univariate functions might be performed when arithmetic functions are computed (for instance, the multiplication of two ciphertexts).

    hashtag
    Public key encryption.

    In public key encryption, the public key contains a given number of ciphertexts all encrypting the value 0. By setting the number of encryptions of 0 in the public key at , where is the LWE dimension, is the ciphertext modulus, and is the number of security bits. In a nutshell, this construction is secure due to the leftover hash lemma, which is essentially related to the impossibility of breaking the underlying multiple subset sum problem. By using this formula, this guarantees both a high-density subset sum and an exponentially large number of possible associated random vectors per LWE sample (a,b).

    plaintext=(Δ∗m)+eplaintext = (\Delta * m) + eplaintext=(Δ∗m)+e
    S=(s0,...,sn)S = (s_0, ..., s_n)S=(s0​,...,sn​)
    nnn
    LweDimensionLweDimensionLweDimension
    (a0,...,an−1)(a_0, ..., a_{n-1})(a0​,...,an−1​)
    bbb
    b=(∑i=0n−1ai∗si)+plaintextb = (\sum_{i = 0}^{n-1}{a_i * s_i}) + plaintextb=(∑i=0n−1​ai​∗si​)+plaintext
    ct0=(a0,...,an,b)ct1=(a1′,...,an′,b′)ct2=ct0+ct1ct2=(a0+a0′,...,an+an′,b+b′)b+b′=(∑i=0n−1ai∗si)+plaintext+(∑i=0n−1ai′∗si)+plaintext′b+b′=(∑i=0n−1(ai+ai′)∗si)+Δm+Δm′+e+e′ct_0 = (a_{0}, ..., a_{n}, b) \\ ct_1 = (a_{1}^{'}, ..., a_{n}^{'}, b^{'}) \\ ct_{2} = ct_0 + ct_1 \\ ct_{2} = (a_{0} + a_{0}^{'}, ..., a_{n} + a_{n}^{'}, b + b^{'})\\ b + b^{'} = (\sum_{i = 0}^{n-1}{a_i * s_i}) + plaintext + (\sum_{i = 0}^{n-1}{a_i^{'} * s_i}) + plaintext^{'}\\ b + b^{'} = (\sum_{i = 0}^{n-1}{(a_i + a_i^{'})* s_i}) + \Delta m + \Delta m^{'} + e + e^{'}\\ct0​=(a0​,...,an​,b)ct1​=(a1′​,...,an′​,b′)ct2​=ct0​+ct1​ct2​=(a0​+a0′​,...,an​+an′​,b+b′)b+b′=(i=0∑n−1​ai​∗si​)+plaintext+(i=0∑n−1​ai′​∗si​)+plaintext′b+b′=(i=0∑n−1​(ai​+ai′​)∗si​)+Δm+Δm′+e+e′
    n+1n + 1n+1
    2−402^{-40}2−40
    m=⌈(n+1)log⁡(q)⌉+λm = \lceil (n+1) \log(q) \rceil + \lambdam=⌈(n+1)log(q)⌉+λ
    nnn
    qqq
    λ\lambdaλ
    TFHE Deep Divearrow-up-right
    repositoryarrow-up-right
    Noise overtaking the plaintexts after homomorphic addition. Most significant bits are on the left.

    Tutorial

    This library is meant to be used both on the server side and on the client side. The typical use case should follow the subsequent steps:

    1. On the client side, generate the client and server keys.

    2. Send the server key to the server.

    3. Then any number of times:

      • On the client side, encryption of the input data with the client key.

      • Transmit the encrypted input to the server.

    hashtag
    Setup

    In the first step, the client creates two keys: the client key and the server key, with the concrete_boolean::gen_keys function:

    • The client_key is of type ClientKey. It is secret, and must never be transmitted. This key will only be used to encrypt and decrypt data.

    • The server_key is of type ServerKey. It is a public key, and can be shared with any party. This key has to be sent to the server because it is required for homomorphic computation.

    Note that both the client_key and server_key implement the Serialize and Deserialize traits. This way you can use any compatible serializer to store/send the data. For instance, to store the server_key in a binary file, you can use the bincode library:

    hashtag
    Encrypting Inputs

    Once the server key is available on the server side, it is possible to perform some homomorphic computations. The client simply needs to encrypt some data and send it to the server. Again, the Ciphertext type implements the Serialize and the Deserialize traits, so that any serializer and communication tool suiting your use case can be employed:

    hashtag
    Encrypting Inputs using a public key

    Once the server key is available on the server side, it is possible to perform some homomorphic computations. The client simply needs to encrypt some data and send it to the server. Again, the Ciphertext type implements the Serialize and the Deserialize traits, so that any serializer and communication tool suiting your use case can be utilized:

    hashtag
    Executing a Boolean circuit

    Once the encrypted inputs are on the server side, the server_key can be used to homomorphically execute the desired Boolean circuit:

    hashtag
    Decrypting the output

    Once the encrypted output is on the client side, the client_key can be used to decrypt it:

    Tutorial

    hashtag
    Using the C API

    Welcome to this TFHE-rs C API tutorial!

    This library exposes a C binding to the TFHE-rs primitives to implement Fully Homomorphic Encryption (FHE) programs.

    hashtag
    First steps using TFHE-rs C API

    hashtag
    Setting-up TFHE-rs C API for use in a C program.

    TFHE-rs C API can be built on a Unix x86_64 machine using the following command:

    or on a Unix aarch64 machine using the following command

    All features are opt-in, but for simplicity here, the C API is enabled for boolean and shortint.

    The tfhe.h header as well as the static (.a) and dynamic (.so) libtfhe binaries can then be found in "${REPO_ROOT}/target/release/"

    The build system needs to be set up so that the C or C++ program links against TFHE-rs C API binaries.

    Here is a minimal CMakeLists.txt allowing to do just that:

    hashtag
    Commented code of a PBS doubling a 2 bits encrypted message using TFHE-rs C API.

    The steps required to perform the multiplication by 2 of a 2 bits ciphertext using a PBS are detailed. This is NOT the most efficient way of doing this operation, but it can help to show the management required to run a PBS manually using the C API.

    WARNING: The following example does not have proper memory management in the error case to make it easier to fit the code on this page.

    To run the example below, the above CMakeLists.txt and main.c files need to be in the same directory. The commands to run are:

    hashtag
    Audience

    Programmers wishing to use TFHE-rs but who are unable to use Rust (for various reasons) can use these bindings in their language of choice, as long as it can interface with C code to bring TFHE-rs functionalities to said language.

    Tutorial

    hashtag
    Using the JS on WASM API

    Welcome to this TFHE-rs JS on WASM API tutorial!

    TFHE-rs uses WASM to expose a JS binding to the client-side primitives, like key generation and encryption, of the Boolean and shortint modules.

    There are several limitations at this time. Due to a lack of threading support in WASM, key generation can be too slow to be practical for bigger parameter sets.

    Some parameter sets lead to FHE keys that are too big to fit in the 2GB memory space of WASM. This means that some parameters sets are virtually unusable.

    hashtag
    First steps using TFHE-rs JS on WASM API

    hashtag
    Setting-up TFHE-rs JS on WASM API for use in nodejs programs.

    To build the JS on WASM bindings for TFHE-rs, you will first need to install in addition to a compatible (>= 1.65) .

    Then, in a shell run the following to clone the TFHE-rs repo (one may want to checkout a specific tag, here the default branch is used for the build):

    The command above targets nodejs. A binding for a web browser can be generated as well using --target=web. This use case will not be discussed in this tutorial.

    Both Boolean and shortint features are enabled here but it's possible to use one without the other.

    After the build, a new directory pkg is present in the tfhe directory.

    hashtag
    Commented code to generate keys for shortint and encrypt a ciphertext

    circle-info

    Be sure to update the path of the required clause in the example below for the TFHE package that was just built.

    The example.js script can then be run using like so:

    On the server side, homomorphic computation with the server key.

  • Transmit the encrypted output to the client.

  • On the client side, decryption of the output data with the client key.

  • wasm-packarrow-up-right
    rust toolchainarrow-up-right
    nodearrow-up-right
    use tfhe::boolean::prelude::*;
    
    fn main() {
    
    // We generate the client key and the server key,
    // using the default parameters:
        let (client_key, server_key): (ClientKey, ServerKey) = gen_keys();
    }
    use std::fs::File;
    use std::io::{Write, Read};
    use tfhe::boolean::prelude::*;
    
    fn main() {
    
    //---------------------------- CLIENT SIDE ----------------------------
    
    // We generate a client key and a server key, using the default parameters:
        let (client_key, server_key) = gen_keys();
    
    // We serialize the server key to bytes, and store them in a file:
        let encoded: Vec<u8> = bincode::serialize(&server_key).unwrap();
    
        let server_key_file = "/tmp/tutorial_server_key.bin";
    
    // We write the server key to a file:
        let mut file = File::create(server_key_file)
            .expect("failed to create server key file");
        file.write_all(encoded.as_slice()).expect("failed to write key to file");
    
    // ...
    // We send the key to server side
    // ...
    
    
    //---------------------------- SERVER SIDE ----------------------------
    
    // We read the file:
        let mut file = File::open(server_key_file)
            .expect("failed to open server key file");
        let mut encoded: Vec<u8> = Vec::new();
        file.read_to_end(&mut encoded).expect("failed to read key");
    
    // We deserialize the server key:
        let key: ServerKey = bincode::deserialize(&encoded[..])
            .expect("failed to deserialize");
    }
    use tfhe::boolean::prelude::*;
    
    fn main() {
        // Don't consider the following line; you should follow the procedure above.
        let (client_key, _) = gen_keys();
    
    //---------------------------- SERVER SIDE
    
    // We use the client key to encrypt the messages:
        let ct_1 = client_key.encrypt(true);
        let ct_2 = client_key.encrypt(false);
    
    // We serialize the ciphertexts:
        let encoded_1: Vec<u8> = bincode::serialize(&ct_1).unwrap();
        let encoded_2: Vec<u8> = bincode::serialize(&ct_2).unwrap();
    
    // ...
    // And we send them to the server somehow
    // ...
    }
    use tfhe::boolean::prelude::*;
    
    fn main() {
        // Don't consider the following line; you should follow the procedure above.
        let (client_key, _) = gen_keys();
        let public_key = PublicKey::new(&client_key);
    
    //---------------------------- SERVER SIDE
    
    // We use the public key to encrypt the messages:
        let ct_1 = public_key.encrypt(true);
        let ct_2 = public_key.encrypt(false);
    
    // We serialize the ciphertexts:
        let encoded_1: Vec<u8> = bincode::serialize(&ct_1).unwrap();
        let encoded_2: Vec<u8> = bincode::serialize(&ct_2).unwrap();
    
    // ...
    // And we send them to the server somehow
    // ...
    }
    use std::fs::File;
    use std::io::{Write, Read};
    use tfhe::boolean::prelude::*;
    
    fn main() {
        // Don't consider the following lines; you should follow the procedure above.
        let (client_key, server_key) = gen_keys();
        let ct_1 = client_key.encrypt(true);
        let ct_2 = client_key.encrypt(false);
        let encoded_1: Vec<u8> = bincode::serialize(&ct_1).unwrap();
        let encoded_2: Vec<u8> = bincode::serialize(&ct_2).unwrap();
    
    //---------------------------- ON SERVER SIDE ----------------------------
    
    // We deserialize the ciphertexts:
        let ct_1: Ciphertext = bincode::deserialize(&encoded_1[..])
            .expect("failed to deserialize");
        let ct_2: Ciphertext = bincode::deserialize(&encoded_2[..])
            .expect("failed to deserialize");
    
    // We use the server key to execute the boolean circuit:
    // if ((NOT ct_2) NAND (ct_1 AND ct_2)) then (NOT ct_2) else (ct_1 AND ct_2)
        let ct_3 = server_key.not(&ct_2);
        let ct_4 = server_key.and(&ct_1, &ct_2);
        let ct_5 = server_key.nand(&ct_3, &ct_4);
        let ct_6 = server_key.mux(&ct_5, &ct_3, &ct_4);
    
    // Then we serialize the output of the circuit:
        let encoded_output: Vec<u8> = bincode::serialize(&ct_6)
            .expect("failed to serialize output");
    
    // ...
    // And we send the output to the client
    // ...
    }
    use std::fs::File;
    use std::io::{Write, Read};
    use tfhe::boolean::prelude::*;
    
    fn main() {
        // Don't consider the following lines; you should follow the procedure above.
        let (client_key, server_key) = gen_keys();
        let ct_6 = client_key.encrypt(true);
        let encoded_output: Vec<u8> = bincode::serialize(&ct_6).unwrap();
    
    //---------------------------- ON CLIENT SIDE
    
    // We deserialize the output ciphertext:
        let output: Ciphertext = bincode::deserialize(&encoded_output[..])
            .expect("failed to deserialize");
    
    // Finally, we decrypt the output:
        let output = client_key.decrypt(&output);
    
    // And check that the result is the expected one:
        assert_eq!(output, true);
    }
    RUSTFLAGS="-C target-cpu=native" cargo build --release --features=x86_64-unix,boolean-c-api,shortint-c-api -p tfhe
    RUSTFLAGS="-C target-cpu=native" cargo build --release --features=aarch64-unix,boolean-c-api,shortint-c-api -p tfhe
    project(my-project)
    
    cmake_minimum_required(VERSION 3.16)
    
    set(TFHE_C_API "/path/to/tfhe-rs/binaries/and/header")
    
    include_directories(${TFHE_C_API})
    add_library(tfhe STATIC IMPORTED)
    set_target_properties(tfhe PROPERTIES IMPORTED_LOCATION ${TFHE_C_API}/libtfhe.a)
    
    if(APPLE)
        find_library(SECURITY_FRAMEWORK Security)
        if (NOT SECURITY_FRAMEWORK)
            message(FATAL_ERROR "Security framework not found")
        endif()
    endif()
    
    set(EXECUTABLE_NAME my-executable)
    add_executable(${EXECUTABLE_NAME} main.c)
    target_include_directories(${EXECUTABLE_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR})
    target_link_libraries(${EXECUTABLE_NAME} LINK_PUBLIC tfhe m pthread dl)
    if(APPLE)
        target_link_libraries(${EXECUTABLE_NAME} LINK_PUBLIC ${SECURITY_FRAMEWORK})
    endif()
    target_compile_options(${EXECUTABLE_NAME} PRIVATE -Werror)
    # /!\ Be sure to update CMakeLists.txt to give the absolute path to the compiled tfhe library
    $ ls
    CMakeLists.txt  main.c
    $ mkdir build && cd build
    $ cmake .. -DCMAKE_BUILD_TYPE=RELEASE
    ...
    $ make
    ...
    $ ./my-executable
    Result: 2
    $
    #include "tfhe.h"
    #include <assert.h>
    #include <inttypes.h>
    #include <stdio.h>
    
    uint64_t double_accumulator_2_bits_message(uint64_t in) { return (in * 2) % 4; }
    
    uint64_t get_max_value_of_accumulator_generator(uint64_t (*accumulator_func)(uint64_t),
                                                    size_t message_bits)
    {
        uint64_t max_value = 0;
        for (size_t idx = 0; idx < (1 << message_bits); ++idx)
        {
            uint64_t acc_value = accumulator_func((uint64_t)idx);
            max_value = acc_value > max_value ? acc_value : max_value;
        }
    
        return max_value;
    }
    
    int main(void)
    {
        ShortintPBSAccumulator *accumulator = NULL;
        ShortintClientKey *cks = NULL;
        ShortintServerKey *sks = NULL;
        ShortintParameters *params = NULL;
    
        // Get the parameters for 2 bits messages with 2 bits of carry
        int get_params_ok = shortint_get_parameters(2, 2, &params);
        assert(get_params_ok == 0);
    
        // Generate the keys with the parameters
        int gen_keys_ok = shortint_gen_keys_with_parameters(params, &cks, &sks);
        assert(gen_keys_ok == 0);
    
        // Generate the accumulator for the PBS
        int gen_acc_ok = shortint_server_key_generate_pbs_accumulator(
            sks, double_accumulator_2_bits_message, &accumulator);
        assert(gen_acc_ok == 0);
    
        ShortintCiphertext *ct = NULL;
        ShortintCiphertext *ct_out = NULL;
    
        // We will compute 1 * 2 using a PBS, it's not the recommended way to perform a multiplication,
        // but it shows how to manage a PBS manually in the C API
        uint64_t in_val = 1;
    
        // Encrypt the input value
        int encrypt_ok = shortint_client_key_encrypt(cks, in_val, &ct);
        assert(encrypt_ok == 0);
    
        // Check the degree is set to the maximum value that can be encrypted on 2 bits, i.e. 3
        // This check is not required and is just added to show, the degree information can be retrieved
        // in the C APi
        size_t degree = -1;
        int get_degree_ok = shortint_ciphertext_get_degree(ct, &degree);
        assert(get_degree_ok == 0);
    
        assert(degree == 3);
    
        // Apply the PBS on our encrypted input
        int pbs_ok = shortint_server_key_programmable_bootstrap(sks, accumulator, ct, &ct_out);
        assert(pbs_ok == 0);
    
        // Set the degree to keep consistency for potential further computations
        // Note: This is only required for the PBS
        size_t degree_to_set =
            (size_t)get_max_value_of_accumulator_generator(double_accumulator_2_bits_message, 2);
    
        int set_degree_ok = shortint_ciphertext_set_degree(ct_out, degree_to_set);
        assert(set_degree_ok == 0);
    
        // Decrypt the result
        uint64_t result = -1;
        int decrypt_non_assign_ok = shortint_client_key_decrypt(cks, ct_out, &result);
        assert(decrypt_non_assign_ok == 0);
    
        // Check the result is what we expect i.e. 2
        assert(result == double_accumulator_2_bits_message(in_val));
        printf("Result: %ld\n", result);
    
        // Destroy entities from the C API
        destroy_shortint_ciphertext(ct);
        destroy_shortint_ciphertext(ct_out);
        destroy_shortint_pbs_accumulator(accumulator);
        destroy_shortint_client_key(cks);
        destroy_shortint_server_key(sks);
        destroy_shortint_parameters(params);
        return EXIT_SUCCESS;
    }
    $ git clone https://github.com/zama-ai/tfhe-rs.git
    Cloning into 'tfhe-rs'...
    ...
    Resolving deltas: 100% (3866/3866), done.
    $ cd tfhe-rs
    $ cd tfhe
    $ rustup run wasm-pack build --release --target=nodejs --features=boolean-client-js-wasm-api,shortint-client-js-wasm-api
    [INFO]: Compiling to Wasm...
    ...
    [INFO]: :-) Your wasm pkg is ready to publish at ...
    $ ls pkg
    LICENSE  index.html  package.json  tfhe.d.ts  tfhe.js  tfhe_bg.txt  tfhe_bg.wasm  tfhe_bg.wasm.d.ts
    $
    // Here import assert to check the decryption went well and panic otherwise
    const assert = require('node:assert').strict;
    // Import the Shortint module from the TFHE-rs package generated earlier
    const { Shortint } = require("/path/to/built/tfhe/pkg");
    
    function shortint_example() {
        // Get pre-defined parameters from the shortint module to manage messages with 4 bits of useful
        // information in total (2 bits of "message" and 2 bits of "carry")
        let params = Shortint.get_parameters(2, 2);
        // Create a new secret ClientKey, this must not be shared
        console.log("Generating client keys...")
        let cks = Shortint.new_client_key(params);
        // Encrypt 3 in a ciphertext
        console.log("Encrypting 3...")
        let ct = Shortint.encrypt(cks, BigInt(3));
    
        // Demonstrate ClientKey serialization (for example saving it on disk on the user device)
        let serialized_cks = Shortint.serialize_client_key(cks);
        // Deserialization
        let deserialized_cks = Shortint.deserialize_client_key(serialized_cks);
    
        // Demonstrate ciphertext serialization to send over the network
        let serialized_ct = Shortint.serialize_ciphertext(ct);
        // Deserialize a ciphertext received over the network for example
        let deserialized_ct = Shortint.deserialize_ciphertext(serialized_ct);
    
        // Decrypt with the deserialized objects
        console.log("Decrypting ciphertext...")
        let decrypted = Shortint.decrypt(deserialized_cks, deserialized_ct);
        // Check decryption works as expected
        assert.deepStrictEqual(decrypted, BigInt(3));
        console.log("Decryption successful!")
    
        // Generate public evaluation keys, also called ServerKey
        console.log("Generating compressed ServerKey...")
        let sks = Shortint.new_compressed_server_key(cks);
    
        // Can be serialized to send over the network to the machine doing the evaluation
        let serialized_sks = Shortint.serialize_compressed_server_key(sks);
        let deserialized_sks = Shortint.deserialize_compressed_server_key(serialized_sks);
        console.log("All done!")
    }
    
    shortint_example();
    $ node example.js
    Generating client keys...
    Encrypting 3...
    Decrypting ciphertext...
    Decryption successful!
    Generating compressed ServerKey...
    All done!
    $

    Tutorial

    hashtag
    Using the core_crypto primitives

    Welcome to this tutorial about TFHE-rs core_crypto module!

    hashtag
    Setting-up TFHE-rs to use the core_crypto module

    To use TFHE-rs, first it has to be added as a dependency in the Cargo.toml:

    Here, this enables the x86_64-unix feature to have efficient implementations of various algorithms for x86_64 CPUs on a Unix-like system. The 'unix' suffix indicates that the UnixSeeder, which uses /dev/random to generate random numbers, is actived as a fallback if no hardware number generator is available, like rdseed on x86_64 or if the on Apple platforms are not available. To avoid having the UnixSeeder as a potential fallback or to run on non-Unix systems (e.g., Windows), the x86_64 feature is sufficient.

    For Apple Silicon, the aarch64-unix or aarch64 feature should be enabled. Note that aarch64 is not supported on Windows as it's currently missing an entropy source required to seed the used in TFHE-rs.

    In short: For x86_64-based machines running Unix-like OSes:

    For Apple Silicon or aarch64-based machines running Unix-like OSes:

    For x86_64-based machines with the running Windows:

    hashtag
    Commented code to double a 2 bits message in a leveled fashion and using a PBS with the core_crypto module.

    As a complete example showing the usage of some common primitives of the core_crypto APIs, the following Rust code homomorphically computes 2 * 3 using two different methods. First using a cleartext multiplication and second using a PBS.

    Randomization Servicesarrow-up-right
    CSPRNGsarrow-up-right
    rdseed instructionarrow-up-right
    tfhe = { version = "0.1.12", features = [ "x86_64-unix" ] }
    tfhe = { version = "0.1.12", features = ["x86_64-unix"] }
    tfhe = { version = "0.1.12", features = ["aarch64-unix"] }
    tfhe = { version = "0.1.12", features = ["x86_64"] }
    use tfhe::core_crypto::prelude::*;
    
    pub fn main() {
        // DISCLAIMER: these toy example parameters are not guaranteed to be secure or yield correct
        // computations
        // Define the parameters for a 4 bits message able to hold the doubled 2 bits message
        let small_lwe_dimension = LweDimension(742);
        let glwe_dimension = GlweDimension(1);
        let polynomial_size = PolynomialSize(2048);
        let lwe_modular_std_dev = StandardDev(0.000007069849454709433);
        let glwe_modular_std_dev = StandardDev(0.00000000000000029403601535432533);
        let pbs_base_log = DecompositionBaseLog(23);
        let pbs_level = DecompositionLevelCount(1);
    
        // Request the best seeder possible, starting with hardware entropy sources and falling back to
        // /dev/random on Unix systems if enabled via cargo features
        let mut boxed_seeder = new_seeder();
        // Get a mutable reference to the seeder as a trait object from the Box returned by new_seeder
        let seeder = boxed_seeder.as_mut();
    
        // Create a generator which uses a CSPRNG to generate secret keys
        let mut secret_generator =
            SecretRandomGenerator::<ActivatedRandomGenerator>::new(seeder.seed());
    
        // Create a generator which uses two CSPRNGs to generate public masks and secret encryption
        // noise
        let mut encryption_generator =
            EncryptionRandomGenerator::<ActivatedRandomGenerator>::new(seeder.seed(), seeder);
    
        println!("Generating keys...");
    
        // Generate an LweSecretKey with binary coefficients
        let small_lwe_sk =
            LweSecretKey::generate_new_binary(small_lwe_dimension, &mut secret_generator);
    
        // Generate a GlweSecretKey with binary coefficients
        let glwe_sk =
            GlweSecretKey::generate_new_binary(glwe_dimension, polynomial_size, &mut secret_generator);
    
        // Create a copy of the GlweSecretKey re-interpreted as an LweSecretKey
        let big_lwe_sk = glwe_sk.clone().into_lwe_secret_key();
    
        // Generate the bootstrapping key, we use the parallel variant for performance reason
        let std_bootstrapping_key = par_allocate_and_generate_new_lwe_bootstrap_key(
            &small_lwe_sk,
            &glwe_sk,
            pbs_base_log,
            pbs_level,
            glwe_modular_std_dev,
            &mut encryption_generator,
        );
    
        // Create the empty bootstrapping key in the Fourier domain
        let mut fourier_bsk = FourierLweBootstrapKey::new(
            std_bootstrapping_key.input_lwe_dimension(),
            std_bootstrapping_key.glwe_size(),
            std_bootstrapping_key.polynomial_size(),
            std_bootstrapping_key.decomposition_base_log(),
            std_bootstrapping_key.decomposition_level_count(),
        );
    
        // Use the conversion function (a memory optimized version also exists but is more complicated
        // to use) to convert the standard bootstrapping key to the Fourier domain
        convert_standard_lwe_bootstrap_key_to_fourier(&std_bootstrapping_key, &mut fourier_bsk);
        // We don't need the standard bootstrapping key anymore
        drop(std_bootstrapping_key);
    
        // Our 4 bits message space
        let message_modulus = 1u64 << 4;
    
        // Our input message
        let input_message = 3u64;
    
        // Delta used to encode 4 bits of message + a bit of padding on u64
        let delta = (1_u64 << 63) / message_modulus;
    
        // Apply our encoding
        let plaintext = Plaintext(input_message * delta);
    
        // Allocate a new LweCiphertext and encrypt our plaintext
        let lwe_ciphertext_in: LweCiphertextOwned<u64> = allocate_and_encrypt_new_lwe_ciphertext(
            &small_lwe_sk,
            plaintext,
            lwe_modular_std_dev,
            &mut encryption_generator,
        );
    
        // Compute a cleartext multiplication by 2
        let mut cleartext_multiplication_ct = lwe_ciphertext_in.clone();
        println!("Performing cleartext multiplication...");
        lwe_ciphertext_cleartext_mul(
            &mut cleartext_multiplication_ct,
            &lwe_ciphertext_in,
            Cleartext(2),
        );
    
        // Decrypt the cleartext multiplication result
        let cleartext_multiplication_plaintext: Plaintext<u64> =
            decrypt_lwe_ciphertext(&small_lwe_sk, &cleartext_multiplication_ct);
    
        // Create a SignedDecomposer to perform the rounding of the decrypted plaintext
        // We pass a DecompositionBaseLog of 5 and a DecompositionLevelCount of 1 indicating we want to
        // round the 5 MSB, 1 bit of padding plus our 4 bits of message
        let signed_decomposer =
            SignedDecomposer::new(DecompositionBaseLog(5), DecompositionLevelCount(1));
    
        // Round and remove our encoding
        let cleartext_multiplication_result: u64 =
            signed_decomposer.closest_representable(cleartext_multiplication_plaintext.0) / delta;
    
        println!("Checking result...");
        assert_eq!(6, cleartext_multiplication_result);
        println!(
            "Cleartext multiplication result is correct! \
            Expected 6, got {cleartext_multiplication_result}"
        );
    
        // Now we will use a PBS to compute the same multiplication, it is NOT the recommended way of
        // doing this operation in terms of performance as it's much more costly than a multiplication
        // with a cleartext, however it resets the noise in a ciphertext to a nominal level and allows
        // to evaluate arbitrary functions so depending on your use case it can be a better fit.
    
        // Here we will define a helper function to generate an accumulator for a PBS
        fn generate_accumulator<F>(
            polynomial_size: PolynomialSize,
            glwe_size: GlweSize,
            message_modulus: usize,
            delta: u64,
            f: F,
        ) -> GlweCiphertextOwned<u64>
        where
            F: Fn(u64) -> u64,
        {
            // N/(p/2) = size of each block, to correct noise from the input we introduce the notion of
            // box, which manages redundancy to yield a denoised value for several noisy values around
            // a true input value.
            let box_size = polynomial_size.0 / message_modulus;
    
            // Create the accumulator
            let mut accumulator_u64 = vec![0_u64; polynomial_size.0];
    
            // Fill each box with the encoded denoised value
            for i in 0..message_modulus {
                let index = i * box_size;
                accumulator_u64[index..index + box_size]
                    .iter_mut()
                    .for_each(|a| *a = f(i as u64) * delta);
            }
    
            let half_box_size = box_size / 2;
    
            // Negate the first half_box_size coefficients to manage negacyclicity and rotate
            for a_i in accumulator_u64[0..half_box_size].iter_mut() {
                *a_i = (*a_i).wrapping_neg();
            }
    
            // Rotate the accumulator
            accumulator_u64.rotate_left(half_box_size);
    
            let accumulator_plaintext = PlaintextList::from_container(accumulator_u64);
    
            let accumulator =
                allocate_and_trivially_encrypt_new_glwe_ciphertext(glwe_size, &accumulator_plaintext);
    
            accumulator
        }
    
        // Generate the accumulator for our multiplication by 2 using a simple closure
        let accumulator: GlweCiphertextOwned<u64> = generate_accumulator(
            polynomial_size,
            glwe_dimension.to_glwe_size(),
            message_modulus as usize,
            delta,
            |x: u64| 2 * x,
        );
    
        // Allocate the LweCiphertext to store the result of the PBS
        let mut pbs_multiplication_ct =
            LweCiphertext::new(0u64, big_lwe_sk.lwe_dimension().to_lwe_size());
        println!("Computing PBS...");
        programmable_bootstrap_lwe_ciphertext(
            &lwe_ciphertext_in,
            &mut pbs_multiplication_ct,
            &accumulator,
            &fourier_bsk,
        );
    
        // Decrypt the PBS multiplication result
        let pbs_multipliation_plaintext: Plaintext<u64> =
            decrypt_lwe_ciphertext(&big_lwe_sk, &pbs_multiplication_ct);
    
        // Round and remove our encoding
        let pbs_multiplication_result: u64 =
            signed_decomposer.closest_representable(pbs_multipliation_plaintext.0) / delta;
    
        println!("Checking result...");
        assert_eq!(6, pbs_multiplication_result);
        println!(
            "Mulitplication via PBS result is correct! Expected 6, got {pbs_multiplication_result}"
        );
    }

    Operations

    hashtag
    How shortint is represented

    In shortint, the encrypted data is stored in an LWE ciphertext.

    Conceptually, the message stored in an LWE ciphertext is divided into a carry buffer and a message buffer.

    The message buffer is the space where the actual message is stored. This represents the modulus of the input messages (denoted by MessageModulus in the code). When doing computations on a ciphertext, the encrypted message can overflow the message modulus: the exceeding information is stored in the carry buffer. The size of the carry buffer is defined by another modulus, called CarryModulus.

    Together, the message modulus and the carry modulus form the plaintext space that is available in a ciphertext. This space cannot be overflowed, otherwise the computation may result in incorrect outputs.

    In order to ensure the correctness of the computation, we keep track of the maximum value encrypted in a ciphertext via an associated attribute called the degree. When the degree reaches a defined threshold, the carry buffer may be emptied to safely resume the computations. Therefore, in shortint the carry modulus is mainly considered as a means to do more computations.

    hashtag
    Types of operations

    The operations available via a ServerKey may come in different variants:

    • operations that take their inputs as encrypted values.

    • scalar operations that take at least one non-encrypted value as input.

    For example, the addition has both variants:

    • ServerKey::unchecked_add which takes two encrypted values and adds them.

    • ServerKey::unchecked_scalar_add which takes an encrypted value and a clear value (the so-called scalar) and adds them.

    Each operation may come in different 'flavors':

    • unchecked: Always does the operation, without checking if the result may exceed the capacity of the plaintext space. Using this operation might have an impact on the correctness of the following operations;

    • checked: Checks are done before computing the operation, returning an error if operation cannot be done safely;

    Not all operations have these 3 flavors, as some of them are implemented in a way that the operation is always possible without ever exceeding the plaintext space capacity.

    hashtag
    How to use operation types

    Let's try to do a circuit evaluation using the different flavours of operations we already introduced. For a very small circuit, the unchecked flavour may be enough to do the computation correctly. Otherwise, the checked and smart are the best options.

    As an example, let's do a scalar multiplication, a subtraction, and a multiplication.

    During this computation, the carry buffer has been overflowed and, as all the operations were unchecked, the output may be incorrect.

    If we redo this same circuit with the checked flavour, a panic will occur.

    Therefore, the checked flavour permits manual management of the overflow of the carry buffer by raising an error if the correctness is not guaranteed.

    Lastly, using the smart flavour will output the correct result all the time. However, the computation may be slower as the carry buffer may be cleaned during the computations.

    #List of available operations

    circle-exclamation

    Currently, certain operations can only be used if the parameter set chosen is compatible with the bivariate programmable bootstrapping, meaning the carry buffer is larger than or equal to the message buffer. These operations are marked with a star (*).

    The list of implemented operations for shortint is:

    • addition between two ciphertexts

    • addition between a ciphertext and an unencrypted scalar

    • comparisons <, <=, >

    In what follows, some simple code examples are given.

    hashtag
    Public key encryption.

    TFHE-rs supports both private and public key encryption methods. Note that the only difference between both lies into the encryption step: in this case, the encryption method is called using public_key instead of client_key.

    Here is a small example on how to use public encryption:

    In what follows, all examples are related to private key encryption.

    hashtag
    Arithmetic operations.

    Classical arithmetic operations are supported by shortint:

    hashtag
    bitwise operations

    Short homomorphic integer types support some bitwise operations.

    A simple example on how to use these operations:

    hashtag
    comparisons

    Short homomorphic integer types support comparison operations.

    A simple example on how to use these operations:

    hashtag
    univariate function evaluations

    A simple example on how to use this operation to homomorphically compute the hamming weight (i.e., the number of bits equal to one) of an encrypted number.

    hashtag
    bi-variate function evaluations

    Using the shortint types offers the possibility to evaluate bi-variate functions, i.e., functions that takes two ciphertexts as input. This requires choosing a parameter set such that the carry buffer size is at least as large as the message one i.e., PARAM_MESSAGE_X_CARRY_Y with X <= Y.

    Here is a simple code example:

    smart: Always does the operation - if the operation cannot be computed safely, the smart operation will clear the carry modulus to make the operation possible.
    ,
    >=
    ,
    ==
    between a ciphertext and an unencrypted scalar
  • division of a ciphertext by an unencrypted scalar

  • LSB multiplication between two ciphertexts returning the result truncated to fit in the message buffer

  • multiplication of a ciphertext by an unencrypted scalar

  • bitwise shift <<, >>

  • subtraction of a ciphertext by another ciphertext

  • subtraction of a ciphertext by an unencrypted scalar

  • negation of a ciphertext

  • bitwise and, or and xor (*)

  • comparisons <, <=, >, >=, == between two ciphertexts (*)

  • division between two ciphertexts (*)

  • MSB multiplication between two ciphertexts returning the part overflowing the message buffer (*)

  • use tfhe::shortint::prelude::*;
    
    
    fn main() {
        // We generate a set of client/server keys, using the default parameters:
        let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
    
        let msg1 = 3;
        let msg2 = 3;
        let scalar = 4;
    
        let modulus = client_key.parameters.message_modulus.0;
    
        // We use the client key to encrypt two messages:
        let mut ct_1 = client_key.encrypt(msg1);
        let ct_2 = client_key.encrypt(msg2);
    
        server_key.unchecked_scalar_mul_assign(&mut ct_1, scalar);
        server_key.unchecked_sub_assign(&mut ct_1, &ct_2);
        server_key.unchecked_mul_lsb_assign(&mut ct_1, &ct_2);
    
        // We use the client key to decrypt the output of the circuit:
        let output = client_key.decrypt(&ct_1);
        println!("expected {}, found {}", ((msg1 * scalar as u64 - msg2) * msg2) % modulus as u64, output);
    }
    use tfhe::shortint::prelude::*;
    
    use std::error::Error;
    
    fn main() {
        // We generate a set of client/server keys, using the default parameters:
        let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
    
        let msg1 = 3;
        let msg2 = 3;
        let scalar = 4;
    
        let modulus = client_key.parameters.message_modulus.0;
    
        // We use the client key to encrypt two messages:
        let mut ct_1 = client_key.encrypt(msg1);
        let ct_2 = client_key.encrypt(msg2);
    
        let mut ops = || -> Result<(), Box<dyn Error>> {
            server_key.checked_scalar_mul_assign(&mut ct_1, scalar)?;
            server_key.checked_sub_assign(&mut ct_1, &ct_2)?;
            server_key.checked_mul_lsb_assign(&mut ct_1, &ct_2)?;
            Ok(())
        };
    
        match ops() {
            Ok(_) => (),
            Err(e) => {
                println!("correctness of operations is not guaranteed due to error: {}", e);
                return;
            },
        }
    
        // We use the client key to decrypt the output of the circuit:
        let output = client_key.decrypt(&ct_1);
        assert_eq!(output, ((msg1 * scalar as u64 - msg2) * msg2) % modulus as u64);
    }
    use tfhe::shortint::prelude::*;
    
    
    fn main() {
        // We generate a set of client/server keys, using the default parameters:
        let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
    
        let msg1 = 3;
        let msg2 = 3;
        let scalar = 4;
    
        let modulus = client_key.parameters.message_modulus.0;
    
        // We use the client key to encrypt two messages:
        let mut ct_1 = client_key.encrypt(msg1);
        let mut ct_2 = client_key.encrypt(msg2);
    
        server_key.smart_scalar_mul_assign(&mut ct_1, scalar);
        server_key.smart_sub_assign(&mut ct_1, &mut ct_2);
        server_key.smart_mul_lsb_assign(&mut ct_1, &mut ct_2);
    
        // We use the client key to decrypt the output of the circuit:
        let output = client_key.decrypt(&ct_1);
        assert_eq!(output, ((msg1 * scalar as u64 - msg2) * msg2) % modulus as u64);
    }
    use tfhe::shortint::prelude::*;
    
    fn main() {
        // Generate the client key and the server key:
        let (cks, _) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
        let pks = PublicKey::new(&cks);
    
        let msg = 2;
        // Encryption of one message:
        let ct = pks.encrypt(msg);
        // Decryption:
        let dec = cks.decrypt(&ct);
        assert_eq!(dec, msg);
    }
    use tfhe::shortint::prelude::*;
    
    fn main() {
        // We generate a set of client/server keys to compute over Z/2^2Z, with 2 carry bits
        let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
    
        let msg1 = 2;
        let msg2 = 1;
    
        let modulus = client_key.parameters.message_modulus.0;
    
        // We use the private client key to encrypt two messages:
        let ct_1 = client_key.encrypt(msg1);
        let ct_2 = client_key.encrypt(msg2);
    
        // We use the server public key to execute an integer circuit:
        let ct_3 = server_key.unchecked_add(&ct_1, &ct_2);
    
        // We use the client key to decrypt the output of the circuit:
        let output = client_key.decrypt(&ct_3);
        assert_eq!(output, (msg1 + msg2) % modulus as u64);
    }
    use tfhe::shortint::prelude::*;
    
    fn main() {
        // We generate a set of client/server keys to compute over Z/2^2Z, with 2 carry bits
        let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
    
        let msg1 = 2;
        let msg2 = 1;
    
        let modulus = client_key.parameters.message_modulus.0;
    
        // We use the private client key to encrypt two messages:
        let ct_1 = client_key.encrypt(msg1);
        let ct_2 = client_key.encrypt(msg2);
    
        // We use the server public key to homomorphically compute a bitwise AND:
        let ct_3 = server_key.unchecked_bitand(&ct_1, &ct_2);
    
        // We use the client key to decrypt the output of the circuit:
        let output = client_key.decrypt(&ct_3);
        assert_eq!(output, (msg1 & msg2) % modulus as u64);
    }
    use tfhe::shortint::prelude::*;
    
    fn main() {
        // We generate a set of client/server keys to compute over Z/2^2Z, with 2 carry bits
        let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
    
        let msg1 = 2;
        let msg2 = 1;
    
        let modulus = client_key.parameters.message_modulus.0;
    
        // We use the private client key to encrypt two messages:
        let ct_1 = client_key.encrypt(msg1);
        let ct_2 = client_key.encrypt(msg2);
    
        // We use the server public key to execute an integer circuit:
        let ct_3 = server_key.unchecked_greater_or_equal(&ct_1, &ct_2);
    
        // We use the client key to decrypt the output of the circuit:
        let output = client_key.decrypt(&ct_3);
        assert_eq!(output, (msg1 >= msg2) as u64 % modulus as u64);
    }
    use tfhe::shortint::prelude::*;
    
    fn main() {
        // We generate a set of client/server keys to compute over Z/2^2Z, with 2 carry bits
        let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
    
        let msg1 = 3;
    
        let modulus = client_key.parameters.message_modulus.0;
    
        // We use the private client key to encrypt two messages:
        let ct_1 = client_key.encrypt(msg1);
    
        //define the accumulator as the
        let acc = server_key.generate_accumulator(|n| n.count_ones().into());
    
        // add the two ciphertexts
        let ct_res = server_key.keyswitch_programmable_bootstrap(&ct_1, &acc);
    
    
        // We use the client key to decrypt the output of the circuit:
        let output = client_key.decrypt(&ct_res);
        assert_eq!(output, msg1.count_ones() as u64);
    }
    use tfhe::shortint::prelude::*;
    
    fn main() {
        // We generate a set of client/server keys to compute over Z/2^2Z, with 2 carry bits
        let (client_key, server_key) = gen_keys(PARAM_MESSAGE_2_CARRY_2);
    
        let msg1 = 3;
        let msg2 = 2;
    
        let modulus = client_key.parameters.message_modulus.0 as u64;
    
        // We use the private client key to encrypt two messages:
        let ct_1 = client_key.encrypt(msg1);
        let ct_2 = client_key.encrypt(msg2);
    
        // Compute the accumulator for the bivariate functions
        let acc = server_key.generate_accumulator_bivariate(|x,y| (x.count_ones()
            + y.count_ones()) as u64 % modulus );
    
        let ct_res = server_key.keyswitch_programmable_bootstrap_bivariate(&ct_1, &ct_2, &acc);
    
        // We use the client key to decrypt the output of the circuit:
        let output = client_key.decrypt(&ct_res);
        assert_eq!(output, (msg1.count_ones() as u64 + msg2.count_ones() as u64) % modulus);
    }