Pyfhel¶
- class Pyfhel.Pyfhel(context_params=None, key_gen=False, pub_key_file=None, sec_key_file=None)¶
Bases:
object
Context class encapsulating most of the Homomorphic Encryption functionalities.
Encrypted addition, multiplication, substraction, exponentiation of integers/doubles. Implementation of homomorphic encryption using SEAL/PALISADE as backend. Pyfhel works with PyPtxt as plaintext class and PyCtxt as cyphertext class.
- __init__()¶
Initializes an empty Pyfhel object, the base for all operations.
- To fill the Pyfhel object during initialization you can:
Provide a dictionary of context parameters to run Pyfhel.contextGen(**context_params).
Set key_gen to True in order to generate a new public/secret key pair.
Provide a pub_key_file and/or sec_key_file to load existing keys from saved files.
- context_params¶
dictionary of context parameters to run contextGen(), or alternatively a string with the name of a saved context, to read with load_context().
- Type:
dict|str|pathlib.Path, optional
- pub_key_file¶
Load public key from this file.
- Type:
str|pathlib.Path, optional
- sec_key_file¶
Load secret key from this file.
- Type:
str|pathlib.Path, optional
Methods
__repr__
A printable string with all the information about the Pyfhel object
__init__
Initializes an empty Pyfhel object, the base for all operations.
add
(self, PyCtxt ctxt, PyCtxt ctxt_other, ...)Sum two PyCtxt ciphertexts homomorphically.
add_plain
(self, PyCtxt ctxt, PyPtxt ptxt, ...)Sum a PyCtxt ciphertext and a PyPtxt plaintext.
align_mod_n_scale
(self, PyCtxt this, other, ...)Aligns the scales & mod_levels of this and other.
batchEnabled
(self)Flag of batch enabled.
contextGen
(self, unicode scheme, int n, ...)Generates Homomorphic Encryption context based on parameters.
cumul_add
(self, PyCtxt ctxt, ...)Performs cumulative addition over the first n_elements of a PyCtxt.
decode
(self, PyPtxt ptxt)Decodes any valid PyPtxt into a value or vector.
decodeABGV
(self, PyPtxt[)decodeAComplex
(self, PyPtxt[)decodeAFrac
(self, PyPtxt[)decodeAInt
(self, PyPtxt[)decodeBGV
(self, PyPtxt ptxt)Decodes a PyPtxt plaintext into a single int value.
decodeComplex
(self, PyPtxt ptxt)Decodes a PyPtxt plaintext into a single float value.
decodeFrac
(self, PyPtxt ptxt)Decodes a PyPtxt plaintext into a single float value.
decodeInt
(self, PyPtxt ptxt)Decodes a PyPtxt plaintext into a single int value.
decrypt
(self, PyCtxt ctxt, bool decode=True, ...)Decrypts any valid PyCtxt into either a PyPtxt ciphertext or a value.
decryptABGV
(self, PyCtxt ctxt)decryptAComplex
(self, PyCtxt ctxt)decryptAFrac
(self, PyCtxt ctxt)decryptAInt
(self, PyCtxt ctxt)decryptAPtxt
(self, PyCtxt ctxt)decryptBGV
(self, PyCtxt ctxt)Decrypts a PyCtxt ciphertext into a single int value.
decryptComplex
(self, PyCtxt ctxt)Decrypts a PyCtxt ciphertext into a vector of complex values
decryptFrac
(self, PyCtxt ctxt)Decrypts a PyCtxt ciphertext into a vector of floats
decryptInt
(self, PyCtxt ctxt)Decrypts a PyCtxt ciphertext into a single int value.
decryptPtxt
(self, PyCtxt ctxt, PyPtxt ptxt=None)Decrypts a PyCtxt ciphertext into a PyPtxt plaintext.
empty_poly
(self, PyCtxt ref)Generates an empty polynomial using ref as reference
encode
(self, val_vec, double scale=0, ...)Encodes any valid value/vector into a PyPtxt plaintext.
encodeABGV
(self, int64_t[, )encodeAComplex
(self, double complex[, , ...)encodeAFrac
(self, double[, , double scale=0, ...)encodeAInt
(self, int64_t[, )encodeBGV
(self, int64_t[, PyPtxt ptxt=None)Encodes an integer vector into a PyPtxt plaintext.
encodeComplex
(self, double complex[, ...)Encodes a complex vector into a PyPtxt plaintext.
encodeFrac
(self, double[, PyPtxt ptxt=None, ...)Encodes a float vector into a PyPtxt plaintext.
encodeInt
(self, int64_t[, PyPtxt ptxt=None)Encodes an integer vector into a PyPtxt plaintext.
encrypt
(self, ptxt, PyCtxt ctxt=None[, scale])Encrypts any valid value into a PyCtxt ciphertext.
encryptABGV
(self, int64_t[, )encryptAComplex
(self, double complex[, , ...)encryptAFrac
(self, double[, , ...)encryptAInt
(self, int64_t[, )encryptAPtxt
(self, PyPtxt[)encryptBGV
(self, int64_t[, PyCtxt ctxt=None)Encrypts a 1D vector of int values into a PyCtxt ciphertext.
encryptComplex
(self, double complex[, ...)Encrypts a 1D vector of complex values into a PyCtxt ciphertext.
encryptFrac
(self, double[, PyCtxt ctxt=None, ...)Encrypts a 1D vector of float values into a PyCtxt ciphertext.
encryptInt
(self, int64_t[, PyCtxt ctxt=None)Encrypts a 1D vector of int values into a PyCtxt ciphertext.
encryptPtxt
(self, PyPtxt ptxt, PyCtxt ctxt=None)Encrypts an encoded PyPtxt plaintext into a PyCtxt ciphertext.
flip
(self, PyCtxt ctxt, bool in_new_ctxt=False)Swaps the two rows of a PyCtxt ciphertext with BFV scheme.
from_bytes_context
(self, bytes content)Restores current context from a bytes object
from_bytes_public_key
(self, bytes content)Restores current public key from a bytes object
from_bytes_relin_key
(self, bytes content)Restores current relin key from a bytes object
from_bytes_rotate_key
(self, bytes content)Restores current rotation key from a bytes object
from_bytes_secret_key
(self, bytes content)Restores current secret key from a bytes object
get_nSlots
(self)Maximum number of slots fitting in a ciphertext.
get_plain_modulus
(self)Plaintext modulus of the current context.
get_poly_modulus_degree
(self)Plaintext coefficient of the current context.
get_qi
(self)Returns the qi values (coeff.
get_scheme
(self)Scheme of the current context.
is_context_empty
(self)True if the current Pyfhel instance has no context.
is_public_key_empty
(self)True if the current Pyfhel instance has no public Key.
is_relin_key_empty
(self)True if the current Pyfhel instance has no relinearization key.
is_rotate_key_empty
(self)True if the current Pyfhel instance has no rotation key.
is_secret_key_empty
(self)True if the current Pyfhel instance has no secret Key.
keyGen
(self)Generates a pair of secret/Public Keys.
load_context
(self, fileName)Restores context from a file
load_public_key
(self, fileName)Restores current public key from a file
load_relin_key
(self, fileName)Restores current relinearization keys from a file
load_rotate_key
(self, fileName)Restores current rotation Keys from a file
load_secret_key
(self, fileName)Restores current secret key from a file
maxBitCount
(self, long poly_modulus_degree, ...)Returns the maximum number of bits that can be used to encode a number.
mod_switch_to_next
(self, cipher_or_plain[, ...])Reduces the ciphertext/plaintext modulus with next prime in the qi chain.
mod_switch_to_next_ctxt
(self, PyCtxt ctxt, ...)Reduces the ciphertext modulus with next prime in the qi chain.
mod_switch_to_next_ptxt
(self, PyPtxt ptxt, ...)Reduces the plaintext modulus with next prime in the qi chain.
multDepth
(self[, max_depth, delta, x_y_z, ...])Empirically determines the multiplicative depth of a Pyfhel Object for a given context.
multiply
(self, PyCtxt ctxt, ...)Multiply first PyCtxt ciphertext by the second PyCtxt ciphertext.
multiply_plain
(self, PyCtxt ctxt, ...)Multiply a PyCtxt ciphertext and a PyPtxt plaintext.
negate
(self, PyCtxt ctxt, bool in_new_ctxt=False)Negate PyCtxt ciphertext value/s.
noise_level
(self, PyCtxt ctxt)Computes the invariant noise budget (bits) of a PyCtxt ciphertext.
poly_add
(self, PyPoly p, PyPoly p_other, ...)Sum two PyPoly polynomials: p + p_other.
poly_from_ciphertext
(self, PyCtxt ctxt, size_t i)Gets the i-th underlying polynomial of a ciphertext
poly_from_coeff_vector
(self, ...)Generates a polynomial with given coefficients
poly_from_plaintext
(self, PyCtxt ref, ...)Gets the underlying polynomial of a plaintext
poly_invert
(self, PyPoly p, ...)Invert PyPoly polynomial: inverse(p)
poly_multiply
(self, PyPoly p, ...)Multiply two PyPoly polynomials: p * p_other.
poly_subtract
(self, PyPoly p, ...)Subtract two PyPoly polynomials: p - p_other.
poly_to_ciphertext
(self, PyPoly p, ...)Set chosen i-th polynimial in ctxt to p.
poly_to_plaintext
(self, PyPoly p, PyPtxt ptxt)Set the polynimial in ptxt to p.
polys_from_ciphertext
(self, PyCtxt ctxt)Generates a list of polynomials of the given ciphertext
power
(self, PyCtxt ctxt, uint64_t expon, ...)Exponentiates PyCtxt ciphertext value/s to expon power.
relinKeyGen
(self)Generates a relinearization Key.
relinearize
(self, PyCtxt ctxt)Relinearizes a ciphertext.
rescale_to_next
(self, PyCtxt ctxt)Rescales a ciphertext by dividing it by one scale factor.
rotate
(self, PyCtxt ctxt, int k, ...)Rotates cyclically PyCtxt ciphertext values k positions.
rotateKeyGen
(self, vector[int] rot_steps=)Generates a rotation Key.
save_context
(self, fileName, ...)Saves current context in a file
save_public_key
(self, fileName, ...)Saves current public key in a file
save_relin_key
(self, fileName, ...)Saves current relinearization keys in a file
save_rotate_key
(self, fileName, ...)Saves current rotation Keys from a file
save_secret_key
(self, fileName, ...)Saves current secret key in a file
scalar_prod
(self, PyCtxt ctxt, ...)Performs a scalar product between two PyCtxt ciphertexts.
scalar_prod_plain
(self, PyCtxt ctxt, ...)Performs a scalar product between two PyCtxt ciphertexts.
sizeof_context
(self, unicode compr_mode=u)Returns an upper bound on the size of the current context in bytes
sizeof_public_key
(self, unicode compr_mode=u)Returns an upper bound on the size of the current public key in bytes
sizeof_relin_key
(self, unicode compr_mode=u)Returns an upper bound on the size of the current relinearization key in bytes
sizeof_rotate_key
(self, unicode compr_mode=u)Returns an upper bound on the size of the current rotation key in bytes
sizeof_secret_key
(self, unicode compr_mode=u)Returns an upper bound on the size of the current secret key in bytes
square
(self, PyCtxt ctxt, bool in_new_ctxt=False)Square PyCtxt ciphertext value/s.
sub
(self, PyCtxt ctxt, PyCtxt ctxt_other, ...)Substracts one PyCtxt ciphertext from another.
sub_plain
(self, PyCtxt ctxt, PyPtxt ptxt, ...)Substracts a PyCtxt ciphertext and a plaintext.
to_bytes_context
(self, unicode compr_mode=u)Saves current context in a bytes string
to_bytes_public_key
(self, unicode compr_mode=u)Saves current public key in a bytes string
to_bytes_relin_key
(self, unicode compr_mode=u)Saves current relinearization key in a bytes string
to_bytes_rotate_key
(self, unicode compr_mode=u)Saves current context in a bytes string
to_bytes_secret_key
(self, unicode compr_mode=u)Saves current secret key in a bytes string
Attributes
n
n, Polynomial coefficient modulus.
qi
Coefficient moduli.
qi_sizes
Chain of prime sizes (bits).
scale
Upscale factor for fixed-point values.
scheme
Scheme of the current context.
sec
Security of the context parameters (bits).
t
t, plaintext modulus.
total_coeff_modulus_bit_count
Total number of bits in the coefficient modulus (sum(bits(q_i))).
API description
- __repr__()¶
A printable string with all the information about the Pyfhel object
- Info:
at: hex ID, unique identifier and memory location.
pk: ‘Y’ if public key is present. ‘-’ otherwise.
sk: ‘Y’ if secret key is present. ‘-’ otherwise.
rtk: ‘Y’ if rotation keys are present. ‘-’ otherwise.
rlk: ‘Y’ if relinarization keys are present. ‘-’ otherwise.
- contx: Context, with values of p, m, base, security,
# of int and frac digits and wether flagBatching is enabled.
- add(self, PyCtxt ctxt, PyCtxt ctxt_other, bool in_new_ctxt=False) PyCtxt ¶
Sum two PyCtxt ciphertexts homomorphically.
Sums two ciphertexts. Encoding must be the same. Requires same context and encryption with same public key. The result is applied to the first ciphertext.
- add_plain(self, PyCtxt ctxt, PyPtxt ptxt, bool in_new_ctxt=False) PyCtxt ¶
Sum a PyCtxt ciphertext and a PyPtxt plaintext.
Sums a ciphertext and a plaintext. Encoding must be the same. Requiressame context and encryption with same public key. The result is applied to the first ciphertext.
- align_mod_n_scale(self, PyCtxt this: PyCtxt, other: Union[PyCtxt, PyPtxt], bool copy_this: bool = True, bool copy_other: bool = True, bool only_mod: bool = False) Tuple[PyCtxt, PyCtxt | PyPtxt] ¶
Aligns the scales & mod_levels of this and other.
Only applies to CKKS. Alligns the scales of the this ciphertext and the other ciphertext/plaintext by aligning the scale and mod_level: - Rescales the ciphertext with the highest mod_level to the next qi/s - Mod switches the second ciphertext/plaintext to the next qi/s - At the end, rounds the scale of the rescaled ciphertext
- Parameters:
- Returns:
inputs with aligned scale & mod_level.
- Return type:
- batchEnabled(self) bool ¶
Flag of batch enabled.
- Returns:
Result, True if enabled, False if disabled.
- Return type:
- contextGen(self, unicode scheme, int n, int t_bits=0, int64_t t=0, int sec=128, double scale=1, int scale_bits=0, vector[int] qi_sizes={}, vector[uint64_t] qi={}) string ¶
Generates Homomorphic Encryption context based on parameters.
Creates a HE context based in parameters, as well as an appropriate encoder according to the scheme choice. The HE context contains the “public parameters” of the scheme, required for all operations (encryption/decryption, scheme/decoding, operations). Validates the choice of parameters and returns the validation status/error.
- BFV scheme: vectorized integer operations in Single Instruction Multiple
Data (SIMD) fashion. The scheme requires a plain_modulus t prime, with t-1 being multiple of 2*n (n is the polynomial modulus degree). This is generated automatically with bitsize t_bits, and it will serve as plaintext modulo (the maximum value of plaintext/ciphetext slots). The coefficient moduli (qi) is chosen under the hood with the security level sec, based on homomorphicencryption.org, although it can be set manually with qi_sizes|qi.
BGV scheme: TODO
- CKKS scheme: vectorized approximate fixed point operations in SIMD. The
underlying coefficient modulus (q) is set with a list of prime sizes qi_sizes (bit sizes) or directly with a chain of primes (qi).
A larger coeff_modulus (q = prod(qi)) implies a larger noise budget, hence more encrypted computation capabilities. However, an upper bound for the total bit-length (total_coeff_modulus_bit_count) of the coeff_modulus is determined by the poly_modulus_degree (n), as follows:
poly_modulus_degree | max coeff_modulus bit-length
1024 2048 4096 8192 16384 32768
27 54 109 218 438 881
- Parameters:
scheme (str) – HE scheme (“bfv” or “ckks”, for integer or float ops).
n (int) – Polynomial coefficient modulus m. (Poly: 1*x^n+1), directly linked to the multiplication depth, (SEAL’s poly_modulus_degree) and equal to the number of slots (nSlots) in bfv.
qi (int, optional) – Chain of primes composing the coefficient moduli. Overriden by qi if scheme is “ckks” and sec if scheme is “bfv”.
qi_sizes (list of ints, optional) – Chain of prime sizes (#bits), to set q.
sec (int, optional) – Security level equivalent in AES. One of {0 (unset)128, 192, 256}. There is little reason to go beyond 128 bits. Sets q if scheme is “bfv” (overriding qi|qi_sizes), and adds compliance checks for “ckks”.
-- (-- Only for CKKS scheme) –
t_bits (int, optional) – Plaintext modulus bit size. Overrides t.
t (int, optional) – Plaintext modulus. (SEAL’s plain_modulus)
-- –
scale (int, optional) – Upscale factor for fixed-point values.
scale_bits (int, optional) – overrides scale, sets it to 2**scale_bits.
- Returns:
- The result of validating the chosen parameters. Contains:
’success: valid’ if the parameters are valid. An informing error name and message otherwise.
- Return type:
- cumul_add(self, PyCtxt ctxt, bool in_new_ctxt=False, size_t n_elements=0) PyCtxt ¶
Performs cumulative addition over the first n_elements of a PyCtxt.
Runs log2(n_elements) additions and rotations to obtain the cumulative sum in the first element of the result. For correct results use a power of 2 for n_elements. If n_elements is 0, it will use the size (nSlots) of the ciphertext.
- decode(self, PyPtxt ptxt)¶
Decodes any valid PyPtxt into a value or vector.
Decodes a PyPtxt plaintext based on the current context. Outputs an integer (int), a truncated decimal (float), or in Batch mode a 1D vector of integers. Automatically selects the decoding function based on type.
- decodeABGV(self, PyPtxt[:] ptxt) ndarray ¶
- decodeAComplex(self, PyPtxt[:] ptxt) ndarray ¶
- decodeAFrac(self, PyPtxt[:] ptxt) ndarray ¶
- decodeAInt(self, PyPtxt[:] ptxt) ndarray ¶
- decodeBGV(self, PyPtxt ptxt) ndarray ¶
Decodes a PyPtxt plaintext into a single int value. Decodes a PyPtxt plaintext into a single int value based on the current context. PyPtxt scheme must be bgv. :param ptxt: plaintext to decode. :type ptxt: PyPtxt, optional
- Returns:
the decoded integer value
- Return type:
- Raises:
RuntimeError – if the ciphertext scheme isn’t Scheme_t.bgv
- decodeComplex(self, PyPtxt ptxt) ndarray ¶
Decodes a PyPtxt plaintext into a single float value.
Decodes a PyPtxt plaintext into a single float value based on the current context. PyPtxt scheme must be ckks.
- Parameters:
ptxt (PyPtxt) – plaintext to decode.
- Returns:
the decoded float value
- Return type:
- Raises:
RuntimeError – if the ciphertext scheme isn’t Scheme_t.ckks
- decodeFrac(self, PyPtxt ptxt) ndarray ¶
Decodes a PyPtxt plaintext into a single float value.
Decodes a PyPtxt plaintext into a single float value based on the current context. PyPtxt scheme must be ckks.
- Parameters:
ptxt (PyPtxt) – plaintext to decode.
- Returns:
the decoded float value
- Return type:
- Raises:
RuntimeError – if the ciphertext scheme isn’t Scheme_t.ckks
- decodeInt(self, PyPtxt ptxt) ndarray ¶
Decodes a PyPtxt plaintext into a single int value.
Decodes a PyPtxt plaintext into a single int value based on the current context. PyPtxt scheme must be bfv.
- Parameters:
ptxt (PyPtxt, optional) – plaintext to decode.
- Returns:
the decoded integer value
- Return type:
- Raises:
RuntimeError – if the ciphertext scheme isn’t Scheme_t.bfv
- decrypt(self, PyCtxt ctxt, bool decode=True, PyPtxt ptxt=None)¶
Decrypts any valid PyCtxt into either a PyPtxt ciphertext or a value.
Decrypts a PyCtxt ciphertext using the current secret key, based on the current context. Outputs an integer (int), a truncated decimal (float), a PyPtxt encoded plaintext, or in Batch mode a 1D numpy vector of integers. Can also return a PyPtxt by setting decode to True.
Selects the encryption function based on type.
If provided a plaintext, decrypts the ciphertext inside it.
- decryptABGV(self, PyCtxt ctxt) ndarray ¶
- decryptAComplex(self, PyCtxt ctxt) ndarray ¶
- decryptAFrac(self, PyCtxt ctxt) ndarray ¶
- decryptAInt(self, PyCtxt ctxt) ndarray ¶
- decryptAPtxt(self, PyCtxt ctxt) ndarray ¶
- decryptBGV(self, PyCtxt ctxt) ndarray ¶
Decrypts a PyCtxt ciphertext into a single int value. Decrypts a PyCtxt ciphertext using the current secret key, based on the current context. PyCtxt scheme must be bfv. :param ctxt: ciphertext to decrypt. :type ctxt: PyCtxt, optional
- Returns:
the decrypted integer value
- Return type:
- Raises:
RuntimeError – if the ctxt scheme isn’t Scheme_t.bgv
- decryptComplex(self, PyCtxt ctxt) ndarray ¶
Decrypts a PyCtxt ciphertext into a vector of complex values
Decrypts a PyCtxt ciphertext using the current secret key, based on the current context. PyCtxt scheme must be ckks.
- Parameters:
ctxt (PyCtxt, optional) – ciphertext to decrypt.
- Returns:
the decrypted complex vector
- Return type:
np.array[complex]
- Raises:
RuntimeError – if the ctxt scheme isn’t Scheme_t.ckks
- decryptFrac(self, PyCtxt ctxt) ndarray ¶
Decrypts a PyCtxt ciphertext into a vector of floats
Decrypts a PyCtxt ciphertext using the current secret key, based on the current context. PyCtxt scheme must be ckks.
- Parameters:
ctxt (PyCtxt, optional) – ciphertext to decrypt.
- Returns:
the decrypted float vector
- Return type:
np.array[float]
- Raises:
RuntimeError – if the ctxt scheme isn’t Scheme_t.ckks
- decryptInt(self, PyCtxt ctxt) ndarray ¶
Decrypts a PyCtxt ciphertext into a single int value.
Decrypts a PyCtxt ciphertext using the current secret key, based on the current context. PyCtxt scheme must be bfv.
- Parameters:
ctxt (PyCtxt, optional) – ciphertext to decrypt.
- Returns:
the decrypted integer value
- Return type:
- Raises:
RuntimeError – if the ctxt scheme isn’t Scheme_t.bfv
- decryptPtxt(self, PyCtxt ctxt, PyPtxt ptxt=None) PyPtxt ¶
Decrypts a PyCtxt ciphertext into a PyPtxt plaintext.
Decrypts a PyCtxt ciphertext using the current secret key, based on the current context. No regard to scheme (decode PyPtxt to obtain value).
- encode(self, val_vec, double scale=0, int scale_bits=0, PyPtxt ptxt=None)¶
Encodes any valid value/vector into a PyPtxt plaintext.
Encodes any valid value/vector based on the current context. Value/Vector must be an integer (int), a decimal that will get truncated (float), or in Batch mode a 1D vector of integers.
If provided a plaintext, encodes the vector inside it.
- encodeABGV(self, int64_t[:, ::1] arr) ndarray ¶
- encodeAComplex(self, double complex[:, ::1] arr, double scale=0, int scale_bits=0) ndarray ¶
- encodeAFrac(self, double[:, ::1] arr, double scale=0, int scale_bits=0) ndarray ¶
- encodeAInt(self, int64_t[:, ::1] arr) ndarray ¶
- encodeBGV(self, int64_t[::1] arr, PyPtxt ptxt=None) PyPtxt ¶
Encodes an integer vector into a PyPtxt plaintext. Encodes a vector of integer values based on the current context. If provided a plaintext, encodes the values inside it. :param arr: values to encode. :type arr: np.array[int]
- Returns:
the plaintext containing the encoded values
- Return type:
- encodeComplex(self, double complex[::1] arr, PyPtxt ptxt=None, double scale=0, int scale_bits=0) PyPtxt ¶
Encodes a complex vector into a PyPtxt plaintext.
Encodes a vector of complex values based on the current context. If provided a plaintext, encodes the values inside it.
- encodeFrac(self, double[::1] arr, PyPtxt ptxt=None, double scale=0, int scale_bits=0) PyPtxt ¶
Encodes a float vector into a PyPtxt plaintext.
Encodes a vector of float values based on the current context. If provided a plaintext, encodes the values inside it.
- encodeInt(self, int64_t[::1] arr, PyPtxt ptxt=None) PyPtxt ¶
Encodes an integer vector into a PyPtxt plaintext.
Encodes a vector of integer values based on the current context. If provided a plaintext, encodes the values inside it.
- encrypt(self, ptxt, PyCtxt ctxt=None, scale=None)¶
Encrypts any valid value into a PyCtxt ciphertext.
Encrypts a plaintext using the current secret key, based on the current context. Plaintext must be an integer vector (int), a float vector that will get truncated (double), or a PyPtxt encoded plaintext. Selects the encryption function based on type.
If provided a ciphertext, encrypts the plaintext inside it.
- encryptABGV(self, int64_t[:, ::1] arr) ndarray ¶
- encryptAComplex(self, double complex[:, ::1] arr, double scale=0, int scale_bits=0) ndarray ¶
- encryptAFrac(self, double[:, ::1] arr, double scale=0, int scale_bits=0) ndarray ¶
- encryptAInt(self, int64_t[:, ::1] arr) ndarray ¶
- encryptAPtxt(self, PyPtxt[:] ptxt) ndarray ¶
- encryptBGV(self, int64_t[:] arr, PyCtxt ctxt=None) PyCtxt ¶
Encrypts a 1D vector of int values into a PyCtxt ciphertext. If provided a ciphertext, encrypts the value inside it. :param value: value to encrypt. :type value: int :param ctxt: Optional destination ciphertext. :type ctxt: PyCtxt, optional
- Returns:
the ciphertext containing the encrypted plaintext
- Return type:
- encryptComplex(self, double complex[:] arr, PyCtxt ctxt=None, double scale=0, int scale_bits=0) PyCtxt ¶
Encrypts a 1D vector of complex values into a PyCtxt ciphertext.
Encrypts a fractional vector using the current secret key, based on the current context. Value must be a complex (double, double) that will get truncated. If provided a ciphertext, encrypts the plaintext inside it.
- encryptFrac(self, double[:] arr, PyCtxt ctxt=None, double scale=0, int scale_bits=0) PyCtxt ¶
Encrypts a 1D vector of float values into a PyCtxt ciphertext.
Encrypts a fractional vector using the current secret key, based on the current context. Value must a decimal (float, double) that will get truncated. If provided a ciphertext, encrypts the plaintext inside it.
- encryptInt(self, int64_t[:] arr, PyCtxt ctxt=None) PyCtxt ¶
Encrypts a 1D vector of int values into a PyCtxt ciphertext.
If provided a ciphertext, encrypts the value inside it.
- encryptPtxt(self, PyPtxt ptxt, PyCtxt ctxt=None) PyCtxt ¶
Encrypts an encoded PyPtxt plaintext into a PyCtxt ciphertext.
Encrypts an encoded PyPtxt plaintext using the current secret key, based on the current context. Plaintext must be a PyPtxt. If provided a ciphertext, encrypts the plaintext inside it.
- flip(self, PyCtxt ctxt, bool in_new_ctxt=False) PyCtxt ¶
Swaps the two rows of a PyCtxt ciphertext with BFV scheme.
Requires previously initialized rotation keys with rotateKeyGen().
- from_bytes_context(self, bytes content) size_t ¶
Restores current context from a bytes object
- Parameters:
content (bytes) – bytes object obtained from to_bytes_context
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- from_bytes_public_key(self, bytes content) size_t ¶
Restores current public key from a bytes object
- Parameters:
content (bytes) – bytes object obtained from to_bytes_public_key
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- from_bytes_relin_key(self, bytes content) size_t ¶
Restores current relin key from a bytes object
- Parameters:
content (bytes) – bytes object obtained from to_bytes_relin_key
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- from_bytes_rotate_key(self, bytes content) size_t ¶
Restores current rotation key from a bytes object
- Parameters:
content (bytes) – bytes object obtained from to_bytes_rotateKey
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- from_bytes_secret_key(self, bytes content) size_t ¶
Restores current secret key from a bytes object
- Parameters:
content (bytes) – bytes object obtained from to_bytes_secret_key
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- get_nSlots(self) size_t ¶
Maximum number of slots fitting in a ciphertext.
Equivalent to n for BFV/BGV, and n/2 for CKKS.
- Returns:
Maximum number of slots.
- Return type:
- get_plain_modulus(self) uint64_t ¶
Plaintext modulus of the current context.
- Returns:
Plaintext modulus.
- Return type:
- get_poly_modulus_degree(self) size_t ¶
Plaintext coefficient of the current context.
The more, the bigger the ciphertexts are, thus allowing for more operations with correct decryption. Also, number of values in a ciphertext in both schemes.
- Returns:
Plaintext coefficient.
- Return type:
- get_qi(self) vector[uint64_t] ¶
Returns the qi values (coeff. modulus values) used in the current context.
- Returns:
qi values.
- Return type:
vector[uint64_t]
- get_scheme(self) scheme_t ¶
Scheme of the current context.
- Returns:
Scheme.
- Return type:
scheme_t
- is_context_empty(self) bool ¶
True if the current Pyfhel instance has no context.
- Returns:
True if there is no context. False if there is.
- Return type:
- is_public_key_empty(self) bool ¶
True if the current Pyfhel instance has no public Key.
- Returns:
True if there is no public Key. False if there is.
- Return type:
- is_relin_key_empty(self) bool ¶
True if the current Pyfhel instance has no relinearization key.
- Returns:
True if there is no relinearization Key. False if there is.
- Return type:
- is_rotate_key_empty(self) bool ¶
True if the current Pyfhel instance has no rotation key.
- Returns:
True if there is no rotation Key. False if there is.
- Return type:
- is_secret_key_empty(self) bool ¶
True if the current Pyfhel instance has no secret Key.
- Returns:
True if there is no secret Key. False if there is.
- Return type:
- keyGen(self) void ¶
Generates a pair of secret/Public Keys.
Based on the current context, initializes a public/secret key pair.
- Parameters:
None –
- Returns:
None
- load_context(self, fileName) size_t ¶
Restores context from a file
- Parameters:
fileName (str, pathlib.Path) – Name of the file.
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- load_public_key(self, fileName) size_t ¶
Restores current public key from a file
- Parameters:
fileName (str, pathlib.Path) – Name of the file.
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- load_relin_key(self, fileName) size_t ¶
Restores current relinearization keys from a file
- Parameters:
fileName (str, pathlib.Path) – Name of the file.
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- load_rotate_key(self, fileName) size_t ¶
Restores current rotation Keys from a file
- Parameters:
fileName (str, pathlib.Path) – Name of the file.
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- load_secret_key(self, fileName) size_t ¶
Restores current secret key from a file
- Parameters:
fileName (str, pathlib.Path) – Name of the file.
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- maxBitCount(self, long poly_modulus_degree, int sec_level) long ¶
Returns the maximum number of bits that can be used to encode a number.
- Parameters:
poly_modulus_degree (long) – Polynomial modulus degree.
sec_level (int) – Security level.
- Returns:
Maximum number of bits that can be used to encode a number.
- Return type:
long
- mod_switch_to_next(self, cipher_or_plain, in_new_obj=False)¶
Reduces the ciphertext/plaintext modulus with next prime in the qi chain.
- mod_switch_to_next_ctxt(self, PyCtxt ctxt, bool in_new_ctxt=False) PyCtxt ¶
Reduces the ciphertext modulus with next prime in the qi chain.
- mod_switch_to_next_ptxt(self, PyPtxt ptxt, bool in_new_ptxt=True) PyPtxt ¶
Reduces the plaintext modulus with next prime in the qi chain.
- multDepth(self, max_depth=64, delta=0.1, x_y_z=(1, 10, 0.1), verbose=False)¶
Empirically determines the multiplicative depth of a Pyfhel Object for a given context. For this, it encrypts the inputs x, y and z with Fractional scheme and performs the following chained multiplication until the result deviates more than delta in absolute value:
> x * y * z * y * z * y * z * y * z …
After each multiplication, the ciphertext is relinearized and checked. Ideally, y and z should be inverses to avoid wrapping over modulo p. Requires the Pyfhel Object to have initialized context and pub/sec/relin keys.
- multiply(self, PyCtxt ctxt, PyCtxt ctxt_other, bool in_new_ctxt=False) PyCtxt ¶
Multiply first PyCtxt ciphertext by the second PyCtxt ciphertext.
Multiplies two ciphertexts. Encoding must be the same. Requires same context and encryption with same public key. The result is applied to the first ciphertext.
- multiply_plain(self, PyCtxt ctxt, PyPtxt ptxt, bool in_new_ctxt=False) PyCtxt ¶
Multiply a PyCtxt ciphertext and a PyPtxt plaintext.
Multiplies a ciphertext and a plaintext. Encoding must be the same. Requires same context and encryption with same public key. The result is applied to the first ciphertext.
- noise_level(self, PyCtxt ctxt) int ¶
Computes the invariant noise budget (bits) of a PyCtxt ciphertext.
The invariant noise budget measures the amount of room there is for thenoise to grow while ensuring correct decryptions. Decrypts a PyCtxt ciphertext using the current secret key, based on the current context.
- poly_add(self, PyPoly p, PyPoly p_other, bool in_new_poly=False) PyPoly ¶
Sum two PyPoly polynomials: p + p_other.
Encoding must be consistent (TODO). The result is applied to the first polynomial or to a newly created one.
- poly_from_ciphertext(self, PyCtxt ctxt, size_t i) PyPoly ¶
Gets the i-th underlying polynomial of a ciphertext
- poly_from_coeff_vector(self, vector[cy_complex] coeff_vector, PyCtxt ref) PyPoly ¶
Generates a polynomial with given coefficients
- poly_from_plaintext(self, PyCtxt ref, PyPtxt ptxt) PyPoly ¶
Gets the underlying polynomial of a plaintext
- poly_invert(self, PyPoly p, bool in_new_poly=False) PyPoly ¶
Invert PyPoly polynomial: inverse(p)
Encoding must be consistent (TODO). The result is applied to the polynomial or to a newly created one.
- poly_multiply(self, PyPoly p, PyPoly p_other, bool in_new_poly=False) PyPoly ¶
Multiply two PyPoly polynomials: p * p_other.
Encoding must be consistent (TODO). The result is applied to the first polynomial or to a newly created one.
- poly_subtract(self, PyPoly p, PyPoly p_other, bool in_new_poly=False) PyPoly ¶
Subtract two PyPoly polynomials: p - p_other.
Encoding must be consistent (TODO). The result is applied to the first polynomial or to a newly created one.
- poly_to_ciphertext(self, PyPoly p, PyCtxt ctxt, size_t i) void ¶
Set chosen i-th polynimial in ctxt to p.
Encoding must be consistent (TODO).
- poly_to_plaintext(self, PyPoly p, PyPtxt ptxt) void ¶
Set the polynimial in ptxt to p.
Encoding must be consistent (TODO).
- polys_from_ciphertext(self, PyCtxt ctxt) list ¶
Generates a list of polynomials of the given ciphertext
- power(self, PyCtxt ctxt, uint64_t expon, bool in_new_ctxt=False) PyCtxt ¶
Exponentiates PyCtxt ciphertext value/s to expon power.
Performs an exponentiation over a cyphertext. Requires previously initialized relinearization keys with relinearizeKeyGen(), since it applies relinearization after each multiplication.
- relinKeyGen(self) void ¶
Generates a relinearization Key.
Generates a relinearization Key, used to reduce size of the ciphertexts when multiplying or exponentiating them. This is needed due to the fact that ciphertexts grow in size after encrypted mults/exponentiations.
Based on the current context, initializes one relinearization key.
- Parameters:
None –
- Returns:
None
- relinearize(self, PyCtxt ctxt) void ¶
Relinearizes a ciphertext.
Relinearizes a ciphertext. This functions relinearizes ctxt, reducing its size down to 2.
- Parameters:
ctxt (PyCtxt) – the ciphertext to relinearize in-place
- Returns:
None
- rescale_to_next(self, PyCtxt ctxt) void ¶
Rescales a ciphertext by dividing it by one scale factor.
- Parameters:
ctxt (PyCtxt) – Ciphertext to rescale.
- Returns:
None
- rotate(self, PyCtxt ctxt, int k, bool in_new_ctxt=False) PyCtxt ¶
Rotates cyclically PyCtxt ciphertext values k positions.
Performs a cyclic rotation over a cyphertext encoded in BATCH mode. Requires previously initialized rotation keys with rotateKeyGen().
- rotateKeyGen(self, vector[int] rot_steps={}) void ¶
Generates a rotation Key.
Generates a rotation Key, used to rotate cyclically the values inside the encrypted vector.
Based on the current context, initializes one rotation key.
- Parameters:
rot_steps (vector of ints) – Number of positions to rotate. If non-empty, only these steps can be used as k in Pyfhel.rotate(ctxt, k), but they will yield faster rotations for non-power-of-two steps. If empty, generates a binary decompositon of rotations over n {1,2,4…,n/2}, and uses them to compose any rotation step k.
- Returns:
None
- save_context(self, fileName, unicode compr_mode=u'zstd') size_t ¶
Saves current context in a file
- Parameters:
fileName (str, pathlib.Path) – Name of the file.
compr_mode (str) – Compression. One of “none”, “zlib”, “zstd”
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- save_public_key(self, fileName, unicode compr_mode=u'zstd') size_t ¶
Saves current public key in a file
- Parameters:
fileName (str, pathlib.Path) – Name of the file.
compr_mode (str) – Compression. One of “none”, “zlib”, “zstd”
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- save_relin_key(self, fileName, unicode compr_mode=u'zstd') size_t ¶
Saves current relinearization keys in a file
- Parameters:
fileName (str, pathlib.Path) – Name of the file.
compr_mode (str) – Compression. One of “none”, “zlib”, “zstd”
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- save_rotate_key(self, fileName, unicode compr_mode=u'zstd') size_t ¶
Saves current rotation Keys from a file
- Parameters:
fileName (str, pathlib.Path) – Name of the file.
compr_mode (str) – Compression. One of “none”, “zlib”, “zstd”
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- save_secret_key(self, fileName, unicode compr_mode=u'zstd') size_t ¶
Saves current secret key in a file
- Parameters:
fileName (str, pathlib.Path) – Name of the file.
compr_mode (str) – Compression. One of “none”, “zlib”, “zstd”
- Returns:
number of bytes saved/loaded
- Return type:
size_t
- scalar_prod(self, PyCtxt ctxt, PyCtxt ctxt_other, bool in_new_ctxt=False, bool with_relin=True, bool with_mod_switch=True, size_t n_elements=0) PyCtxt ¶
Performs a scalar product between two PyCtxt ciphertexts.
Performs a scalar product between two ciphertexts. Encoding must be the same. Requires same context and encryption with same public key.
- Parameters:
ctxt (PyCtxt) – ciphertext multiplied with ctxt_other.
ctxt_other (PyCtxt) – ciphertext left untouched.
n_elements (size_t) – number of elements to be considered on each vector. If 0, the full encrypted vectors are considered (get_n_slots/ctxt.size).
with_relin (bool) – whether to perform relinearization after multiplication.
with_mod_switch (bool) – whether to perform modulus switching after multiplication.
in_new_ctxt (bool) – result in a newly created ciphertext.
- Returns:
resulting ciphertext, the input transformed or a new one
- Return type:
- scalar_prod_plain(self, PyCtxt ctxt, PyPtxt ptxt_other, bool in_new_ctxt=False, bool with_relin=True, bool with_mod_switch=True, size_t n_elements=0) PyCtxt ¶
Performs a scalar product between two PyCtxt ciphertexts.
Performs a scalar product between two ciphertexts. Encoding must be the same. Requires same context and encryption with same public key.
- Parameters:
ctxt (PyCtxt) – ciphertext multiplied with ctxt_other.
ptxt_other (PyPtxt) – plaintext left untouched.
n_elements (size_t) – number of elements to be considered on each vector. If 0, the full encrypted vectors are considered (get_n_slots/ctxt.size).
with_relin (bool) – whether to perform relinearization after multiplication.
with_mod_switch (bool) – whether to perform modulus switching after multiplication.
in_new_ctxt (bool) – result in a newly created ciphertext.
- Returns:
resulting ciphertext, the input transformed or a new one
- Return type:
- sizeof_context(self, unicode compr_mode=u'none') size_t ¶
Returns an upper bound on the size of the current context in bytes
- Returns:
size of the current context in bytes
- Return type:
size_t
- sizeof_public_key(self, unicode compr_mode=u'none') size_t ¶
Returns an upper bound on the size of the current public key in bytes
- Returns:
size of the current public key in bytes
- Return type:
size_t
- sizeof_relin_key(self, unicode compr_mode=u'none') size_t ¶
Returns an upper bound on the size of the current relinearization key in bytes
- Returns:
size of the current relinearization key in bytes
- Return type:
size_t
- sizeof_rotate_key(self, unicode compr_mode=u'none') size_t ¶
Returns an upper bound on the size of the current rotation key in bytes
- Returns:
size of the current rotation key in bytes
- Return type:
size_t
- sizeof_secret_key(self, unicode compr_mode=u'none') size_t ¶
Returns an upper bound on the size of the current secret key in bytes
- Returns:
size of the current secret key in bytes
- Return type:
size_t
- sub(self, PyCtxt ctxt, PyCtxt ctxt_other, bool in_new_ctxt=False) PyCtxt ¶
Substracts one PyCtxt ciphertext from another.
Substracts one ciphertext from another. Encoding must be the same. Requires same context and encryption with same public key. The result is stored/applied to the first ciphertext.
- sub_plain(self, PyCtxt ctxt, PyPtxt ptxt, bool in_new_ctxt=False) PyCtxt ¶
Substracts a PyCtxt ciphertext and a plaintext.
Performs ctxt = ctxt - ptxt. Encoding must be the same. Requires same context and encryption with same public key. The result is stored/applied to the ciphertext.
- to_bytes_public_key(self, unicode compr_mode=u'zstd') bytes ¶
Saves current public key in a bytes string
- to_bytes_relin_key(self, unicode compr_mode=u'zstd') bytes ¶
Saves current relinearization key in a bytes string
- to_bytes_rotate_key(self, unicode compr_mode=u'zstd') bytes ¶
Saves current context in a bytes string
- to_bytes_secret_key(self, unicode compr_mode=u'zstd') bytes ¶
Saves current secret key in a bytes string
- n¶
n, Polynomial coefficient modulus. (1*x^n+1).
- qi¶
Coefficient moduli. Chain of primes that composition.
- qi_sizes¶
Chain of prime sizes (bits). Sets sizes of coefficient moduli (qi).
- scale¶
Upscale factor for fixed-point values. Only applies to CKKS scheme.
- scheme¶
Scheme of the current context.
- sec¶
Security of the context parameters (bits).
- t¶
t, plaintext modulus.
- total_coeff_modulus_bit_count¶
Total number of bits in the coefficient modulus (sum(bits(q_i))).