API serialized

class Pyfhel.PyCtxt(PyCtxt copy_ctxt=None, Pyfhel pyfhel=None, fileName=None, bytestring=None, scheme=None)

Bases: object

Ciphertext class of Pyfhel, contains a value/vector of encrypted ints/doubles.

This class references SEAL and PALISADE ciphertexts, using the one corresponding to the backend selected in Pyfhel. By default, it is SEAL.

__add__(other)

Sums this ciphertext with either another PyCtx or a PyPtxt plaintext.

Sums with a PyPtxt/PyCtxt, storing the result a new ciphertext.

Parameters:

other (PyCtxt, PyPtxt) – Second summand.

Returns:

Ciphertext resulting of addition.

Return type:

PyCtxt

Raises:

TypeError – if other doesn’t have a valid type.

See also

add()

__bytes__(self)
__bytes__() None

Serialize current ciphertext to bytes

__iadd__()

Sums this ciphertext with either another PyCtx or a PyPtxt plaintext.

Sums with a PyPtxt/PyCtxt, storing the result in this ciphertext.

Parameters:

other (PyCtxt, PyPtxt) – Second summand.

Raises:

TypeError – if other doesn’t have a valid type.

__ilshift__()

Rotates this ciphertext k positions to the left, in-place.

Parameters:

k (int) – Number of positions to rotate.

__imatmul__()

Performs the in-place scalar product with another ciphertext

The result is stored in a new ciphertext.

Parameters:

other (PyCtxt) – Ciphertext to perform the scalar product with.

Returns:

Ciphertext resulting of scalar product, with the first slot

containing the result.

Return type:

PyCtxt

Raises:

TypeError – if other doesn’t have a valid type.

See also

multiply()

__imul__()

Multiplies this ciphertext with either another PyCtxt or a PyPtxt plaintext.

Multiplies with a PyPtxt/PyCtxt, storing the result in this ciphertext.

Parameters:

other (PyCtxt, PyPtxt) – Multiplier, to be multiplied with this ciphertext.

Returns:

Ciphertext resulting of multiplication

Return type:

PyCtxt

Raises:

TypeError – if other doesn’t have a valid type.

__init__(PyCtxt copy_ctxt=None, Pyfhel pyfhel=None, fileName=None, bytestring=None, scheme=None)

Initializes an empty PyCtxt ciphertext.

To fill the ciphertext during initialization you can:
  • Provide a PyCtxt to deep copy.

  • Provide a pyfhel instance to act as its backend.

  • Provide a fileName and an scheme to load the data from a saved file.

copy_ctxt

Other PyCtxt to deep copy.

Type:

PyCtxt, optional

pyfhel

Pyfhel instance needed to operate.

Type:

Pyfhel, optional

fileName

Load PyCtxt from this file. Requires non-empty scheme.

Type:

str, pathlib.Path, optional

bytestring

Read PyCtxt from a bytes bytestring string, obtained by calling the to_bytes method.

Type:

bytes, optional

scheme

scheme type of the new PyCtxt.

Type:

str, type, int, optional

__invert__()

Relinarizes this ciphertext in-place.

Requires valid relinearization keys.

See also

relinearize()

__ipow__()

Exponentiates this ciphertext to the desired exponent, inplace.

Exponentiates to the desired exponent.

Parameters:

exponent (int) – Exponent for the power.

__irshift__()

Rotates this ciphertext k positions to the right, in-place.

Parameters:

k (int) – Number of positions to rotate.

__isub__()

Subtracts this ciphertext with either another PyCtxt or a PyPtxt plaintext.

Subtracts with a PyPtxt/PyCtxt, storing the result in this ciphertext.

Parameters:

other (PyCtxt, PyPtxt) – Substrahend, to be subtracted from this ciphertext.

Raises:

TypeError – if other doesn’t have a valid type.

__itruediv__()

Multiplies this ciphertext with the inverse of divisor.

This operation can only be done with plaintexts. Division between two Ciphertexts is not possible.

For bfv Integer Scheme, the inverse is calculated as:

inverse -> (divisor * inverse) mod t = 1

For ckks Fractional scheme, the inverse is calculated as 1/divisor.

Parameters:

divisor (int, float, PyPtxt) – divisor for the operation.

__ixor__()

__xor__(k)

Swaps the ciphertext top and bottom half-arrays in BFV, in-place. A No-op otherwise.

k is not used.

See also

flip()

__len__()

Return the current size of the ciphertext.

See also

size()

__lshift__()

Rotates this ciphertext k positions to the left.

Parameters:

k (int) – Number of positions to rotate.

__matmul__()

Performs the scalar product with another ciphertext

The result is stored in a new ciphertext.

Parameters:

other (PyCtxt) – Ciphertext to perform the scalar product with.

Returns:

Ciphertext resulting of scalar product, with the first slot

containing the result.

Return type:

PyCtxt

Raises:

TypeError – if other doesn’t have a valid type.

See also

scalar_prod()

__mul__()

Multiplies this ciphertext with either another PyCtxt or a PyPtxt plaintext.

Multiplies with a PyPtxt/PyCtxt, storing the result in a new ciphertext.

Parameters:

other (PyCtxt, PyPtxt) – Multiplier, to be multiplied with this ciphertext.

Returns:

Ciphertext resulting of multiplication

Return type:

PyCtxt

Raises:

TypeError – if other doesn’t have a valid type.

See also

multiply()

__neg__()

Negates this ciphertext.

__new__(**kwargs)
__pos__()

Computes the cumulative addition over all the slots of the ciphertext.

__pow__(exponent)

Exponentiates this ciphertext to the desired exponent.

Exponentiates to the desired exponent.

Parameters:

exponent (int) – Exponent for the power.

See also

power()

__radd__()
__reduce__(self)
__reduce__() None
Required for pickling purposes. Returns a tuple with:
  • A callable object that will be called to create the initial version of the object.

  • A tuple of arguments for the callable object.

__repr__()

Prints information about the current ciphertext

__rlshift__(value, /)

Return value<<self.

__rmatmul__(value, /)

Return value@self.

__rmul__()
__rpow__(value, mod=None, /)

Return pow(value, self, mod).

__rrshift__(value, /)

Return value>>self.

__rshift__(k)

Rotates this ciphertext k positions to the right.

Parameters:

k (int) – Number of positions to rotate.

__rsub__()
__rtruediv__(value, /)

Return value/self.

__rxor__(value, /)

Return value^self.

__sizeof__(self)
__sizeof__() None

Return the size of the ciphertext in bytes

__sub__(other)

Subtracts this ciphertext with either another PyCtxt or a PyPtxt plaintext.

Subtracts with a PyPtxt/PyCtxt, storing the result in a new ciphertext.

Parameters:

other (PyCtxt, PyPtxt) – Substrahend, to be subtracted from this ciphertext.

Returns:

Ciphertext resulting of subtraction

Return type:

PyCtxt

Raises:

TypeError – if other doesn’t have a valid type.

See also

sub()

__truediv__(divisor)

Multiplies this ciphertext with the inverse of divisor.

This operation can only be done with plaintexts. Division between two Ciphertexts is not possible.

For bfv Integer Scheme, the inverse is calculated as:

inverse -> (divisor * inverse) mod t = 1

For ckks Fractional scheme, the inverse is calculated as 1/divisor.

Parameters:

divisor (int, float, PyPtxt) – divisor for the operation.

__xor__(k)

Swaps the ciphertext top and bottom half-arrays in BFV. A No-op otherwise.

k is not used.

See also

flip()

copy(self) PyCtxt
copy() PyCtxt

Returns a deep copy of the PyCtxt.

decrypt(self)
decrypt() None

Decrypts itself using _pyfhel.

Parameters:

None

Returns:

value decrypted.

Return type:

int, float, np.array

See also

decrypt()

encode_operand(self, other)
encode_operand(other) None

Encodes the given value into a PyPtxt using _pyfhel.

Parameters:

other (int, float, np.array, list) – Encodes accordingly to the type

Returns:

Encoded value

Return type:

PyPtxt

See also

encode()

encrypt(self, value)
encrypt(value) None

Encrypts the given value using _pyfhel.

Parameters:

value (int, float, np.array) – Encrypts accordingly to the type

Returns:

None

See also

encrypt()

from_bytes(self, bytes content, scheme=None) void
from_bytes(bytes content, scheme) None

Recover the serialized ciphertext from a binary/bytes string.

Parameters:
  • content (bytes) – Python bytes object containing the PyCtxt.

  • scheme (str, type, int, Scheme_t) –

    One of the following:

    • (‘int’, ‘INTEGER’, int, 1, Scheme_t.bfv) -> integer scheme.

    • (‘float’, ‘FRACTIONAL’, float, 2, Scheme_t.ckks) -> fractional scheme.

Returns:

None

See also

to_Scheme_t()

get_multiplicative_inverse(self, other)
get_multiplicative_inverse(other) None

Returns the inverse of the given Value/s.

Parameters:

other (int|float|np.array) – Value/s to invert

Returns:

Inverse of the given Value/s, encoded to operate with self.

Return type:

PyPtxt

load(self, unicode fileName, scheme=None) size_t
load(self, str fileName, scheme) None

Load the ciphertext from a file.

Parameters:
  • fileName – (str) Valid file where the ciphertext is retrieved from.

  • scheme (str, type, int, Scheme_t) –

    One of the following:

    • (‘int’, ‘INTEGER’, int, 1, Scheme_t.bfv) -> integer scheme.

    • (‘float’, ‘FRACTIONAL’, float, 2, Scheme_t.ckks) -> fractional scheme.

    • (3, Scheme_t.bgv) -> integer scheme.

Returns:

number of loaded bytes.

Return type:

size_t

See also

to_Scheme_t()

round_scale(self) void
round_scale() None

Rounds the scale of the ciphertext to the nearest power of 2.

save(self, unicode fileName, unicode compr_mode=u'zstd') size_t
save(str fileName) None

Save the ciphertext into a file. The file can new one or exist already, in which case it will be overwriten.

Parameters:
  • fileName – (str) File where the ciphertext will be stored.

  • compr_mode – (str) Compression mode. One of “none”, “zlib”, “zstd”.

Returns:

Number of bytes written.

Return type:

size_t

set_scale(self, double new_scale) void
set_scale(double new_scale) None

Sets the scale of the ciphertext.

Parameters:

scale (double) – new scale of the ciphertext.

size(self) int

Current size of the ciphertext.

Returns:

size of this ciphertext

Return type:

int

sizeof_ciphertext(self, unicode compr_mode=u'none') size_t

Returns the number of bytes that will be written when saving the ciphertext.

Parameters:

compr_mode – (str) Compression mode. One of “none”, “zlib”, “zstd”.

Returns:

Number of bytes that will be written.

Return type:

size_t

to_bytes(self, unicode compr_mode=u'none') bytes
to_bytes() None

Serialize the ciphertext into a binary/bytes string.

Parameters:

compr_mode – (str) Compression mode. One of “none”, “zlib”, “zstd”.

Returns:

serialized ciphertext

Return type:

bytes

__pyx_vtable__ = <capsule object NULL>
_pyfhel

A Pyfhel instance, used for operations

capacity

Maximum size the ciphertext can hold.

Type:

int

mod_level

returns the number of moduli consumed so far.

Only usable in ckks.

Type:

mod_level

noiseBudget

Noise budget.

A value of 0 means that it cannot be decrypted correctly anymore.

See also

noiseLevel()

Type:

int

scale

multiplying factor to encode values in ckks.

Type:

double

scale_bits

number of bits in scale to encode values in ckks

Type:

int

scheme

returns the scheme type.

Can be set to: none, bfv, bgv (INTEGER) or ckks (FRACTIONAL).

See also

to_Scheme_t()

Type:

scheme

class Pyfhel.PyPoly(PyPoly other=None, PyCtxt ref=None, PyPtxt ptxt=None, size_t index=0)

Bases: object

Polynomial class of Pyfhel with the underlying data of a PyCtxt/PyPtxt.

other_ptxt

Other PyPtxt to deep copy

Type:

PyPtxt, optional

__add__()

Sums this pollynomial with another polynomial.

Sums with a PyPoly, storing the result in a new PyPoly.

Parameters:

other (PyPoly) – Second summand.

Returns:

Polynomial resulting of addition.

Return type:

PyPoly

See also

poly_add()

__delitem__(key, /)

Delete self[key].

__getitem__(key, /)

Return self[key].

__iadd__()

Sums this pollynomial with another polynomial inplace.

Sums with a PyPoly, storing the result in this PyPoly.

Parameters:

other (PyPoly) – Second summand.

Returns:

None

See also

poly_add()

__imul__()

Multiplies this polynomial with another polynomial inplace.

Multiplies with a PyPoly, storing the result in this PyPoly.

Parameters:

other (PyPoly) – multiplier polynomial.

Returns:

Polynomial resulting of multiplication.

Return type:

PyPoly

See also

poly_multiply()

__init__()

Initializes a PyPoly polynomial.

To fill the polynomial during initialization you can either:
  • Provide a PyPoly to deep copy.

  • Provide a reference PyCtxt and (optionally) an index for the i-th

    polynomial in the cipertext or (optionally) a source PyPtxt.

other

Other PyPoly to deep copy.

Type:

PyPoly, optional

ref

PyCtxt instance needed as reference.

Type:

PyCtxt, optional

size_t

extract i-th polynomial from ciphertext ref.

Type:

int, optional

ptxt

plaintext used as source.

Type:

PyPtxt, optional

__invert__()

Inverts this polynomial.

See also

poly_invert()

__isub__()

Subtracts other pollynomial from this polynomial inplace.

Subtracts with a PyPoly, storing the result in this PyPoly.

Parameters:

other (PyPoly) – Substrahend, to be subtracted from this polynomial.

Returns:

None

See also

poly_subtract()

__iter__()

Creates an iterator to extract all coefficients

__len__()

Return len(self).

__list__(self)
__mul__()

Multiplies this polynomial with another polynomial.

Multiplies with a PyPoly, storing the result in a new PyPoly.

Parameters:

other (PyPoly) – multiplier polynomial.

Returns:

Polynomial resulting of multiplication.

Return type:

PyPoly

See also

poly_multiply()

__new__(**kwargs)
__radd__()
__reduce__()

PyPoly.__reduce_cython__(self)

__rmul__()
__rsub__()
__setitem__(key, value, /)

Set self[key] to value.

__setstate__()

PyPoly.__setstate_cython__(self, __pyx_state)

__sub__()

Subtracts other polynomial from this polynomial.

Subtracts with a PyPoly, storing the result in this PyPoly.

Parameters:

other (PyPoly) – Substrahend, to be subtracted from this polynomial.

Returns:

Polynomial resulting of subtraction.

Return type:

PyPoly

See also

poly_subtract()

check_afpoly(self) void

Checks if afpoly was initialized or not

from_bytes(self, bytes content, encoding) void
from_bytes(bytes content) None

Recover the serialized polynomial from a binary/bytes string.

Parameters:
  • content – (bytes) Python bytes object containing the PyPoly.

  • encoding – (:obj: str) String or type describing the encoding: * (‘int’, ‘integer’, int, 1, scheme_t.INTEGER) -> integer encoding. * (‘float’, ‘double’, float, 2, scheme_t.FRACTIONAL) -> fractional encoding. * (‘array’, ‘batch’, ‘matrix’, list, 3, scheme_t.BATCH) -> batch encoding.

from_coeff_list(self, vector[cy_complex] coeff_list, PyCtxt ref) void

Sets all the coefficients at once.

Parameters:

coeff_list (List(complex)) – list of coefficients

Returns:

value decrypted.

Return type:

int, float, np.array

See also

decode()

get_coeff(self, size_t i) cy_complex

Gets the chosen coefficient in position i.

Parameters:

i (int) – coefficient position

Returns:

coefficient value

Return type:

complex

load(self, unicode fileName, encoding) void
load(self, str fileName, encoding) None

Load the polynomial from a file.

Parameters:
  • fileName – (str) Valid file where the polynomial is retrieved from.

  • encoding – (str, type, int, scheme_t) One of the following: * (‘int’, ‘integer’, int, 1, scheme_t.INTEGER) -> integer encoding. * (‘float’, ‘double’, float, 2, scheme_t.FRACTIONAL) -> fractional encoding.

Returns:

None

See also

to_scheme_t()

save(self, unicode fileName) void
save(str fileName) None

Save the polynomial into a file. The file can new one or exist already, in which case it will be overwriten.

Parameters:

fileName – (str) File where the polynomial will be stored.

Returns:

None

set_coeff(self, cy_complex coeff, size_t i) void

Sets the given complex value as coefficient in position i.

Parameters:

coeff (complex) – new coefficient value

Returns:

None

to_bytes(self) bytes
to_bytes() None

Serialize the polynomial into a binary/bytes string.

Returns:

serialized polynomial

Return type:

bytes

to_coeff_list(self) vector[cy_complex]

List of complex coefficients of the polynomial

__pyx_vtable__ = <capsule object NULL>
_pyfhel

A pyfhel instance, used for operations

_scheme

returns the scheme type.

Can be set to: 0-None, 1-BFV, 2-CKKS, 3-BGV.

See also

to_scheme_t()

Type:

_scheme

coeff_count
coeff_modulus_count
class Pyfhel.PyPtxt(PyPtxt copy_ptxt=None, Pyfhel pyfhel=None, fileName=None, bytestring=None, scheme=None)

Bases: object

Plaintext class of Pyfhel, contains a value/vector of encoded ints/double.

This class references SEAL, PALISADE and HElib plaintexts, using the one corresponding to the backend selected in Pyfhel (SEAL by default).

other_ptxt

Other PyPtxt to deep copy

Type:

PyPtxt, optional

__float__()

returns the float in the first slot of the plaintext

__init__(PyPtxt copy_ctxt=None, Pyfhel pyfhel=None, fileName=None, scheme=None)

Initializes an empty PyPtxt encoded plaintext.

To fill the plaintext during initialization you can:
  • Provide a PyPtxt to deep copy.

  • Provide a pyfhel instance to act as its backend.

  • Provide a fileName and an scheme to load the data from a saved file.

copy_ctxt

Other PyPtxt to deep copy.

Type:

PyPtxt, optional

pyfhel

Pyfhel instance needed to operate.

Type:

Pyfhel, optional

fileName

Load PyPtxt from this file. Requires non-empty scheme.

Type:

str, pathlib.Path, optional

scheme

scheme type of the new PyPtxt.

Type:

str, type, int, optional

__int__()

returns the integer in the first slot of the plaintext

__new__(**kwargs)
__reduce__()

PyPtxt.__reduce_cython__(self)

__repr__()

Return repr(self).

__setstate__()

PyPtxt.__setstate_cython__(self, __pyx_state)

decode(self)
decode() None

Decodes itself using _pyfhel.

Parameters:

None

Returns:

value decrypted.

Return type:

int, float, np.array

See also

decode()

encode(self, value)
encode(value) None

Encodes the given value using _pyfhel.

Parameters:

value (int, float, np.array) – Encodes accordingly to the tipe

Returns:

None

See also

encode()

from_bytes(self, bytes content, scheme=None) void
from_bytes(bytes content) None

Recover the serialized plaintext from a binary/bytes string.

Parameters:
  • content – (bytes) Python bytes object containing the PyPtxt.

  • scheme – (:obj: str) String or type describing the scheme: * (‘int’, ‘integer’, int, 1, scheme_t.bfv) -> integer scheme. * (‘float’, ‘double’, float, 2, scheme_t.ckks) -> fractional scheme. * (3, scheme_t.bgv) -> integer scheme.

is_ntt_form(self) bool

bool: Flag to quickly check if it is in NTT form

is_zero(self) bool

bool: Flag to quickly check if it is empty

load(self, unicode fileName, scheme=None) void
load(self, str fileName, scheme) None

Load the plaintext from a file.

Parameters:

fileName – (str) Valid file where the plaintext is retrieved from.

Returns:

None

See also

to_Scheme_t()

save(self, unicode fileName, unicode compr_mode=u'zstd') void
save(str fileName) None

Save the plaintext into a file. The file can new one or exist already, in which case it will be overwriten.

Parameters:
  • fileName – (str) File where the plaintext will be stored.

  • compr_mode – (str) Compression mode. One of “none”, “zlib”, “zstd”.

Returns:

None

set_scale(self, double new_scale) void
set_scale(double new_scale) None

Sets the scale of the ciphertext.

Parameters:

scale (double) – new scale of the ciphertext.

to_bytes(self, unicode compr_mode=u'none') bytes
to_bytes() None

Serialize the plaintext into a binary/bytes string.

Parameters:

compr_mode – (str) Compression mode. One of “none”, “zlib”, “zstd”

Returns:

serialized plaintext

Return type:

bytes

to_poly_string(self) string

str: Polynomial representation of the plaintext

__pyx_vtable__ = <capsule object NULL>
_pyfhel

A pyfhel instance, used for operations

mod_level

returns the number of moduli consumed so far.

Only usable in ckks.

Type:

mod_level

scale

multiplying factor to encode values in ckks.

Type:

double

scale_bits

number of bits in scale to encode values in ckks

Type:

int

scheme

returns the scheme type.

Can be set to: 0-none, 1-bfv, 2-ckks, 3-bgv

See also

to_Scheme_t()

Type:

scheme

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

key_gen

generate a new public/secret key pair

Type:

bool, 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

__new__(**kwargs)
__reduce__(self)

Required for pickling purposes. Returns a tuple with: - A callable object that will be called to create the initial version of the object. - A tuple of arguments for the callable object.

__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.

Parameters:
  • ctxt (PyCtxt) – ciphertext whose values are added with ctxt_other.

  • ctxt_other (PyCtxt) – ciphertext left untouched.

  • in_new_ctxt (bool) – result in a newly created ciphertext

Returns:

resulting ciphertext, the input transformed or a new one

Return type:

PyCtxt

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.

Parameters:
  • ctxt (PyCtxt) – ciphertext whose values are added with ptxt.

  • ptxt (PyPtxt) – plaintext left untouched.

  • in_new_ctxt (bool) – result in a newly created ciphertext

Returns:

resulting ciphertext, the input transformed or a new one

Return type:

PyCtxt

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:
  • this (PyCtxt) – Ciphertext to align.

  • other (PyCtxt|PyPtxt) – Ciphertext|plaintext to align with.

  • copy_this (bool) – Copy the this ciphertext before aligning.

  • copy_other (bool) – Copy the other ciphertext|plaintext before aligning.

  • only_mod (bool) – If True, only mod_level is aligned.

Returns:

inputs with aligned scale & mod_level.

Return type:

Tuple[PyCtxt, Union[PyCtxt, PyPtxt]]

batchEnabled(self) bool

Flag of batch enabled.

Returns:

Result, True if enabled, False if disabled.

Return type:

bool

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:

str

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.

Parameters:
  • ctxt (PyCtxt) – ciphertext whose values are rotated.

  • n_elements (int) – number of elements to rotate. If 0, uses the ciphertext’s nSlots.

  • in_new_ctxt (bool) – result in a newly created ciphertext

Returns:

resulting ciphertext, the input transformed or a new one

Return type:

PyCtxt

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.

Parameters:

ptxt (PyPtxt, int, float, np.array) – plaintext to decode.

Returns:

the decoded value or vector.

Return type:

int, float, list[int]

Raises:

TypeError – if the plaintext doesn’t have a valid 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:

int

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:

float

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:

float

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:

int

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.

Parameters:
  • ctxt (PyCtxt) – ciphertext to decrypt.

  • (bool (decode) – True): return value or return PyPtxt.

  • ptxt (PyPtxt, optional) – Optional destination PyPtxt.

Returns:

the decrypted result

Return type:

PyPtxt, np.array[int|float]

Raises:

TypeError – if the cipertext scheme is invalid.

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:

int

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:

int

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).

Parameters:
  • ctxt (PyCtxt) – ciphertext to decrypt.

  • ptxt (PyPtxt, optional) – Optional destination plaintext.

Returns:

the decrypted plaintext

Return type:

PyPtxt

empty_poly(self, PyCtxt ref) PyPoly

Generates an empty polynomial using ref as reference

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.

Parameters:
  • val_vec (int, float, list[int]) – value/vector to encode.

  • ptxt (PyPtxt, optional) – Optional destination plaintext.

Returns:

the plaintext containing the encoded vector.

Return type:

PyPtxt

Raises:

TypeError – if the val_vec doesn’t have a valid type.

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:

PyPtxt

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.

Parameters:
  • arr (np.array[complex]) – values to encode.

  • ptxt (PyPtxt, optional) – Optional destination plaintext.

Returns:

the plaintext containing the encoded values

Return type:

PyPtxt

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.

Parameters:
  • arr (np.array[float]) – values to encode.

  • ptxt (PyPtxt, optional) – Optional destination plaintext.

Returns:

the plaintext containing the encoded values

Return type:

PyPtxt

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.

Parameters:

arr (np.array[int]) – values to encode.

Returns:

the plaintext containing the encoded values

Return type:

PyPtxt

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.

Parameters:
  • ptxt (PyPtxt, int, double, np.ndarray) – plaintext to encrypt.

  • ctxt (PyCtxt, optional) – Optional destination ciphertext.

Returns:

the ciphertext containing the encrypted plaintext

Return type:

PyCtxt

Raises:

TypeError – if the plaintext doesn’t have a valid type.

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:

PyCtxt

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.

Parameters:
  • arr (complex[]) – values to encrypt.

  • ctxt (PyCtxt, optional) – Optional destination ciphertext.

  • scale (double) – scale factor to apply to the values.

Returns:

the ciphertext containing the encrypted plaintext

Return type:

PyCtxt

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.

Parameters:
  • arr (float[]) – values to encrypt.

  • ctxt (PyCtxt, optional) – Optional destination ciphertext.

  • scale (double) – scale factor to apply to the values.

Returns:

the ciphertext containing the encrypted plaintext

Return type:

PyCtxt

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.

Parameters:
  • value (int) – value to encrypt.

  • ctxt (PyCtxt, optional) – Optional destination ciphertext.

Returns:

the ciphertext containing the encrypted plaintext

Return type:

PyCtxt

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.

Parameters:
  • ptxt (PyPtxt) – plaintext to encrypt.

  • ctxt (PyCtxt, optional) – Optional destination ciphertext.

Returns:

the ciphertext containing the encrypted plaintext

Return type:

PyCtxt

Raises:

TypeError – if the plaintext doesn’t have a valid type.

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().

Parameters:
  • ctxt (PyCtxt) – ciphertext whose values are rotated.

  • in_new_ctxt (bool) – result in a newly created ciphertext

Returns:

resulting ciphertext, the input transformed or a new one

Return type:

PyCtxt

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:

int

get_plain_modulus(self) uint64_t

Plaintext modulus of the current context.

Returns:

Plaintext modulus.

Return type:

int

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:

int

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:

bool

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:

bool

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:

bool

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:

bool

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:

bool

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.

Parameters:

cipher_or_plain (PyCtxt|PyPtxt) – Ciphertext to reduce.

Returns:

None

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.

Parameters:
  • ctxt (PyCtxt) – Ciphertext to reduce.

  • in_new_ctxt (bool) – result in a newly created ciphertext

Returns:

resulting ciphertext, the input transformed or a new one

Return type:

PyCtxt

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.

Parameters:
  • ptxt (PyPtxt) – Plaintext to reduce.

  • in_new_ptxt (bool) – result in a newly created plaintext

Returns:

resulting plaintext, the input transformed or a new one

Return type:

PyPtxt

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.

Parameters:
  • ctxt (PyCtxt) – ciphertext multiplied with ctxt_other.

  • ctxt_other (PyCtxt) – ciphertext left untouched.

  • in_new_ctxt (bool) – result in a newly created ciphertext.

Returns:

resulting ciphertext, the input transformed or a new one

Return type:

PyCtxt

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.

Parameters:
  • ctxt (PyCtxt) – ciphertext whose values are multiplied with ptxt.

  • ptxt (PyPtxt) – plaintext left untouched.

Returns:

resulting ciphertext, either the input transformed or a new one

Return type:

PyCtxt

negate(self, PyCtxt ctxt, bool in_new_ctxt=False) PyCtxt

Negate PyCtxt ciphertext value/s.

Parameters:
  • ctxt (PyCtxt) – ciphertext whose values are negated.

  • in_new_ctxt (bool) – result in a newly created ciphertext

Returns:

resulting ciphertext, the input transformed or a new one

Return type:

PyCtxt

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.

Parameters:

ctxt (PyCtxt) – ciphertext to be measured.

Returns:

the noise budget level

Return type:

int

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.

Parameters:
  • p (PyPoly) – polynomial whose values are added with p_other.

  • p_other (PyPoly) – polynomial left untouched.

  • in_new_poly (bool) – result in a newly created polynomial

Returns:

resulting polynomial, the input transformed or a new one.

Return type:

PyPoly

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.

Parameters:
  • p (PyPoly) – polynomial whose values are inverted.

  • in_new_poly (bool) – result in a newly created polynomial

Returns:

resulting polynomial, the input transformed or a new one.

Return type:

PyPoly

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.

Parameters:
  • p (PyPoly) – polynomial whose values are multiplied with p_other.

  • p_other (PyPoly) – polynomial left untouched.

  • in_new_poly (bool) – result in a newly created polynomial

Returns:

resulting polynomial, the input transformed or a new one.

Return type:

PyPoly

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.

Parameters:
  • p (PyPoly) – polynomial whose values are subtracted with p_other.

  • p_other (PyPoly) – polynomial left untouched.

  • in_new_poly (bool) – result in a newly created polynomial

Returns:

resulting polynomial, the input transformed or a new one.

Return type:

PyPoly

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).

Parameters:
  • p (PyPoly) – polynomial to be inserted.

  • ctxt (PyCtxt) – base ciphertext.

  • i (int) – number of polynomial in ctxt to be set.

Returns:

None

poly_to_plaintext(self, PyPoly p, PyPtxt ptxt) void

Set the polynimial in ptxt to p.

Encoding must be consistent (TODO).

Parameters:
  • p (PyPoly) – polynomial to be inserted.

  • ptxt (PyPtxt) – base plaintext.

Returns:

None

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.

Parameters:
  • ctxt (PyCtxt) – ciphertext whose value/s are exponetiated.

  • expon (int) – exponent.

  • in_new_ctxt (bool) – result in a newly created ciphertext

Returns:

resulting ciphertext, the input transformed or a new one

Return type:

PyCtxt

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().

Parameters:
  • ctxt (PyCtxt) – ciphertext whose values are rotated.

  • k (int) – number of positions to rotate.

  • in_new_ctxt (bool) – result in a newly created ciphertext

Returns:

resulting ciphertext, the input transformed or a new one

Return type:

PyCtxt

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:

PyCtxt

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:

PyCtxt

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

square(self, PyCtxt ctxt, bool in_new_ctxt=False) PyCtxt

Square PyCtxt ciphertext value/s.

Parameters:
  • ctxt (PyCtxt) – ciphertext whose values are squared.

  • in_new_ctxt (bool) – result in a newly created ciphertext

Returns:

resulting ciphertext, the input transformed or a new one

Return type:

PyCtxt

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.

Parameters:
  • ctxt (PyCtxt) – ciphertext substracted by ctxt_other.

  • ctxt_other (PyCtxt) – ciphertext being substracted from ctxt.

  • in_new_ctxt (bool) – result in a newly created ciphertext

Returns:

resulting ciphertext, the input transformed or a new one

Return type:

PyCtxt

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.

Parameters:
  • ctxt (PyCtxt) – ciphertext substracted by ptxt.

  • ptxt (*) – plaintext substracted from ctxt.

  • in_new_ctxt (bool) – result in a newly created ciphertext

Returns:

resulting ciphertext, the input transformed or a new one

Return type:

PyCtxt

to_bytes_context(self, unicode compr_mode=u'zstd') bytes

Saves current context in a bytes string

Parameters:

compr_mode (str) – Compression. One of “none”, “zlib”, “zstd”

Returns:

Serialized Context.

Return type:

bytes

to_bytes_public_key(self, unicode compr_mode=u'zstd') bytes

Saves current public key in a bytes string

Parameters:

compr_mode (str) – Compression. One of “none”, “zlib”, “zstd”

Returns:

Serialized public key.

Return type:

bytes

to_bytes_relin_key(self, unicode compr_mode=u'zstd') bytes

Saves current relinearization key in a bytes string

Parameters:

compr_mode (str) – Compression. One of “none”, “zlib”, “zstd”

Returns:

Serialized relinearization key.

Return type:

bytes

to_bytes_rotate_key(self, unicode compr_mode=u'zstd') bytes

Saves current context in a bytes string

Parameters:

compr_mode (str) – Compression. One of “none”, “zlib”, “zstd”

Returns:

Serialized rotation key.

Return type:

bytes

to_bytes_secret_key(self, unicode compr_mode=u'zstd') bytes

Saves current secret key in a bytes string

Parameters:

compr_mode (str) – Compression. One of “none”, “zlib”, “zstd”

Returns:

Serialized secret key.

Return type:

bytes

__pyx_vtable__ = <capsule object NULL>
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))).