Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
This library makes it possible to execute homomorphic operations over encrypted data, where the data are either Booleans, short integers (named shortint in the rest of this documentation), or integers up to 256 bits. It allows you 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. Then the user can decrypt it with the secret key
.
The overall process to write an homomorphic program is the same for all types. The basic steps for using the TFHE-rs library are the following:
Choose a data type (Boolean, shortint, integer)
Import the library
Create client and server keys
Encrypt data with the client key
Compute over encrypted data using the server key
Decrypt data with the client key
This library has different modules, with different levels of abstraction.
There is the core_crypto module, which is the lowest level API with the primitive functions and types of the TFHE scheme.
Above the core_crypto module, there are the Boolean, shortint, and integer modules, which simply allow evaluation of Boolean, short integer, and integer circuits.
Finally, there is the high-level module built on top of the Boolean, shortint, integer modules. This module is meant to abstract cryptographic complexities: no cryptographical knowledge is required to start developing an FHE application. Another benefit of the high-level module is the drastically simplified development process compared to lower level modules.
TFHE-rs exposes a high-level API by default that includes datatypes that try to match Rust's native types by having overloaded operators (+, -, ...).
Here is an example of how the high-level API is used:
Use the --release
flag to run this example (eg: cargo run --release
)
Here is an example of how the library can be used to evaluate a Boolean circuit:
Use the --release
flag to run this example (eg: cargo run --release
)
Here is a full example using shortint:
Use the --release
flag to run this example (eg: cargo run --release
)
Use the --release
flag to run this example (eg: cargo run --release
)
The library is simple to use and can evaluate homomorphic circuits of arbitrary length. The description of the algorithms can be found in the TFHE paper (also available as ePrint 2018/421).
To use TFHE-rs
in your project, you first need to add it as a dependency in your Cargo.toml
:
When running code that uses tfhe-rs
, it is highly recommended to run in release mode with cargo's --release
flag to have the best performances possible, eg: cargo run --release
.
TFHE-rs
exposes different cargo features
to customize the types and features used.
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) |
---|---|---|
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.
TFHE-rs is supported on Linux (x86, aarch64), macOS (x86, aarch64) and Windows (x86 with RDSEED
instruction).
Users who have ARM devices can use TFHE-rs
by compiling using the nightly
toolchain.
Install the needed Rust toolchain:
Then, you can either:
Manually specify the toolchain to use in each of the cargo commands:
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:
TFHE-rs is a cryptographic library dedicated to Fully Homomorphic Encryption. As its name suggests, it is based on the TFHE scheme.
It is necessary to understand some basics about TFHE to comprehend where the limitations are coming from, both in terms of precision (number of bits used to represent plaintext values) and execution time (why TFHE operations are slower than native operations).
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.
A LWE ciphertext is composed of two parts:
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, let's review the example of the addition between ciphertexts to illustrate why it is slower to compute over encrypted data.
To add two ciphertexts, we must add their $mask$ and $body$:
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, noise must be tracked and managed to guarantee the correctness of the computation.
Bootstrapping operations are used across the computation to decrease noise within the ciphertexts, preventing it from tampering the message. The rest of the operations are called leveled because they do not need bootstrapping operations and are usually really fast as a result.
The following sections explain the concept of noise and padding in ciphertexts.
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 more secure the encryption, the larger the standard deviation.
In TFHE-rs
, noise is encoded in the least significant bits of the plaintexts. Each leveled computation increases the noise. 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.
Since encoded values have a fixed precision, operating on them can 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 TFHE Deep Dive.
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 (repository) with red_cost_model = reduction.RC.BDGL16
.
The list of supported operations by the homomorphic Booleans is:
Operation Name | type |
---|
A walk-through using homomorphic Booleans can be found .
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 |
---|
The division operation implements a subtlety: since data is encrypted, it might be possible to compute a division by 0. The division is tweaked so that dividing by 0 returns 0.
The list of supported operations is:
Due to their nature, homomorphic operations are naturally slower than their clear equivalent. Some timings are exposed for basic operations. For completeness, benchmarks for other libraries are also given.
All benchmarks were launched on an AWS m6i.metal with the following specifications: Intel(R) Xeon(R) Platinum 8375C CPU @ 2.90GHz and 512GB of RAM.
This measures the execution time of a single binary Boolean gate.
Parameter set | Concrete FFT | Concrete FFT + avx512 |
---|
Parameter set | fftw | spqlios-fma |
---|
Parameter set | GINX | GINX (Intel HEXL) |
---|
This measures the execution time for some operations and some parameter sets of tfhe-rs::shortint.
This uses the Concrete FFT + avx512 configuration.
Next, the timings for the operation flavor default
are given. This flavor ensures predictable timings of an operation all along the circuit by clearing the carry space after each operation.
This measures the execution time for some operation sets of tfhe-rs::integer.
All timings are related to parallelized Radix-based integer operations, where each block is encrypted using PARAM_MESSAGE_2_CARRY_2. To ensure predictable timings, the operation flavor is the default
one: a carry propagation is computed after each operation. Operation cost could be reduced by using unchecked
, checked
, or smart
.
📁 | 💛 | 🟨
TFHE-rs is a pure Rust implementation of TFHE for Boolean and 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 worrying 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.
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.
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)
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
This library is meant to be used both on the server side and the client side. The typical use case should follow the subsequent steps:
On the client side, generate the client
and server keys
.
Send the server key
to the server.
Then any number of times:
On the client side, encrypt the input data with the client key
.
Transmit the encrypted input to the server.
On the server side, perform homomorphic computation with the server key
.
Transmit the encrypted output to the client.
On the client side, decrypt the output data with the client key
.
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. To store the server_key
in a binary file, you can use the bincode
library:
Once the server key is available on the server side, it is possible to perform some homomorphic computations. The client 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:
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:
Once the encrypted inputs are on the server side, the server_key
can be used to homomorphically execute the desired Boolean circuit:
Once the encrypted output is on the client side, the client_key
can be used to decrypt it:
As explained in the Introduction, most types 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
uses the framework. Serde's Serialize
and Deserialize
functions are implemented on TFHE's types.
To serialize our data, a should be picked. Here, is a good choice, mainly because it is a binary format.
In tfhe::boolean, the available operations are mainly related to their equivalent Boolean gates (i.e., AND, OR... etc). What follows are examples of a unary gate (NOT) and a binary gate (XOR). The last one is about the ternary MUX gate, which allows homomorphic computation of conditional statements of the form If..Then..Else
.
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:
The TFHE cryptographic scheme relies on a variant of and is based on a problem so difficult that it is even post-quantum resistant.
Some cryptographic parameters will require tuning to ensure both the correctness of the result and the security of the computation.
To make it simpler, we've provided 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 (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.
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 when computing a programmable bootstrapping (i.e., any gates but the not
). The other one is closer to the error probability claimed in the original , namely , but it is up-to-date regarding security requirements.
The following array summarizes this:
Parameter set | Error probability |
---|
You can also create your own set of parameters. This is an unsafe
operation as failing to properly fix the parameters will result in an incorrect and/or insecure computation:
The structure and operations related to all types (ì.e., Booleans, shortint and integer) are described in this section.
Native homomorphic Booleans support common Boolean operations.
The list of supported operations is:
name | symbol | type |
---|
Native small homomorphic integer types (e.g., FheUint3 or FheUint4) easily compute various operations. In general, computing over encrypted data is as easy as computing over clear data, since the same operation symbol is used. The addition between two ciphertexts is done using the symbol +
between two FheUint. Many operations can be computed between a clear value (i.e. a scalar) and a ciphertext.
In Rust native types, any operation is modular. In Rust, u8
, computations are done modulus 2^8. The similar idea is applied for FheUintX, where operations are done modulus 2^X. In the type FheUint3, operations are done modulo 8.
Small homomorphic integer types support all common arithmetic operations, meaning +
, -
, x
, /
, mod
.
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.
The list of supported operations is:
A simple example on how to use these operations:
Small homomorphic integer types support some bitwise operations.
The list of supported operations is:
A simple example on how to use these operations:
Small homomorphic integer types support comparison operations.
Due to some Rust limitations, it is not possible to overload the comparison symbols because of the inner definition of the operations. Rust expects to have a Boolean as an output, whereas a ciphertext encrypted result is returned when using homomorphic types.
You will need to use the different methods instead of using symbols for the comparisons. These methods follow the same naming conventions as the two standard Rust traits:
A simple example on how to use these operations:
The shortint type also supports the computation of univariate functions, which deep down uses TFHE's programmable bootstrapping.
A simple example on how to use these operations:
Using the shortint type allows you to evaluate bivariate functions (i.e., functions that takes two ciphertexts as input).
A simple code example:
In TFHE-rs, integers are used to encrypt any messages larger than 4 bits. All supported operations are listed below.
Homomorphic integer types support arithmetic operations.
The list of supported operations is:
A simple example on how to use these operations:
Homomorphic integer types support some bitwise operations.
The list of supported operations is:
A simple example on how to use these operations:
Homomorphic integers support comparison operations. Since Rust does not allow the overloading of these operations, a simple function has been associated to each one.
The list of supported operations is:
A simple example on how to use these operations:
Homomorphic integers support the min/max operations.
A simple example on how to use these operations:
The basic steps for using the high-level API of TFHE-rs are:
Importing TFHE-rs prelude;
Client-side: Configuring and creating keys;
Client-side: Encrypting data;
Server-side: Setting the server key;
Server-side: Computing over encrypted data;
Client-side: Decrypting data.
Here is the full example (mixing client and server parts):
Default configuration for x86 Unix machines:
tfhe
uses traits
to have a consistent API for creating FHE types and enable users to write generic functions. To be able to use associated functions and methods of a trait, the trait has to be in scope.
To make it easier, the prelude
'pattern' is used. All tfhe
important traits are in a prelude
module that you glob import. With this, there is no need to remember or know the traits to import.
The first step is the creation of the configuration. The configuration is used to declare which type you will use or not use, as well as enabling you to use custom crypto-parameters for these types for more advanced usage / testing.
Creating a configuration is done using the ConfigBuilder type.
The config is done by first creating a builder with all types deactivated. Then, the uint8
type with default parameters is activated.
The generate_keys
command returns a client key and a server key.
The client_key
is meant to stay private and not leave the client whereas the server_key
can be made public and sent to a server for it to enable FHE computations.
The next step is to call set_server_key
This function will move the server key to an internal state of the crate and manage the details to give a simpler interface.
Encrypting data is done via the encrypt
associated function of the [FheEncrypt] trait.
Types exposed by this crate implement at least one of [FheEncrypt] or [FheTryEncrypt] to allow enryption.
Computations should be as easy as normal Rust to write, thanks to operator overloading.
The decryption is done by using the decrypt
method, which comes from the [FheDecrypt] trait.
The goal of this tutorial is to build a data type that represents a Latin string in FHE while implementing the to_lower
and to_upper
functions.
The allowed characters in a Latin string are:
Uppercase letters: A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Lowercase letters: a b c d e f g h i j k l m n o p q r s t u v w x y z
For the code point of the letters,ascii
codes are used:
The uppercase letters are in the range [65, 90]
The lowercase letters are in the range [97, 122]
lower_case
= upper_case
+ 32 <=> upper_case
= lower_case
- 32
For this type, the FheUint8
type is used.
This type will hold the encrypted characters as a Vec<FheUint8>
, as well as the encrypted constant 32
to implement the functions that change the case.
In the FheLatinString::encrypt
function, some data validation is done:
The input string can only contain ascii letters (no digit, no special characters).
The input string cannot mix lower and upper case letters.
These two points are to work around a limitation of FHE. It is not possible to create branches, meaning the function cannot use conditional statements. Checking if the 'char' is an uppercase letter to modify it to a lowercase one cannot be done, like in the example below.
With these preconditions checked, implementing to_lower
and to_upper
is rather simple.
To use the FheUint8
type, the integer
feature must be activated:
This example is dedicated to the building of a small function that homomorphically computes a parity bit.
First, a non-generic function is written. Then, generics are used to handle the case where the function inputs are both FheBool
s and clear bool
s.
The parity bit function takes as input two parameters:
A slice of Boolean
A mode (Odd
or Even
)
This function returns a Boolean that will be either true
or false
so that the sum of Booleans (in the input and the returned one) is either an Odd
or Even
number, depending on the requested mode.
To use Booleans, the booleans
feature in our Cargo.toml must be enabled:
First, the verification function is defined.
The way to find the parity bit is to initialize it to false, then
XOR
it with all the bits, one after the other, adding negation depending on the requested mode.
A validation function is also defined to sum together the number of the bit set within the input with the computed parity bit and check that the sum is an even or odd number, depending on the mode.
After the mandatory configuration steps, the function is called:
To make the compute_parity_bit
function compatible with both FheBool
and bool
, generics have to be used.
Writing a generic function that accepts FHE
types as well as clear types can help test the function to see if it is correct. If the function is generic, it can run with clear data, allowing the use of print-debugging or a debugger to spot errors.
Writing generic functions that use operator overloading for our FHE types can be trickier than normal, since FHE
types are not copy. So using the reference &
is mandatory, even though this is not the case when using native types, which are all Copy
.
This will make the generic bounds trickier at first.
The function has the following signature:
To make it generic, the first step is:
Next, the generic bounds have to be defined with the where
clause.
In the function, the following operators are used:
!
(trait: Not
)
^
(trait: BitXor
)
By adding them to where
, this gives:
However, the compiler will complain:
fhe_bit
is a reference to a BoolType
(&BoolType
) since it is borrowed from the fhe_bits
slice when iterating over its elements. The first try is to change the BitXor
bounds to what the Compiler suggests by requiring &BoolType
to implement BitXor
and not BoolType
.
The Compiler is still not happy:
The way to fix this is to use Higher-Rank Trait Bounds
:
The final code will look like this:
Here is a complete example that uses this function for both clear and FHE values:
OS | x86 | aarch64 |
---|---|---|
An LWE secret key is a list of n
random integers: . is called the
The mask
The body
To add ciphertexts, it is sufficient to add their masks and bodies. Instead of just adding two 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 Programmable Bootstrapping).
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 (i.e., the multiplication of two ciphertexts).
In public key encryption, the public key contains a given number of ciphertexts all encrypting the value 0. By setting the number of encryptions to 0 in the public key at , where is the LWE dimension, is the ciphertext modulus, and is the number of security bits. This construction is secure due to the leftover hash lemma, which relates to the impossibility of breaking the underlying multiple subset sum problem. This guarantees both a high-density subset sum and an exponentially large number of possible associated random vectors per LWE sample (a,b).
A walk-through example can be found , and more examples and explanations can be found .
In TFHE-rs, integers represent unsigned integers up to 256 bits. They are encoded using Radix representations by default (more details ).
Operation name | Type |
---|
A walk-through example can be found .
Parameter set | unchecked_add | unchecked_mul_lsb | keyswitch_programmable_bootstrap |
---|
Parameter set | add | mul_lsb | keyswitch_programmable_bootstrap |
---|
Plaintext size | add | mul | greater_than (gt) | min |
---|
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 .
If you would like to know more about the problems that FHE solves, we suggest you review our .
name | symbol | type |
---|
name | symbol | type |
---|
name | symbol | type |
---|
name | symbol | type |
---|
name | symbol | type |
---|
name | symbol | type |
---|
Other configurations can be found .
In this example, 8-bit unsigned integers with default parameters are used. The integers
feature must also be enabled, as per the table on the .
Other configurations can be found .
Other configurations can be found .
Booleans
boolean
Booleans
ShortInts
shortint
Short unsigned integers
Integers
integer
Arbitrary-sized unsigned integers
Linux
x86_64-unix
aarch64-unix
*
macOS
x86_64-unix
aarch64-unix
*
Windows
x86_64
Unsupported
Negation | Unary |
Addition | Binary |
Subtraction | Binary |
Multiplication | Binary |
Bitwise OR, AND, XOR | Binary |
Equality | Binary |
Left/Right Shift | Binary |
Comparisons | Binary |
Min, Max | Binary |
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 | 3.06 µs | 134 ms | 129.4 ms |
PARAM_MESSAGE_4_CARRY_4 | 11.7 µs | 854 ms | 828.1 ms |
PARAM_MESSAGE_1_CARRY_1 | 7.90 ms | 8.00 ms | 8.10 ms |
PARAM_MESSAGE_2_CARRY_2 | 18.4 ms | 18.1 ms | 18.4 ms |
PARAM_MESSAGE_3_CARRY_3 | 131.5 ms | 129.5 ms | 129.4 ms |
PARAM_MESSAGE_4_CARRY_4 | 852.5 ms | 839.7 ms | 828.1 ms |
8 bits | 129.0 ms | 227.2 ms | 111.9 ms | 186.8 ms |
16 bits | 256.3 ms | 756.0 ms | 145.3 ms | 233.1 ms |
32 bits | 469.4 ms | 2.10 s | 192.0 ms | 282.9 ms |
40 bits | 608.0 ms | 3.37 s | 228.4 ms | 318.6 ms |
64 bits | 959.9 ms | 5.53 s | 249.0 ms | 336.5 ms |
128 bits | 1.88 s | 14.1 s | 294.7 ms | 398.6 ms |
256 bits | 3.66 s | 29.2 s | 361.8 ms | 509.1 ms |
Greater than |
| Binary |
Greater or equal than |
| Binary |
Lower than |
| Binary |
Lower or equal than |
| Binary |
Equal |
| Binary |
Min |
| Binary |
Max |
| Binary |
| Unary |
| Binary |
| Binary |
| Binary |
| Binary |
| Binary |
| Ternary |
Negation | Unary |
Addition | Binary |
Subtraction | Binary |
Multiplication | Binary |
Division* | Binary |
Modular reduction | Binary |
Comparisons | Binary |
Left/Right Shift | Binary |
And | Binary |
Or | Binary |
Xor | Binary |
Exact Function Evaluation | Unary/Binary |
The steps to homomorphically evaluate a circuit are described below.
tfhe::shortint
provides 3 key types:
ClientKey
ServerKey
PublicKey
The ClientKey
is the key that encrypts and decrypts messages (integer values up to 8 bits here). It 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. Most importantly, it contains 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
.
Computation/operation methods are tied to the ServerKey
type.
The PublicKey
is the key used to encrypt messages. It can be publicly shared to allow users to encrypt data such that only the ClientKey
holder will be able to decrypt. Encrypting with the PublicKey
does not alter the homomorphic capabilities associated to the ServerKey
.
Once the keys have been generated, the client key is used to encrypt data:
Once the keys have been generated, the client key is used to encrypt data:
With the server_key
, addition is now possible over encrypted values. The resulting plaintext is recovered after the decryption with the secret client key.
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 serde framework. Serde's Serialize and Deserialize are then implemented on tfhe::shortint's types.
To serialize the data, we need to pick a data format. For our use case, bincode is a good choice, mainly because it is binary format.
All parameter sets provide at least 128-bits of security according to the Lattice-Estimator, with an error probability equal to when computing using programmable bootstrapping. This error probability is due to the randomness added at each encryption (see here for more details about the encryption process).
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.
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
.
This example contains keys that are generated to have messages encoded over 2 bits (i.e., computations are done modulus ) with 2 bits of carry.
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.
As shown here, the choice of the parameter set impacts the operations available and their efficiency.
The computations of bi-variate functions is based on a trick: concatenating two ciphertexts into one. Where the carry buffer is not at least as large as the message one, this trick no longer works. Many bi-variate operations, such as comparisons, then cannot be correctly computed. The only exception concerns multiplication.
In the case of 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 method. 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 slower than using the other one. Using the smart
version of the multiplication automatically chooses which algorithm is used depending on the chosen parameters.
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:
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:
The steps to homomorphically evaluate an integer circuit are described here.
integer
provides 3 basic key types:
ClientKey
ServerKey
PublicKey
The ClientKey
is the key that encrypts and decrypts messages, 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 a bootstrapping key and a keyswitching key. This key is created from a ClientKey
that needs to be shared to the server, so 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.
The PublicKey
is a key used to encrypt messages. It can be publicly shared to allow users to encrypt data such that only the ClientKey
holder will be able to decrypt. Encrypting with the PublicKey
does not alter the homomorphic capabilities associated to the ServerKey
.
To generate the keys, a user needs two parameters:
A set of shortint
cryptographic parameters.
The number of ciphertexts used to encrypt an integer (we call them "shortint blocks").
We are now going to build a pair of keys that can encrypt an 8-bit integer by using 4 shortint blocks that store 2 bits of message each.
Once we have our keys, we can encrypt values:
Once the client key is generated, the public key can be derived and used to encrypt data.
With our server_key
, and encrypted values, we can now do an addition and then decrypt the result.
There are two ways to contribute to TFHE-rs. You can:
open issues to report bugs and typos and to suggest ideas;
ask to become an official contributor by emailing hello@zama.ai. Only approved contributors can send pull requests, so get in touch before you do.
DEFAULT_PARAMETERS |
TFHE_LIB_PARAMETERS |
| Binary |
| Binary |
| Binary |
| Unary |
| Binary |
| Binary |
| Binary |
| Binary |
| Binary |
| Unary |
| Binary |
| Binary |
| Binary |
| Binary |
| Binary |
| Binary |
| Binary |
| Binary |
| Unary |
| Binary |
| Binary |
| Binary |
| Binary |
| Binary |
The structure and operations related to the integers are described in this section.
In integer
, the encrypted data is split amongst many ciphertexts encrypted with the shortint
library. Below is a scheme representing an integer composed by k shortint ciphertexts.
This crate implements two ways to represent an integer:
the Radix representation
the CRT (Chinese Reminder Theorem) representation
The first possibility to represent a large integer is to use a Radix-based decomposition on the plaintexts. Let be a basis such that the size of is smaller than (or equal to) 4 bits. Then, an integer can be written as , where each is strictly smaller than . Each is then independently encrypted. In the end, an Integer ciphertext is defined as a set of shortint ciphertexts.
The definition of an integer requires a basis and a number of blocks. This is done at key generation. Below, the keys are dedicated to unsigned integers encrypting messages over 8 bits, using a basis over 2 bits (i.e., ) and 4 blocks.
In this representation, the correctness of operations requires to propagate the carries between the ciphertext. This operation is costly since it relies on the computation of many programmable bootstrapping operations over shortints.
The second approach to represent large integers is based on the Chinese Remainder Theorem. In this case, the basis is composed of several integers , such that there are pairwise coprime, and each has a size smaller than 4 bits. The CRT-based integer are defined modulus . For an integer , its CRT decomposition is simply defined as . Each part is then encrypted as a shortint ciphertext. In the end, an Integer ciphertext is defined as a set of shortint ciphertexts.
In the following example, the chosen basis is . The integer is defined modulus . There is no need to pre-size the number of blocks since it is determined from the number of values composing the basis. Here, the integer is split over three blocks.
This representation has many advantages: no carry propagation is required, cleaning the carry buffer of each ciphertext block is enough. This implies that operations can easily be parallelized. It also allows the efficient computation of PBS in the case where the function is CRT-compliant.
A variant of the CRT is proposed, where each block might be associated to a different key couple. In the end, a keychain to the computations is required, but performance might be improved.
The list of operations available in integer
depends on the type of representation:
Much like shortint
, the operations available via a ServerKey
may come in different variants:
operations that take their inputs as encrypted values.
scalar operations 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.
checked
: Checks are done before computing the operation, returning an error if operation cannot be done safely.
smart
: Always does the operation, if the operation cannot be computed safely, the smart operation will propagate the carry buffer to make the operation possible.
default
: Always compute the operation and always clear the carry. Could be slower than smart, but ensure that the timings are consistent from one call to another.
Not all operations have these 4 flavors, as some of them are implemented in a way that the operation is always possible without ever exceeding the plaintext space capacity.
Let's try to do a circuit evaluation using the different flavors of already introduced operations. For a very small circuit, the unchecked
flavor may be enough to do the computation correctly. Otherwise, checked
and smart
are the best options.
As an example, let's do a scalar multiplication, a subtraction, and an addition.
During this computation the carry buffer has been overflowed, and the output may be incorrect as all the operations were unchecked
.
If the same circuit is done but using the checked
flavor, a panic will occur:
The checked
flavor permits the manual management of the overflow of the carry buffer by raising an error if correctness is not guaranteed.
Using the smart
flavor will output the correct result all the time. However, the computation may be slower as the carry buffer may be propagated during the computations.
The main advantage of the default flavor is to ensure predictable timings, as long as only this kind of operation is used. Only the parallelized version of the operations is provided.
Using default
could slow down computations.
The structure and the operations related to the short integers are described in this section.
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 track 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. In shortint
the carry modulus is considered useful as a means to do more computations.
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;
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;
default
: Always does the operation and always clears the carry. Could be slower than smart, but it ensures that the timings are consistent from one call to another.
Not all operations have these 4 flavors, as some of them are implemented in a way that the operation is always possible without ever exceeding the plaintext space capacity.
Let's try to do a circuit evaluation using the different flavors of operations we already introduced. For a very small circuit, the unchecked
flavour may be enough to do the computation correctly. Otherwise,checked
and smart
are the best options.
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
flavor, a panic will occur:
The checked
flavor permits manual management of the overflow of the carry buffer by raising an error if correctness is not guaranteed.
Using the smart
flavor will output the correct result all the time. However, the computation may be slower as the carry buffer may be cleaned during the computations.
The main advantage of the default flavor is to ensure predictable timings as long as only this kind of operation is used.
Using default
could slow-down computations.
#List of available operations
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 <
, <=
, >
, >=
, ==
, !=
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
(*)
TFHE-rs supports both private and public key encryption methods. The only difference between both lies in 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:
Classical arithmetic operations are supported by shortint:
Short homomorphic integer types support some bitwise operations.
A simple example on how to use these operations:
Short homomorphic integer types support comparison operations.
A simple example on how to use these operations:
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.
Using the shortint types offers the possibility to evaluate bi-variate functions, or functions that take two ciphertexts as input. This requires choosing a parameter set such that the carry buffer size is at least as large as the message (i.e., PARAM_MESSAGE_X_CARRY_Y with X <= Y).
Here is a simple code example:
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 parameter sets are virtually unusable.
To build the JS on WASM bindings for TFHE-rs, you need to install in addition to a compatible (>= 1.65) .
In a shell, then 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.
Be sure to update the path of the required clause in the example below for the TFHE package that was just built.
integer
does not come with its own set of parameters. Instead, it relies on parameters from shortint
. Currently, parameter sets having the same space dedicated to the message and the carry (i.e. PARAM_MESSAGE_{X}_CARRY_{X}
with X
in [1,4]) are recommended. See for more details about cryptographic parameters, and to see how to properly instantiate integers depending on the chosen representation.
#Using the High-level C API
This library exposes a C binding to the high-level TFHE-rs primitives to implement Fully Homomorphic Encryption (FHE) programs.
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:
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 to do just that:
TFHE-rs 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:
As explained in the introduction, some types (Serverkey
, Ciphertext
) are meant to be shared with the server that does the computations.
The easiest way to send these data to a server is to use the serialization and deserialization features. TFHE-rs uses the serde framework, so serde's Serialize and Deserialize are implemented.
To be able to serialize our data, a needs to be picked. Here, is a good choice, mainly because it is binary format.
This library exposes a C binding to the TFHE-rs shortint API to implement Fully Homomorphic Encryption (FHE) programs.
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 to do just that:
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:
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 entity definitions and another focused on algorithms. 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.
The API is convenient to easily add or modify existing algorithms or to have direct access to the raw data. Even if the LWE ciphertext object is defined along with functions giving access to the body, this is also possible to bypass these to get directly the element of LWE mask.
For instance, the code to encrypt and then decrypt a message looks like:
core_crypto
primitivesWelcome to this tutorial about TFHE-rs core_crypto
module.
core_crypto
moduleTo use TFHE-rs
, first it has to be added as a dependency in the Cargo.toml
:
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 activated 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. 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:
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 then using a PBS.
Operation name | Radix-based | CRT-based |
---|---|---|
The example.js
script can then be run using , like so:
Negation
Addition
Scalar Addition
Subtraction
Scalar Subtraction
Multiplication
Scalar Multiplication
Bitwise OR, AND, XOR
Equality
Left/Right Shift
Comparisons <
,<=
,>
, >=
Min, Max