Package {openfhe.R}


Title: R Interface to the 'OpenFHE' Fully Homomorphic Encryption Library
Version: 1.6.1
Description: Provides an R interface to 'OpenFHE', the open-source C++ library for fully homomorphic encryption (Al Badawi and others, 2022) https://eprint.iacr.org/2022/915, which allows computation directly on encrypted data without access to the secret key. Supports the Brakerski-Fan-Vercauteren (BFV, 2012) https://eprint.iacr.org/2012/144, Brakerski-Gentry-Vaikuntanathan (BGV, 2014) <doi:10.1145/2633600>, and Cheon-Kim-Kim-Song (CKKS, 2017) https://eprint.iacr.org/2016/421 schemes for arithmetic on encrypted numbers, together with the Ducas-Micciancio (FHEW, 2015) https://eprint.iacr.org/2014/816 and Chillotti-Gama-Georgieva-Izabachene (TFHE, 2020) https://eprint.iacr.org/2018/421 schemes for evaluating arbitrary functions on encrypted bits.
License: BSD_2_clause + file LICENSE
Copyright: file inst/COPYRIGHTS
URL: https://openfheorg.github.io/openfhe.R/, https://github.com/openfheorg/openfhe.R
BugReports: https://github.com/openfheorg/openfhe.R/issues
Depends: R (≥ 4.3.0)
Imports: S7, cli, rlang, methods
Suggests: tinytest, knitr, rmarkdown
VignetteBuilder: knitr
LinkingTo: cpp11 (≥ 0.4.2)
SystemRequirements: cmake (>= 3.16), GNU make, C++17
Collate: 'openfhe-package.R' 'cpp11.R' 'openfhe-object.R' 'fast-new.R' 'enums.R' 'generics.R' 'element-params.R' 'crypto-parameters.R' 'encoding-params.R' 'params.R' 'params-getters.R' 'context.R' 'cryptocontext-getters.R' 'keys.R' 'plaintext.R' 'plaintext-accessors.R' 'params-setters.R' 'ciphertext.R' 'ciphertext-accessors.R' 'methods-encrypt.R' 'methods-eval.R' 'methods-eval-extra.R' 'methods-eval-backlog.R' 'methods-ckks.R' 'series-powers.R' 'multiparty.R' 'eval-key-map.R' 'secret-sharing.R' 'interactive-bootstrap.R' 'binfhe.R' 'object-accessors.R' 'key-switching.R' 'schemelet.R' 'functional-bootstrapping.R' 'serialization.R' 'binfhe-keys.R' 'scheme-switching.R' 'scheme-switching-serializer.R' 'operators.R' 'tolerance.R' 'utils.R' 'zzz.R'
Encoding: UTF-8
Config/roxygen2/version: 8.1.1
NeedsCompilation: yes
Packaged: 2026-11-13 04:51:25 UTC; naras
Author: Balasubramanian Narasimhan ORCID iD [aut, cre, cph], New Jersey Institute of Technology [cph] (OpenFHE C++ library, inst/openfhe/src), Duality Technologies, Inc. [ctb, cph] (OpenFHE C++ library, inst/openfhe/src), Samuel Neves [ctb, cph] (BLAKE2 reference implementation, inst/openfhe/src/core), Jean-Philippe Aumasson [ctb, cph] (BLAKE2X reference implementation, inst/openfhe/src/core), Randolph Voorhies [ctb, cph] (cereal serialization library, inst/openfhe/cereal), Shane Grant [ctb, cph] (cereal serialization library, inst/openfhe/cereal), Juan Pedro Bolivar Puente [ctb, cph] (cereal std::optional and std::variant support), THL A29 Limited, a Tencent company [cph] (RapidJSON, bundled in inst/openfhe/cereal), Milo Yip [ctb, cph] (RapidJSON, bundled in inst/openfhe/cereal), Alexander Chemeris [ctb, cph] (msinttypes, bundled in inst/openfhe/cereal), Marcin Kalicinski [ctb, cph] (RapidXml, bundled in inst/openfhe/cereal), Rene Nyffenegger [ctb, cph] (base64 encoder/decoder, bundled in inst/openfhe/cereal)
Maintainer: Balasubramanian Narasimhan <naras@stanford.edu>
Repository: CRAN
Date/Publication: 2026-11-13 16:20:02 UTC

openfhe.R: R Interface to the 'OpenFHE' Fully Homomorphic Encryption Library

Description

logo

Provides an R interface to 'OpenFHE', the open-source C++ library for fully homomorphic encryption (Al Badawi and others, 2022) https://eprint.iacr.org/2022/915, which allows computation directly on encrypted data without access to the secret key. Supports the Brakerski-Fan-Vercauteren (BFV, 2012) https://eprint.iacr.org/2012/144, Brakerski-Gentry-Vaikuntanathan (BGV, 2014) doi:10.1145/2633600, and Cheon-Kim-Kim-Song (CKKS, 2017) https://eprint.iacr.org/2016/421 schemes for arithmetic on encrypted numbers, together with the Ducas-Micciancio (FHEW, 2015) https://eprint.iacr.org/2014/816 and Chillotti-Gama-Georgieva-Izabachene (TFHE, 2020) https://eprint.iacr.org/2018/421 schemes for evaluating arbitrary functions on encrypted bits.

Author(s)

Maintainer: Balasubramanian Narasimhan naras@stanford.edu (ORCID) [copyright holder]

Authors:

Other contributors:

See Also

Useful links:


BFV Parameters

Description

Constructor for the BFV scheme's CCParams surface. Every argument maps 1:1 to an upstream ⁠CCParams<CryptoContextBFVRNS>::Set*⁠ method whose override is not disabled in the BFV specialization. The 13 setters that BFV explicitly disables (SetScalingTechnique, SetFirstModSize, SetPRENumHops, SetExecutionMode, …) are not exposed here.

Usage

BFVParams(
  plaintext_modulus = NULL,
  multiplicative_depth = NULL,
  scaling_mod_size = NULL,
  batch_size = NULL,
  security_level = NULL,
  secret_key_dist = NULL,
  key_switch_technique = NULL,
  ring_dim = NULL,
  digit_size = NULL,
  num_large_digits = NULL,
  standard_deviation = NULL,
  multiparty_mode = NULL,
  threshold_num_of_parties = NULL,
  multiplication_technique = NULL,
  max_relin_sk_deg = NULL,
  pre_mode = NULL,
  eval_add_count = NULL,
  key_switch_count = NULL,
  encryption_technique = NULL
)

Arguments

plaintext_modulus

Integer modulus t for the BFV plaintext space. BFV plaintexts are elements of Z_t[x]/Phi_m(x) and every homomorphic operation is performed modulo t. Must be a prime (or a composite supporting NTT in the batching case) and must be at least large enough that the end-to-end computation does not wrap modulo t. Typical values: 65537 (the smallest batching-friendly prime) for small-integer arithmetic, 786433 or larger when the operands or intermediate sums are larger. There is no scheme-level default — the user must supply one.

multiplicative_depth

Integer depth of the multiplication circuit the context must support. BFV and BGV grow ciphertext noise with each multiplication, and the ring modulus q is sized by OpenFHE to survive exactly multiplicative_depth successive multiplications plus an EvalAdd chain between them. Set to the exact depth of your circuit; setting it too small causes correctness failure at decrypt, setting it too large inflates ring dimension and slows every operation. Couples tightly to security_level (together they pin ring_dim).

scaling_mod_size

Integer bit-size of each intermediate scaling modulus in the RNS decomposition of q. Default leaves OpenFHE to choose from its internal tables (typically 60 bits). Override only when you know your depth budget needs a tighter value; the upstream simple-integers example uses the default.

batch_size

Integer number of SIMD-batched plaintext slots. Default is ring_dim / 2 under the full-packing convention. Set to a smaller power of two when your input vector is short and rotation cost dominates the circuit (the inner-product idiom). Must divide ring_dim / 2. Couples to ring_dim.

security_level

One of SecurityLevel$HEStd_128_classic (default when unset), HEStd_192_classic, HEStd_256_classic, and their ⁠_quantum⁠ counterparts. Fixes the target hardness assumption and, together with multiplicative_depth, determines the minimum ring dimension via the upstream lattice-parameters tables in core/lattice/stdlatticeparms.h.

secret_key_dist

One of SecretKeyDist$GAUSSIAN, UNIFORM_TERNARY (default under classic lattice parameters), or SPARSE_TERNARY. Controls the coefficient distribution of the secret key. Change only for research scenarios that demand a specific distribution; every production vignette uses the default.

key_switch_technique

One of KeySwitchTechnique$BV (default for BFV) or HYBRID. BV produces smaller evaluation keys and is the simpler option; HYBRID is relevant only when you are also setting num_large_digits and benchmarking rotation cost.

ring_dim

Integer power-of-two lattice ring dimension. Default (NULL) asks OpenFHE to compute the minimum ring dimension that satisfies security_level at the chosen multiplicative_depth. Override only to force a larger value than the auto-selection, typically to reserve headroom for later parameter sweeps.

digit_size

Integer r for BV key-switching: the base-2^r digit decomposition of the ciphertext during a key-switch. Default 0L selects the upstream default. Larger values decrease the number of digit multiplications at the cost of larger per-digit noise.

num_large_digits

Integer number of digit groupings in HYBRID key switching. Only meaningful when key_switch_technique = KeySwitchTechnique$HYBRID; ignored otherwise. Default 0L lets OpenFHE pick.

standard_deviation

Numeric standard deviation of the Gaussian error distribution used during key generation and encryption. Default (NULL) uses the upstream default 3.19. Override only in research scenarios.

multiparty_mode

One of MultipartyMode$FIXED_NOISE_MULTIPARTY or NOISE_FLOODING_MULTIPARTY. Selects between threshold-FHE with fixed noise (no flooding) and noise-flooding-protected threshold-FHE. Both cox-threshold and CVXR-consensus-ADMM vignettes rely on threshold paths; leave at upstream default unless you are intentionally tuning the leakage/performance trade-off.

threshold_num_of_parties

Integer count of parties in an n-of-n threshold protocol. Ignored in non-threshold contexts. The cox-threshold vignette uses 2; the threshold-fhe-5p Python example uses 5.

multiplication_technique

One of MultiplicationTechnique$BEHZ, HPS, HPSPOVERQ, HPSPOVERQLEVELED. BFV-specific choice of how the plaintext modulus interacts with the ciphertext modulus during multiply. Default upstream is HPSPOVERQLEVELED; override only if you are benchmarking multiplication-path variants.

max_relin_sk_deg

maximum degree of the secret key that can be relinearized. Upstream default is 2. No current vignette or Python example exercises this; the cpp11 binding is in place so a later release can promote it without a recompile.

pre_mode

proxy re-encryption mode (PREMode$NOT_SET, INDCPA, FIXED_NOISE_HRA, NOISE_FLOODING_HRA). Only meaningful if the PRE feature is enabled on the context. No current vignette uses PRE.

eval_add_count

upstream noise-budget hint: maximum additions between multiplications. Used only by the noise-flooding path. Default 0.

key_switch_count

upstream noise-budget hint: maximum key-switch count. Default 0.

encryption_technique

BFV-specific encryption variant (EncryptionTechnique$STANDARD or EXTENDED). Default STANDARD.

Value

A BFVParams S7 object.


BGV Parameters

Description

Constructor for the BGV scheme's CCParams surface. Every argument maps 1:1 to an enabled ⁠CCParams<CryptoContextBGVRNS>::Set*⁠ method. The 10 BGV-disabled setters (SetEncryptionTechnique, SetMultiplicationTechnique, SetExecutionMode, …) are not exposed.

Usage

BGVParams(
  plaintext_modulus = NULL,
  multiplicative_depth = NULL,
  scaling_mod_size = NULL,
  scaling_technique = NULL,
  batch_size = NULL,
  first_mod_size = NULL,
  security_level = NULL,
  secret_key_dist = NULL,
  key_switch_technique = NULL,
  ring_dim = NULL,
  digit_size = NULL,
  num_large_digits = NULL,
  standard_deviation = NULL,
  multiparty_mode = NULL,
  threshold_num_of_parties = NULL,
  max_relin_sk_deg = NULL,
  pre_mode = NULL,
  statistical_security = NULL,
  num_adversarial_queries = NULL,
  eval_add_count = NULL,
  key_switch_count = NULL,
  pre_num_hops = NULL
)

Arguments

plaintext_modulus

Integer modulus t for the BGV plaintext space. See the BFV entry for full semantics; BGV shares the same Z_t-valued plaintext model.

multiplicative_depth

Integer multiplicative depth; sizes the ring modulus q. See the BFV entry for the full coupling.

scaling_mod_size

Integer bit-size per scaling modulus in the modulus chain.

scaling_technique

One of ScalingTechnique$FIXEDMANUAL, FIXEDAUTO, FLEXIBLEAUTO (upstream default), FLEXIBLEAUTOEXT. Selects whether the scheme rescales automatically between multiplications (⁠*AUTO*⁠) or leaves it to the caller (FIXEDMANUAL). Every vignette uses an auto mode; pick FIXEDMANUAL only if you need deterministic control over rescale insertion.

batch_size

Integer SIMD slot count; see the BFV entry.

first_mod_size

Integer bit size of the first (largest) prime in the modulus chain. Default leaves OpenFHE to pick. Override only when tuning the noise budget at the top of the chain.

security_level

See the BFV entry.

secret_key_dist

See the BFV entry.

key_switch_technique

See the BFV entry. BGV accepts both BV and HYBRID.

ring_dim

See the BFV entry.

digit_size

See the BFV entry.

num_large_digits

See the BFV entry.

standard_deviation

See the BFV entry.

multiparty_mode

See the BFV entry.

threshold_num_of_parties

See the BFV entry.

max_relin_sk_deg

see the BFV entry.

pre_mode

see the BFV entry.

statistical_security

statistical security parameter (bits), used by the noise-flooding decryption path.

num_adversarial_queries

upper bound on the number of adversarial queries the noise-flooding path must survive.

eval_add_count

see the BFV entry.

key_switch_count

see the BFV entry.

pre_num_hops

maximum number of hops for proxy re-encryption in BGV. Only meaningful if the PRE feature is enabled.

Value

A BGVParams S7 object.


BinFHE context (Binary FHE)

Description

BinFHE context (Binary FHE)

Usage

BinFHEContext(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class BinFHEContext, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ boolean-circuit context. It is the BinFHE counterpart of CryptoContext and is deliberately a different class, so a CryptoContext cannot be passed where a BinFHE context belongs or the other way round. Obtain one from bin_fhe_context() rather than by calling this constructor directly.


Binary FHE Methods

Description

Mirrors the C++ enum BINFHE_METHOD in binfhe/binfhe-constants.h.

Usage

BinFHEMethod

Value

A named list of 4 integer scalars, each the value of the OpenFHE C++ enumerator of the same name, selecting the bootstrapping method a boolean-circuit context uses: AP (Alperin-Sheriff-Peikert), GINX (Gama-Izabachene-Nguyen-Xie, the default) or LMKCDEY. INVALID_METHOD marks an unset value. Pass an element as the method argument of bin_fhe_context().


Binary FHE Output Types

Description

Mirrors the C++ enum BINFHE_OUTPUT in binfhe/binfhe-constants.h.

Usage

BinFHEOutput

Value

A named list of 5 integer scalars, each the value of the OpenFHE C++ enumerator of the same name, describing the form the ciphertext produced by a BinFHE operation should take: FRESH (noise reset to the level of a fresh encryption), BOOTSTRAPPED, LARGE_DIM and SMALL_DIM (the LWE dimension the result is expressed in). INVALID_OUTPUT marks an unset value. Pass an element as the output argument of bin_encrypt().


Binary FHE Parameter Sets

Description

Mirrors the C++ enum BINFHE_PARAMSET in binfhe/binfhe-constants.h, whose enumerators are numbered sequentially from 0.

Usage

BinFHEParamSet

Details

The integer values belong to the vendored OpenFHE release. OpenFHE 1.6 reordered the list, so an integer saved from an earlier version of this package names a different parameter set; always refer to an element by name.

Value

A named list of 112 integer scalars, each the value of the OpenFHE C++ enumerator of the same name. An element names a pre-tabulated set of lattice parameters for the boolean-circuit (BinFHE) schemes: TOY and MEDIUM are insecure sizes for experimentation, and the STD128, STD192 and STD256 families target the corresponding bits of security against classical attacks, with the Q suffix targeting quantum attacks and the ⁠_3⁠ and ⁠_4⁠ suffixes 3- and 4-input gates. The LPF prefix marks a variant with a lower probability of failure. Sets without a method suffix are tuned for the GINX bootstrapping method and may be used with any method; the ⁠_LMKCDEY⁠ suffix marks a set for the Lee-Micciancio-Kim-Choi-Deryabin-Eom-Yoo method only, and the ⁠_AP⁠ suffix a set for the AP method only. SIGNED_MOD_TEST and TOY_MULTI_BASE are test sets. Pass an element as the paramset argument of bin_fhe_context().


Binary Gate Types

Description

Mirrors the C++ enum BINGATE in binfhe/binfhe-constants.h, whose enumerators are numbered sequentially from 0.

Usage

BinGate

Value

A named list of 14 integer scalars, each the value of the OpenFHE C++ enumerator of the same name, naming the boolean gate to evaluate on encrypted bits: the two-input gates OR, AND, NOR, NAND, XOR, XNOR and the faster XOR_FAST, XNOR_FAST; the three- and four-input AND3, OR3, AND4, OR4; and MAJORITY and CMUX. Pass an element as the gate argument of eval_bin_gate().


CKKS Data Type

Description

Mirrors the C++ enum CKKSDataType in pke/constants-defs.h.

Usage

CKKSDataType

Value

A named list of 2 integer scalars, each the value of the OpenFHE C++ enumerator of the same name, declaring whether the slots of a CKKS ciphertext hold REAL or COMPLEX numbers.


CKKS Parameters

Description

Constructor for the CKKS scheme's CCParams surface. Every argument maps 1:1 to an enabled ⁠CCParams<CryptoContextCKKSRNS>::Set*⁠ method. The 8 CKKS-disabled setters (SetPlaintextModulus, SetEvalAddCount, SetKeySwitchCount, SetEncryptionTechnique, SetMultiplicationTechnique, SetPRENumHops, SetMultipartyMode, SetThresholdNumOfParties) are not exposed. CKKS is a fixed-point scheme over the complex numbers and has no plaintext modulus; threshold_num_of_parties is currently CKKS-disabled upstream even though the scheme supports threshold variants via a separate code path.

Usage

CKKSParams(
  multiplicative_depth = NULL,
  scaling_mod_size = NULL,
  scaling_technique = NULL,
  batch_size = NULL,
  first_mod_size = NULL,
  security_level = NULL,
  secret_key_dist = NULL,
  key_switch_technique = NULL,
  ring_dim = NULL,
  digit_size = NULL,
  num_large_digits = NULL,
  interactive_boot_compression_level = NULL,
  standard_deviation = NULL,
  register_word_size = NULL,
  ckks_data_type = NULL,
  max_relin_sk_deg = NULL,
  pre_mode = NULL,
  execution_mode = NULL,
  decryption_noise_mode = NULL,
  noise_estimate = NULL,
  desired_precision = NULL,
  statistical_security = NULL,
  num_adversarial_queries = NULL,
  composite_degree = NULL
)

Arguments

multiplicative_depth

See the BFV entry.

scaling_mod_size

Integer bit-size of the CKKS rescaling factor (typically 50 or 59 bits). Together with multiplicative_depth this pins the modulus chain and therefore the precision budget available at the bottom of the circuit. Upstream default varies by scaling technique; when in doubt use the value the matching Python example uses.

scaling_technique

See the BGV entry. CKKS additionally supports NORESCALE (debug-only) and the ⁠COMPOSITESCALING*⁠ modes.

batch_size

See the BFV entry.

first_mod_size

See the BGV entry.

security_level

See the BFV entry.

secret_key_dist

See the BFV entry.

key_switch_technique

See the BFV entry. CKKS typically benefits from HYBRID.

ring_dim

See the BFV entry.

digit_size

See the BFV entry.

num_large_digits

See the BFV entry.

interactive_boot_compression_level

One of CompressionLevel$COMPACT (2) or SLACK (3). Controls the compression level to which the input ciphertext is brought before interactive multi-party bootstrapping. COMPACT is more efficient but assumes a stronger security model; SLACK is less efficient with weaker assumptions. Used by the ⁠tckks- interactive-mp-bootstrapping*⁠ Python examples.

standard_deviation

See the BFV entry.

register_word_size

Integer word size (in bits) for the register-based multi-precision arithmetic path. Default leaves it to upstream. Used by the simple-real-numbers-composite- scaling Python example.

ckks_data_type

One of CKKSDataType$REAL (default) or COMPLEX. Selects whether CKKS plaintexts are modeled as real vectors or complex vectors. All current R vignettes use REAL.

max_relin_sk_deg

see the BFV entry.

pre_mode

see the BFV entry.

execution_mode

one of ExecutionMode$EXEC_EVALUATION (default) or EXEC_NOISE_ESTIMATION. The noise-estimation mode is only used by the adversarial-query noise-flooding path.

decryption_noise_mode

one of DecryptionNoiseMode$FIXED_NOISE_DECRYPT (default) or NOISE_FLOODING_DECRYPT.

noise_estimate

numeric noise estimate used by the noise-flooding path. Paired with execution_mode = EXEC_NOISE_ESTIMATION.

desired_precision

numeric target precision (in bits) for the noise-flooding path.

statistical_security

see the BGV entry.

num_adversarial_queries

see the BGV entry.

composite_degree

composite scaling degree for the ⁠COMPOSITESCALING*⁠ scaling techniques. Upstream default 0 means single-prime scaling.

Value

A CKKSParams S7 object.


Ciphertext class

Description

Wraps an encrypted OpenFHE ciphertext. Supports arithmetic operators +, -, * which dispatch to homomorphic operations.

Usage

Ciphertext(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class Ciphertext, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ ciphertext. Ciphertexts are produced by encrypt() and by the ⁠eval_*()⁠ family rather than by calling this constructor directly, and they carry the encrypted vector together with the level and scaling-factor bookkeeping the scheme needs.


Compression Level (interactive multi-party bootstrap)

Description

Mirrors the C++ enum CompressionLevel in pke/constants-defs.h. Note that the values start at 2, not 0: the header explains that compression levels 0 and 1 are not supported and that the remaining values are deliberately not renumbered.

Usage

CompressionLevel

Value

A named list of 2 integer scalars, each the value of the OpenFHE C++ enumerator of the same name, naming how far a ciphertext is compressed before the interactive bootstrapping round-trip: COMPACT (2) sends the least data but is only safe when the result is decrypted immediately, while SLACK (3) leaves room for further computation on the result. Pass an element as the interactive_boot_compression_level argument of CKKSParams() or fhe_context().


Crypto Context

Description

Crypto Context

Usage

CryptoContext(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class CryptoContext, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ crypto context. The context owns the scheme parameters and the registry of evaluation keys, and is the first argument to most operations. Obtain one from fhe_context() rather than by calling this constructor directly.


Crypto Parameters (opaque)

Description

Wraps ⁠std::shared_ptr<CryptoParametersBase<DCRTPoly>>⁠ on the C++ side. Returned by get_crypto_parameters(cc) and used as an opaque token for RNS-level parameter accessors such as get_scaling_factor_real, get_key_switch_technique, etc. This class ships as scaffolding only: the S7 class definition is in place so that the getter wiring can treat it as already defined, but there is no constructor path from R.

Usage

CryptoParameters(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class CryptoParameters, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ ⁠CryptoParametersBase<DCRTPoly>⁠. It is an opaque token: its contents are read with the RNS-level accessors rather than from R, and it is obtained from get_crypto_parameters() rather than by calling this constructor directly.


A ring element of a ciphertext

Description

An element of the polynomial ring, in the double-CRT (RNS) representation OpenFHE computes in. A ciphertext is a short list of them. The class is an opaque handle, as in openfhe-python: it has no methods of its own and exists so that the elements of one ciphertext can be read with get_elements() and written to another with set_elements().

Usage

DCRTPoly(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class DCRTPoly, inheriting from OpenFHEObject.


Decryption Noise Mode

Description

Mirrors the C++ enum DecryptionNoiseMode in pke/constants-defs.h.

Usage

DecryptionNoiseMode

Value

A named list of 2 integer scalars, each the value of the OpenFHE C++ enumerator of the same name: FIXED_NOISE_DECRYPT decrypts with a fixed noise estimate, while NOISE_FLOODING_DECRYPT floods the result with extra noise so that the decryption itself leaks nothing about the circuit. Pass an element as the decryption_noise_mode argument of CKKSParams() or fhe_context().


Distribution Type (lattice parameters)

Description

Mirrors the C++ enum DistributionType in core/lattice/stdlatticeparms.h.

Usage

DistributionType

Value

A named list of 3 integer scalars, each the value of the OpenFHE C++ enumerator of the same name, naming the secret distribution a row of the HomomorphicEncryption.org standard parameter tables applies to: HEStd_uniform, HEStd_error or HEStd_ternary.


Element Parameters (opaque)

Description

Wraps ⁠std::shared_ptr<typename DCRTPoly::Params>⁠ on the C++ side. Used by the params argument of CKKS plaintext factories and returned by get_element_params(). This class ships as scaffolding only: no constructor surface other than wrapping an existing external pointer.

Usage

ElementParams(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class ElementParams, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ DCRTPoly::Params. It is an opaque token describing the ring the polynomials live in, obtained from get_element_params() and passed on to the CKKS plaintext factories.


Encoding Parameters (opaque)

Description

Wraps ⁠std::shared_ptr<EncodingParamsImpl>⁠ on the C++ side. Returned by get_encoding_params(cc) and by Plaintext::GetEncodingParams() once the corresponding Plaintext accessor lands. This class ships as scaffolding only: the S7 class definition is in place so that the getter wiring can treat it as already defined, but there is no constructor path from R.

Usage

EncodingParams(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class EncodingParams, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ EncodingParamsImpl. It is an opaque token describing how values are packed into a plaintext, obtained from get_encoding_params() rather than by calling this constructor directly.


Encryption Technique

Description

Mirrors the C++ enum EncryptionTechnique in pke/constants-defs.h.

Usage

EncryptionTechnique

Value

A named list of 2 integer scalars, each the value of the OpenFHE C++ enumerator of the same name: STANDARD encrypts in the ciphertext modulus, while EXTENDED encrypts in an enlarged modulus, which lowers the noise BFV multiplication starts from. Pass an element as the encryption_technique argument of BFVParams() or fhe_context().


EvalKey class for multi-party key operations

Description

EvalKey class for multi-party key operations

Usage

EvalKey(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class EvalKey, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ ⁠EvalKey<DCRTPoly>⁠. An evaluation key is the public material that lets the computing party carry out one operation — a relinearization, a rotation, or a re-encryption — without the secret key. Obtain one from multi_key_switch_gen() or the rest of the ⁠multi_*()⁠ family rather than by calling this constructor directly.


Map of homomorphic evaluation keys

Description

Opaque S7 wrapper around a ⁠shared_ptr<std::map<uint32_t, EvalKey<DCRTPoly>>>⁠. Produced by the ⁠multi_eval_*_key_gen()⁠ family and by get_eval_sum_key_map() / get_eval_automorphism_key_map(); consumed by multi_add_eval_sum_keys(), multi_add_eval_automorphism_keys(), insert_eval_sum_key(), and insert_eval_automorphism_key(). The map is keyed by a rotation/automorphism index and carries one EvalKey per index.

Usage

EvalKeyMap(ptr = NULL)

Arguments

ptr

External pointer (internal use).

Details

Users do not construct or index into an EvalKeyMap directly — it is a transport format for the multi-party eval-key protocols. In a single-user protocol the same data is tracked inside the CryptoContext's internal key registry (populated by EvalSumKeyGen() / EvalRotateKeyGen()) and is only exposed as an EvalKeyMap when the distributed-party flow needs to exchange it.

Value

An S7 object of class EvalKeyMap, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ ⁠std::map<uint32_t, EvalKey<DCRTPoly>>⁠. It carries one evaluation key per rotation or automorphism index and acts as the transport format for the multi-party key protocols; it is produced by the ⁠multi_eval_*_key_gen()⁠ family rather than by calling this constructor directly.


Execution Mode

Description

Mirrors the C++ enum ExecutionMode in pke/constants-defs.h.

Usage

ExecutionMode

Value

A named list of 2 integer scalars, each the value of the OpenFHE C++ enumerator of the same name: EXEC_EVALUATION runs the computation normally, while EXEC_NOISE_ESTIMATION runs it only to measure the noise growth, which is the first of the two passes needed when decryption uses noise flooding. Pass an element as the execution_mode argument of CKKSParams() or fhe_context().


Precomputed digit decomposition for hoisted rotations

Description

Returned by eval_fast_rotation_precompute() and consumed by eval_fast_rotation(). Hoisting amortizes the per-rotation decomposition over many rotations of the same source ciphertext.

Usage

FastRotationPrecomputation(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class FastRotationPrecomputation, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ digit decomposition. It caches the work that is common to every rotation of one source ciphertext; obtain one from eval_fast_rotation_precompute() and pass it to eval_fast_rotation() rather than calling this constructor directly.


PKE Scheme Features (bitmask)

Description

Mirrors the C++ enum PKESchemeFeature in pke/constants-defs.h. The values are bit flags, so several may be combined with bitwOr() to describe a set of capabilities.

Usage

Feature

Value

A named list of 8 integer scalars. Each element carries the integer value the OpenFHE C++ enumerator of the same name has, and names a capability of a crypto context: PKE (encryption and decryption), KEYSWITCH, PRE (proxy re-encryption), LEVELEDSHE (leveled homomorphic arithmetic), ADVANCEDSHE, MULTIPARTY, FHE (bootstrapping) and SCHEMESWITCH. Pass an element to enable_feature() to turn that capability on for a context.


Polynomial representation

Description

Mirrors the C++ enum Format in core/utils/inttypes.h: whether a ring element is held in EVALUATION (number-theoretic transform) or COEFFICIENT representation. Used by set_format().

Usage

Format

Value

A named list of 2 integer scalars, each the value of the OpenFHE C++ enumerator of the same name.


Key Pair

Description

Contains a public key and a secret (private) key.

Usage

KeyPair(public = NULL, secret = NULL)

Arguments

public

A PublicKey

secret

A PrivateKey

Value

An S7 object of class KeyPair with two properties, public (a PublicKey) and secret (a PrivateKey), which are the two halves of one freshly generated key. Obtain one from key_gen() rather than by calling this constructor directly.


Key Switching Techniques

Description

Mirrors the C++ enum KeySwitchTechnique in pke/constants-defs.h.

Usage

KeySwitchTechnique

Value

A named list of 3 integer scalars, each the value of the OpenFHE C++ enumerator of the same name. BV selects the Brakerski-Vaikuntanathan digit-decomposition key switch and HYBRID the hybrid variant, which is the usual choice; INVALID_KS_TECH marks an unset value. Pass an element as the key_switch_technique argument of CKKSParams(), BFVParams(), BGVParams() or fhe_context().


Key Generation Mode

Description

Mirrors the C++ enum KEYGEN_MODE in binfhe/binfhe-constants.h.

Usage

KeygenMode

Value

A named list of 2 integer scalars, each the value of the OpenFHE C++ enumerator of the same name: SYM_ENCRYPT generates only the material needed for symmetric-key encryption, while PUB_ENCRYPT additionally generates a public key. Pass an element as the keygen_mode argument of bin_bt_key_gen().


LWE Ciphertext (Binary FHE)

Description

LWE Ciphertext (Binary FHE)

Usage

LWECiphertext(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class LWECiphertext, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ LWE ciphertext. This is the encrypted-bit type the boolean- circuit (BinFHE) schemes operate on; obtain one from bin_encrypt() or from a gate evaluation rather than by calling this constructor directly.


LWE key pair (Binary FHE)

Description

The public key and the matching secret key from bin_key_gen_pair(). is_good() is TRUE when both are present.

Usage

LWEKeyPair(public = NULL, secret = NULL)

Arguments

public

An LWEPublicKey.

secret

An LWEPrivateKey.

Value

An S7 object of class LWEKeyPair with properties public and secret.


LWE Private Key (Binary FHE)

Description

LWE Private Key (Binary FHE)

Usage

LWEPrivateKey(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class LWEPrivateKey, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ LWE secret key. It both encrypts and decrypts in the boolean-circuit (BinFHE) schemes; obtain one from bin_key_gen() rather than by calling this constructor directly.


LWE public key (Binary FHE)

Description

The public key of the LWE scheme of a BinFHE context, from bin_key_gen_pair() or bin_pub_key_gen(). bin_encrypt() accepts it in place of the secret key.

Usage

LWEPublicKey(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class LWEPublicKey, inheriting from OpenFHEObject.


LWE switching key (Binary FHE)

Description

A key that switches an LWE ciphertext of modulus Q and dimension N to one of modulus q and dimension n, from bin_key_switch_gen() or get_switch_key(). It is an opaque handle, as in openfhe-python.

Usage

LWESwitchingKey(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class LWESwitchingKey, inheriting from OpenFHEObject.


Multiparty Mode

Description

Mirrors the C++ enum MultipartyMode in pke/constants-defs.h.

Usage

MultipartyMode

Value

A named list of 3 integer scalars, each the value of the OpenFHE C++ enumerator of the same name, selecting how a threshold context masks the secret shares: FIXED_NOISE_MULTIPARTY adds a fixed amount of noise, while NOISE_FLOODING_MULTIPARTY adds enough to give provable circuit privacy at a higher cost. INVALID_MULTIPARTY_MODE marks an unset value. Pass an element as the multiparty_mode argument of BFVParams(), BGVParams() or fhe_context().


Multiplication Technique (BFV)

Description

Mirrors the C++ enum MultiplicationTechnique in pke/constants-defs.h.

Usage

MultiplicationTechnique

Value

A named list of 4 integer scalars, each the value of the OpenFHE C++ enumerator of the same name, selecting the algorithm BFV uses for homomorphic multiplication: BEHZ (Bajard-Eynard-Hasan-Zucca) or the Halevi-Polyakov-Shoup variants HPS, HPSPOVERQ and HPSPOVERQLEVELED. Pass an element as the multiplication_technique argument of BFVParams() or fhe_context().


Base class for OpenFHE objects

Description

All OpenFHE objects (CryptoContext, Ciphertext, Plaintext, Keys, etc.) inherit from this class. It holds an external pointer to a C++ shared_ptr.

Usage

OpenFHEObject(ptr = NULL)

Arguments

ptr

External pointer to C++ object (internal use)

Value

An S7 object of class OpenFHEObject, the base class every object in this package inherits from. It has a single property, ptr, holding an external pointer to the underlying C++ shared_ptr. Constructing one directly is of no use; the class exists so that methods can dispatch on the common parent and so that the pointer is managed in one place.


Proxy Re-encryption Mode

Description

Mirrors the C++ enum ProxyReEncryptionMode in pke/constants-defs.h. The R-side name PREMode is a shortened form, the same pattern as Feature for PKESchemeFeature.

Usage

PREMode

Value

A named list of 4 integer scalars, each the value of the OpenFHE C++ enumerator of the same name, naming the security notion the re-encryption key should satisfy: INDCPA, FIXED_NOISE_HRA or NOISE_FLOODING_HRA, the last two being honest-re-encryption-attack secure. NOT_SET disables proxy re-encryption. Pass an element as the pre_mode argument of CKKSParams(), BFVParams(), BGVParams() or fhe_context().


Plaintext

Description

Plaintext

Usage

Plaintext(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class Plaintext, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ plaintext. A plaintext holds an encoded but unencrypted vector together with its encoding type; obtain one from a ⁠make_*_plaintext()⁠ factory or from decrypt() rather than by calling this constructor directly, and read its contents with get_packed_value(), get_real_value() and the other accessors.


Plaintext Encoding Types

Description

Mirrors the C++ enum PlaintextEncodings in pke/constants-defs.h.

Usage

PlaintextEncodings

Value

A named list of 5 integer scalars, each the value of the OpenFHE C++ enumerator of the same name, naming how values are laid out inside a plaintext polynomial: COEF_PACKED_ENCODING, PACKED_ENCODING (integer SIMD slots), STRING_ENCODING and CKKS_PACKED_ENCODING (approximate real or complex slots). INVALID_ENCODING marks an unset value. This is the value reported by get_encoding_type() on a Plaintext.


An RLWE ciphertext

Description

The pair ⁠{b, a}⁠ of polynomials over one large modulus that the schemelet_ functions produce and consume. The class is an opaque handle, as in openfhe-python. PolyVector() makes an empty one.

Usage

PolyVector(ptr = NULL)

switch_modulus(x, modulus)

Arguments

ptr

External pointer (internal use). NULL (default) makes an empty vector.

x

A PolyVector.

modulus

The new modulus: a string of decimal digits, or a whole number of at most 2^53.

Details

length() gives the number of polynomials. clone() returns a copy. switch_modulus() changes the modulus of every polynomial in place, keeping the residues, and x - y subtracts two ciphertexts element by element.

schemelet_mod_switch() and switch_modulus() change the object they are given. Assigning a PolyVector to another name does not copy it; use clone() for a copy that later changes do not reach.

Value

PolyVector(): an S7 object of class PolyVector, inheriting from OpenFHEObject. switch_modulus(): x, invisibly.

See Also

schemelet_encrypt_coeff()


Private Key

Description

Private Key

Usage

PrivateKey(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class PrivateKey, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ secret key. This is the key decrypt() takes; obtain one as the secret element of the KeyPair returned by key_gen() rather than by calling this constructor directly.


Public Key

Description

Public Key

Usage

PublicKey(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class PublicKey, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ public key. This is the key encrypt() takes; obtain one as the public element of the KeyPair returned by key_gen() rather than by calling this constructor directly.


Bootstrapping key (Binary FHE)

Description

The refreshing key, switching key and public key that bin_bt_key_gen() generates, as one object, from get_bt_key(). It is an opaque handle, as in openfhe-python: write it to a file with fhe_serialize() and load it into a context with bin_bt_key_load().

Usage

RingGSWBTKey(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class RingGSWBTKey, inheriting from OpenFHEObject.


Scaling Techniques (CKKS)

Description

Mirrors the C++ enum ScalingTechnique in pke/constants-defs.h.

Usage

ScalingTechnique

Value

A named list of 8 integer scalars, each the value of the OpenFHE C++ enumerator of the same name. The element chosen tells a CKKS context how to manage the scaling factor between multiplications: FIXEDMANUAL leaves rescaling to the caller, FIXEDAUTO and the ⁠FLEXIBLE*⁠ variants rescale automatically with increasing precision, the ⁠COMPOSITESCALING*⁠ variants split the scaling factor across several moduli, and NORESCALE disables rescaling. INVALID_RS_TECHNIQUE marks an unset value. Pass an element as the scaling_technique argument of CKKSParams(), BGVParams() or fhe_context().


Parameters of scheme switching

Description

The parameter object eval_ckks_to_fhew_setup() and eval_scheme_switching_setup() take. SchSwchParams() makes one with the library defaults; the set_ functions on this page change one field each and return the object invisibly, so a parameter object is built step by step as in the OpenFHE examples.

Usage

SchSwchParams(ptr = NULL)

set_security_level_ckks(params, value)

set_security_level_fhew(params, value)

set_arbitrary_function_evaluation(params, value)

set_use_dynamic_mode_fhew(params, value)

set_compute_argmin(params, value)

set_one_hot_encoding(params, value)

set_use_alt_argmin(params, value)

set_num_slots_ckks(params, value)

set_num_values(params, value)

set_ctxt_mod_size_fhew_large_prec(params, value)

set_ctxt_mod_size_fhew_intermed_swch(params, value)

set_b_step_ltr_ckks_to_fhew(params, value)

set_b_step_ltr_fhew_to_ckks(params, value)

set_level_ltr_ckks_to_fhew(params, value)

set_level_ltr_fhew_to_ckks(params, value)

set_ring_dimension(params, value)

set_initial_ckks_modulus(params, value)

set_params_from_ckks_cryptocontext_called(params)

get_security_level_ckks(params)

get_security_level_fhew(params)

get_arbitrary_function_evaluation(params)

get_use_dynamic_mode_fhew(params)

get_compute_argmin(params)

get_one_hot_encoding(params)

get_use_alt_argmin(params)

get_num_slots_ckks(params)

get_num_values(params)

get_ctxt_mod_size_fhew_large_prec(params)

get_ctxt_mod_size_fhew_intermed_swch(params)

get_b_step_ltr_ckks_to_fhew(params)

get_b_step_ltr_fhew_to_ckks(params)

get_level_ltr_ckks_to_fhew(params)

get_level_ltr_fhew_to_ckks(params)

get_ring_dimension(params)

get_initial_ckks_modulus(params)

Arguments

ptr

External pointer (internal use). NULL (default) makes a new parameter object.

params

A SchSwchParams object.

value

The new value of the field: a logical for the five flags, an enum member for the two security levels, a string of decimal digits (or a whole number of at most 2^53) for initial_ckks_modulus, and a non-negative whole number otherwise.

Details

The three fields initial_ckks_modulus, ring_dimension, scaling_mod_size and batch_size describe the CKKS context. The setup functions fill them from the context, so they are not set by hand in ordinary use; set_params_from_ckks_cryptocontext() does the same on request.

The get_ functions return the fields. The library refuses to read a parameter object whose CKKS fields have not been filled, so they work after a setup function or set_params_from_ckks_cryptocontext() has been given the object; format() and print() show every field at any time.

Field Meaning Default
security_level_ckks Security level of the CKKS context, an element of SecurityLevel HEStd_128_classic
security_level_fhew Parameter set of the FHEW context, an element of BinFHEParamSet STD128
arbitrary_function_evaluation Whether the FHEW context is for arbitrary function evaluation FALSE
use_dynamic_mode_fhew Whether the FHEW context uses dynamic gadget bases FALSE
compute_argmin Whether the argmin is computed with the minimum (or argmax with the maximum) FALSE
one_hot_encoding Whether the argmin is returned one-hot encoded TRUE
use_alt_argmin Whether the alternative argmin method is used FALSE
num_slots_ckks Number of CKKS slots to switch 0
num_values Number of values to switch 0
ctxt_mod_size_fhew_large_prec Bits of the large-precision FHEW ciphertext modulus 25
ctxt_mod_size_fhew_intermed_swch Bits of the intermediate modulus of the switch 27
b_step_ltr_ckks_to_fhew Baby-step of the linear transform from CKKS to FHEW 0
b_step_ltr_fhew_to_ckks Baby-step of the linear transform from FHEW to CKKS 0
level_ltr_ckks_to_fhew Level of the linear transform from CKKS to FHEW 1
level_ltr_fhew_to_ckks Level of the linear transform from FHEW to CKKS 0

Value

SchSwchParams(): an S7 object of class SchSwchParams, inheriting from OpenFHEObject. The set_ functions: params, invisibly. The get_ functions: the value of the field, a string of decimal digits for initial_ckks_modulus.

Examples

params <- SchSwchParams()
set_security_level_ckks(params, SecurityLevel$HEStd_NotSet)
set_security_level_fhew(params, BinFHEParamSet$TOY)
set_num_slots_ckks(params, 16L)
params

The scheme object of a CryptoContext

Description

The object that implements the operations of a context's scheme, as returned by get_scheme() on a CryptoContext. It is an opaque handle, as in openfhe-python, with no methods of its own.

Usage

SchemeBase(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class SchemeBase, inheriting from OpenFHEObject.


Scheme Identifier

Description

Mirrors the C++ enum SCHEME in pke/scheme/scheme-id.h. The R-side name SchemeId matches the upstream header filename and avoids colliding with a potential future Scheme S7 class.

Usage

SchemeId

Value

A named list of 4 integer scalars, each the value of the OpenFHE C++ enumerator of the same name, identifying the encryption scheme a context implements: CKKSRNS_SCHEME, BFVRNS_SCHEME or BGVRNS_SCHEME, with INVALID_SCHEME for an unset value. This is the value reported by get_scheme() on any CCParams object.


Write and read the data of a scheme-switching computation

Description

A scheme-switching computation needs a CKKS context with its public key and evaluation keys, the FHEW context inside it with its bootstrapping keys, the switching key from FHEW to CKKS, and the ciphertext to work on. SchemeSwitchingDataSerializer writes all of it to a directory, and SchemeSwitchingDataDeserializer reads it back in another session, so that one party can set the computation up and another can run it.

Usage

SchemeSwitchingDataSerializer(
  crypto_context = NULL,
  public_key = NULL,
  raw_ciphertext = NULL,
  ptr = NULL
)

SchemeSwitchingDataDeserializer(ptr = NULL)

set_data_directory(x, dir)

serialize_scheme_switching_data(x)

deserialize_scheme_switching_data(x)

get_raw_ciphertext(x)

Arguments

crypto_context

A CKKS CryptoContext on which scheme switching has been set up and its keys generated (eval_scheme_switching_setup(), eval_scheme_switching_key_gen()).

public_key

The PublicKey of the context.

raw_ciphertext

The Ciphertext to write.

ptr

External pointer (internal use).

x

A SchemeSwitchingDataSerializer or SchemeSwitchingDataDeserializer.

dir

Character string; the directory.

Details

The writer is made from the context, the public key and the ciphertext. set_data_directory() names the directory, which must exist, and serialize_scheme_switching_data() writes the files (binary format, fixed file names). The multiplication and automorphism keys written are all those in the key registries.

The reader is made empty. After set_data_directory(), deserialize_scheme_switching_data() reads the files, registers the evaluation keys, and puts the FHEW context and the switching key into the CKKS context. get_crypto_context(), get_public_key() and get_raw_ciphertext() then return the three objects.

The C++ classes default the directory to demoData under the working directory. The R functions do not: reading or writing before set_data_directory() is an error.

Value

The constructors: an S7 object of the class, inheriting from OpenFHEObject. get_raw_ciphertext(): a Ciphertext, or NULL before the data has been read. The others: x, invisibly.


Secret Key Distribution

Description

Mirrors the C++ enum SecretKeyDist in core/lattice/constants-lattice.h.

Usage

SecretKeyDist

Value

A named list of 4 integer scalars, each the value of the OpenFHE C++ enumerator of the same name, naming the distribution the secret key polynomial is drawn from: GAUSSIAN, UNIFORM_TERNARY (the default, coefficients uniform on -1, 0, 1), SPARSE_TERNARY (ternary with a fixed small Hamming weight) and SPARSE_ENCAPSULATED. Pass an element as the secret_key_dist argument of CKKSParams(), BFVParams(), BGVParams() or fhe_context().


Map of secret-key shares for threshold-FHE abort recovery

Description

Opaque S7 wrapper around a ⁠shared_ptr<std::unordered_map<uint32_t, DCRTPoly>>⁠. Produced by share_keys() — each call returns one party's contribution to the distributed shares of their own secret key. Consumed by recover_shared_key(), which reconstructs the original secret from threshold or more shares when a party drops out.

Usage

SecretShareMap(ptr = NULL)

Arguments

ptr

External pointer (internal use).

Details

The map is keyed by party index (1-based uint32). Users do not index into it directly; it is a transport format for the secret-sharing protocol.

Value

An S7 object of class SecretShareMap, inheriting from OpenFHEObject, whose ptr property holds an external pointer to the C++ ⁠std::unordered_map<uint32_t, DCRTPoly>⁠. It carries one share per party index and acts as the transport format for the threshold-FHE abort-recovery protocol; it is produced by share_keys() rather than by calling this constructor directly.


Security Levels

Description

Mirrors the C++ enum SecurityLevel in core/lattice/stdlatticeparms.h.

Usage

SecurityLevel

Value

A named list of 7 integer scalars, each the value of the OpenFHE C++ enumerator of the same name. An element names the number of bits of security the ring dimension is chosen to provide against a classical (⁠HEStd_*_classic⁠) or quantum (⁠HEStd_*_quantum⁠) adversary, following the HomomorphicEncryption.org standard tables. HEStd_NotSet skips the table lookup, in which case the ring dimension must be set explicitly. Pass an element as the security_level argument of CKKSParams(), BFVParams(), BGVParams() or fhe_context().


Precomputed powers of a ciphertext

Description

The powers, or the Chebyshev polynomials, of one ciphertext, as eval_powers() and eval_cheby_polys() compute them. The class is an opaque handle, as in openfhe-python: it is passed to eval_poly_with_precomp() or eval_chebyshev_series_with_precomp(), which leave it unchanged.

Usage

SeriesPowers(ptr = NULL)

Arguments

ptr

External pointer (internal use)

Value

An S7 object of class SeriesPowers, inheriting from OpenFHEObject.


Bootstrap an LWE ciphertext

Description

Refreshes a ciphertext without applying a gate.

Usage

bin_bootstrap(ctx, ct, extended = FALSE)

Arguments

ctx

A BinFHEContext with bootstrapping keys.

ct

An LWECiphertext.

extended

Logical; if TRUE the result is returned before key switching (modulus Q, dimension N). Default FALSE.

Value

An LWECiphertext.

See Also

eval_bin_gate()


Generate BinFHE bootstrapping keys

Description

Generate BinFHE bootstrapping keys

Usage

bin_bt_key_gen(
  ctx,
  sk,
  keygen_mode = KeygenMode$SYM_ENCRYPT,
  internal32 = TRUE
)

Arguments

ctx

A BinFHE context

sk

An LWEPrivateKey

keygen_mode

Integer from KeygenMode; controls whether the bootstrapping keys are generated under symmetric-key encryption (KeygenMode$SYM_ENCRYPT, the default and the C++ default per binfhe-constants.h line 133) or public-key encryption (KeygenMode$PUB_ENCRYPT), matching the BTKeyGen(sk, keygenMode, internal32) method in binfhecontext.h.

internal32

Logical. If TRUE (the default, and the C++ default), keys whose moduli fit are generated directly in the library's 32-bit internal form; a key that does not qualify is generated in the 64-bit form. If FALSE, all keys are generated in the 64-bit form.

Value

Invisibly, the ctx BinFHE context that was passed in. Called for its side effect: the bootstrapping and key-switching keys are generated and stored inside the C++ context, after which eval_bin_gate() and the other gate evaluations can be used.

Memory

The bootstrapping keys can occupy several gigabytes (about 5.8 GB for STD128 with arb_func = TRUE and log_q = 12). R's garbage collector does not see this memory, so removing a context with rm() does not release it until a collection happens to run.


Decrypt a Binary FHE ciphertext

Description

Decrypt a Binary FHE ciphertext

Usage

bin_decrypt(ctx, sk, ct, p = 4L)

Arguments

ctx

A BinFHE context

sk

An LWEPrivateKey

ct

An LWECiphertext

p

Plaintext modulus (default: 4)

Value

Integer value


Encrypt a value for Binary FHE

Description

Encrypt a value for Binary FHE

Usage

bin_encrypt(
  ctx,
  sk,
  message,
  output = BinFHEOutput$BOOTSTRAPPED,
  p = 4L,
  mod = NULL
)

Arguments

ctx

A BinFHE context

sk

An LWEPrivateKey, or an LWEPublicKey to encrypt under the public key.

message

Integer (0 or 1 for Boolean; larger for integer FHE)

output

An element of BinFHEOutput (default: BinFHEOutput$BOOTSTRAPPED). Use BinFHEOutput$LARGE_DIM together with mod for the functional-bootstrapping path. With a public key the default is BinFHEOutput$SMALL_DIM, as in openfhe-python, which needs the switching key that bin_bt_key_gen() generates.

p

Plaintext modulus (default: 4)

mod

Optional large ciphertext modulus Q for the LARGE_DIM path. NULL (default) selects the standard small-modulus encrypt. A whole number of at most 2^53, or a string of decimal digits for a larger value.

Value

An LWECiphertext


Create a Binary FHE context

Description

Create a Binary FHE context

Usage

bin_fhe_context(
  paramset = BinFHEParamSet$STD128,
  method = BinFHEMethod$GINX,
  arb_func = FALSE,
  log_q = 11L,
  n = 0L,
  time_optimization = FALSE
)

Arguments

paramset

A BinFHEParamSet value (default: STD128)

method

A BinFHEMethod value (default: GINX)

arb_func

If TRUE, build a context that supports arbitrary-function bootstrapping (EvalSign, EvalFunc). Supplying any of arb_func, log_q, n, or time_optimization, even at its default value, selects the C++ overload that derives the parameters from them instead of reading the table for paramset; the two give different contexts for the same paramset.

log_q

log2 of the large ciphertext modulus Q used by functional bootstrapping (default 11; use 17 for the eval-sign example).

n

Ring dimension override (0 lets OpenFHE pick).

time_optimization

Enable the GINX time-optimization variant.

Value

A BinFHEContext object.

Memory

The bootstrapping keys that bin_bt_key_gen() stores in a context can occupy several gigabytes (about 5.8 GB for STD128 with arb_func = TRUE and log_q = 12). R's garbage collector does not see this memory, so removing a context with rm() does not release it until a collection happens to run.


Generate BinFHE secret key

Description

Generate BinFHE secret key

Usage

bin_key_gen(ctx)

Arguments

ctx

A BinFHE context

Value

An LWEPrivateKey


Keys of the LWE scheme of a BinFHE context

Description

bin_key_gen_pair() generates a public key and its secret key. bin_pub_key_gen() generates a public key for an existing secret key. bin_key_gen_n() generates a secret key of the large dimension N, and bin_key_switch_gen() the key that switches ciphertexts under it (modulus Q, dimension N) to ciphertexts under sk (modulus q, dimension n).

Usage

bin_key_gen_pair(ctx)

bin_pub_key_gen(ctx, sk)

bin_key_gen_n(ctx)

bin_key_switch_gen(ctx, sk, sk_n)

Arguments

ctx

A BinFHEContext.

sk

An LWEPrivateKey of dimension n, from bin_key_gen().

sk_n

An LWEPrivateKey of dimension N, from bin_key_gen_n().

Value

bin_key_gen_pair(): an LWEKeyPair. bin_pub_key_gen(): an LWEPublicKey. bin_key_gen_n(): an LWEPrivateKey. bin_key_switch_gen(): an LWESwitchingKey.

See Also

bin_key_gen(), bin_encrypt(), switch_ct_to_qn()

Examples

ctx <- bin_fhe_context(BinFHEParamSet$TOY)
kp <- bin_key_gen_pair(ctx)
## Under the public key of the pair, in dimension N; no bootstrapping
## keys are needed for this form.
ct <- bin_encrypt(ctx, kp@public, 1L, BinFHEOutput$LARGE_DIM)
bin_decrypt(ctx, kp@secret, ct)

CCParams getters (all schemes)

Description

Retrieve a parameter from a BFVParams, BGVParams, or CKKSParams object. Each getter wraps the corresponding upstream ⁠CCParams<T>::Get*⁠ method and returns its value unchanged.

Usage

get_ring_dim(params, ...)

get_plaintext_modulus(params, ...)

get_digit_size(params, ...)

get_composite_degree(params, ...)

get_scheme(params, ...)

get_standard_deviation(params, ...)

get_secret_key_dist(params, ...)

get_max_relin_sk_deg(params, ...)

get_pre_mode(params, ...)

get_multiparty_mode(params, ...)

get_execution_mode(params, ...)

get_decryption_noise_mode(params, ...)

get_noise_estimate(params, ...)

get_desired_precision(params, ...)

get_statistical_security(params, ...)

get_num_adversarial_queries(params, ...)

get_threshold_num_of_parties(params, ...)

get_key_switch_technique(params, ...)

get_scaling_technique(params, ...)

get_batch_size(params, ...)

get_first_mod_size(params, ...)

get_num_large_digits(params, ...)

get_multiplicative_depth(params, ...)

get_scaling_mod_size(params, ...)

get_security_level(params, ...)

get_eval_add_count(params, ...)

get_key_switch_count(params, ...)

get_encryption_technique(params, ...)

get_multiplication_technique(params, ...)

get_pre_num_hops(params, ...)

get_interactive_boot_compression_level(params, ...)

get_register_word_size(params, ...)

get_ckks_data_type(params, ...)

Arguments

params

A BFVParams, BGVParams, or CKKSParams.

...

Reserved for future method-specific arguments (currently unused — all getters take only params).

Details

Several parameters are "disabled" on specific schemes (their setters throw at runtime). For a disabled scheme/parameter combination the getter returns the default value of the underlying field (typically 0L for uint32_t, 0 for double, or the enum's zero sentinel) rather than throwing. This is benign — the field was never set so its default is all the information available — but it means e.g. calling get_plaintext_modulus(params) on a CKKSParams object returns 0 rather than a meaningful modulus.

Value

The underlying parameter value. Types vary per getter.

Functions

Return-type note

get_statistical_security and get_num_adversarial_queries return double rather than integer. This matches an inconsistency in the upstream Params base class: the corresponding setters take uint32_t but the getters return double. The underlying field is a double — R binds per the header, not per the setter signature.

get_plaintext_modulus returns a number for a modulus of at most 2^53 and a string of decimal digits for a larger one, which an R number cannot hold exactly.


Set a parameter on a parameter object

Description

Change one parameter of a BFVParams, BGVParams, or CKKSParams object after it has been constructed. Each function wraps the ⁠CCParams<T>::Set*⁠ method of the same name. The parameter constructors take the same parameters as arguments; these functions are for code that builds a parameter object step by step, as the OpenFHE examples do.

Usage

set_plaintext_modulus(params, ...)

set_digit_size(params, ...)

set_standard_deviation(params, ...)

set_secret_key_dist(params, ...)

set_max_relin_sk_deg(params, ...)

set_pre_mode(params, ...)

set_multiparty_mode(params, ...)

set_execution_mode(params, ...)

set_decryption_noise_mode(params, ...)

set_noise_estimate(params, ...)

set_desired_precision(params, ...)

set_statistical_security(params, ...)

set_num_adversarial_queries(params, ...)

set_threshold_num_of_parties(params, ...)

set_key_switch_technique(params, ...)

set_scaling_technique(params, ...)

set_batch_size(params, ...)

set_first_mod_size(params, ...)

set_num_large_digits(params, ...)

set_multiplicative_depth(params, ...)

set_scaling_mod_size(params, ...)

set_security_level(params, ...)

set_ring_dim(params, ...)

set_eval_add_count(params, ...)

set_key_switch_count(params, ...)

set_encryption_technique(params, ...)

set_multiplication_technique(params, ...)

set_pre_num_hops(params, ...)

set_interactive_boot_compression_level(params, ...)

set_composite_degree(params, ...)

set_register_word_size(params, ...)

Arguments

params

A BFVParams, BGVParams, or CKKSParams object.

...

Method-specific arguments: value, the new value of the parameter.

Details

Every setter is defined for all three parameter classes, as in the C++ library. A parameter that a scheme does not use is refused by OpenFHE, and its error is raised: for example set_plaintext_modulus() on a CKKSParams object.

Parameters whose values are members of an enumeration take the member, for example set_security_level(p, SecurityLevel$HEStd_128_classic).

Value

params, invisibly. The object is modified in place.

Functions

See Also

ccparams_getters for the matching ⁠get_*⁠ functions; BFVParams(), BGVParams(), CKKSParams().

Examples

p <- CKKSParams()
set_multiplicative_depth(p, 2L)
set_scaling_mod_size(p, 50L)
set_batch_size(p, 8L)
get_multiplicative_depth(p)

CKKS scaling-mod-size in bits

Description

Reads the real-valued scaling factor at level 0 from cc via get_scaling_factor_real() and returns its log2 rounded to the nearest integer. For a CKKS context constructed with set_scaling_mod_size(50L) this returns 50L.

Usage

ckks_scaling_factor_bits(cc)

Arguments

cc

A CryptoContext (should be CKKS — meaningful only for CKKS contexts).

Details

Used by the Stage 2 form of fhe_ckks_tolerance().

Value

Integer.


Release the precomputations a CKKS context has cached

Description

CKKS bootstrapping and scheme switching keep precomputed tables in the context. clear_bootstrap_precom() and clear_scheme_switch_precom() release one kind each, and raise an error on a context that is not CKKS. clear_all_ckks_caches() releases both and does nothing on a context of another scheme.

Usage

clear_all_ckks_caches(cc)

clear_bootstrap_precom(cc)

clear_scheme_switch_precom(cc)

Arguments

cc

A CryptoContext.

Value

cc, invisibly.


Clear the EvalAutomorphism key cache

Description

Companion to clear_eval_mult_keys() for the EvalAutomorphism key map (used by rotation and sum operations). key_tag = NULL clears everything (same as clear_fhe_state()'s "automorphism_keys" branch); a character scalar clears only that tag's entries.

Usage

clear_eval_automorphism_keys(key_tag = NULL)

Arguments

key_tag

NULL (default) to clear everything, or a character scalar to clear only one tag's entries.

Value

NULL, invisibly.

See Also

clear_fhe_state(), clear_eval_mult_keys()


Clear the EvalMult key cache

Description

Clears the CryptoContextImpl internal EvalMult key map. With key_tag = NULL (the default), clears the entire cache — equivalent to the no-arg ClearEvalMultKeys() form used by clear_fhe_state(). With a non-NULL key_tag, clears only the entries registered under that tag, preserving everything else. Useful in checkpoint workflows where a single party's keys need to be evicted without wiping the whole registry.

Usage

clear_eval_mult_keys(key_tag = NULL)

Arguments

key_tag

NULL (default) to clear everything, or a character scalar to clear only one tag's entries.

Value

NULL, invisibly.

See Also

clear_fhe_state(), clear_eval_automorphism_keys()


Remove summation keys from the registry

Description

Removes the keys that eval_sum_key_gen() registered: all of them, or those under one key tag.

Usage

clear_eval_sum_keys(key_tag = NULL)

Arguments

key_tag

Character string, or NULL (default) for all keys.

Value

NULL, invisibly.

See Also

clear_eval_mult_keys(), clear_eval_automorphism_keys()


Clear cached evaluation keys and contexts

Description

Clear cached evaluation keys and contexts

Usage

clear_fhe_state(what = c("mult_keys", "automorphism_keys", "contexts"))

Arguments

what

Character vector: subset of "mult_keys", "automorphism_keys", "contexts"

Value

No return value, called for side effects. Depending on what, it drops the process-wide caches of relinearization keys and of automorphism (rotation) keys, and releases the registry of crypto contexts, freeing the memory they hold.


Clear OpenFHE static maps and vectors

Description

Releases memory held in the upstream static eval-key maps and related global caches. Useful in long-running R sessions where repeated context construction accumulates static state. The call is idempotent; calling it when no static state is held is a no-op.

Usage

clear_static_maps_and_vectors()

Value

invisible(NULL).


Copy a ciphertext

Description

clone() returns a deep copy: a new ciphertext with its own elements, which later in-place operations on the original do not change. clone_empty() returns a ciphertext with the same context, key tag and encoding but no elements.

Usage

clone(x, ...)

clone_empty(x)

Arguments

x

A Ciphertext.

...

Reserved for future method-specific arguments.

Details

Assigning a ciphertext to another name in R does not copy it; both names refer to one C++ object.

Value

A Ciphertext.


Multiply two ciphertexts and reduce the modulus

Description

Multiplies, relinearizes, and then reduces the modulus of the product by one level, in one call. Needs the relinearization key.

Usage

composed_eval_mult(ct1, ct2)

Arguments

ct1, ct2

Ciphertext objects.

Value

A Ciphertext.


Compress a ciphertext to fewer towers

Description

Truncates the ciphertext's RNS modulus representation to towers_left towers and sets its noise-scale-degree to noise_scale_deg. Used by the interactive multi-party bootstrapping protocol to shrink a ciphertext before sending it across the network.

Usage

compress(x, ...)

Arguments

x

A Ciphertext.

...

Method-specific arguments: towers_left (integer, target tower count, default 1L), noise_scale_deg (integer, default 1L).

Value

A compressed Ciphertext.


Decrypt a ciphertext

Description

decrypt dispatches on both arguments and accepts them in either order, as the C++ header does: Decrypt(ciphertext, privateKey) is the primary form and Decrypt(privateKey, ciphertext) forwards to it (cryptocontext.h, both overloads). The key-first order lets code that is written around the holder of the key, such as a party object in a protocol, put that holder first, the same way encrypt() puts the key first.

Usage

decrypt(ct, key, ...)

Arguments

ct

A Ciphertext, or a PrivateKey when the key-first order is used.

key

A PrivateKey, or a Ciphertext when the key-first order is used.

...

Additional arguments (cc = CryptoContext)

Value

A Plaintext

Examples

cc <- fhe_context("CKKS", multiplicative_depth = 2L,
                  scaling_mod_size = 50L, batch_size = 8L)
kp <- key_gen(cc, eval_mult = TRUE)
pt <- make_ckks_packed_plaintext(cc, c(0.25, 0.5, 0.75, 1))
ct <- encrypt(kp@public, pt, cc = cc)

## Add the encrypted vector to itself, then decrypt. Decryption
## returns a Plaintext padded out to the full slot count, so trim it
## back to the length that was encoded.
out <- decrypt(eval_add(ct, ct), kp@secret, cc = cc)
out <- set_length(out, 4L)
get_real_packed_value(out)

## The same call with the key first:
out2 <- decrypt(kp@secret, eval_add(ct, ct), cc = cc)
get_real_packed_value(set_length(out2, 4L))

Deserialize evaluation keys from file

Description

Deserialize evaluation keys from file

Usage

deserialize_eval_keys(
  filename,
  type = c("mult", "automorphism", "sum"),
  format = "binary"
)

Arguments

filename

Path to serialized file

type

"mult", "automorphism", or "sum"

format

"binary" (default) or "json"

Value

TRUE on success (invisibly)


Deserialize evaluation keys held in memory

Description

Registers the keys in data, as serialize_eval_keys() with filename = NULL returns them.

Usage

deserialize_eval_keys_string(
  data,
  type = c("mult", "automorphism", "sum"),
  format = NULL
)

Arguments

data

A raw vector (binary format) or a character string (JSON).

type

"mult", "automorphism" or "sum".

format

NULL (default) to take the format from data, or "binary" or "json", which must then agree with data.

Value

TRUE, invisibly.


Enable a feature on a CryptoContext

Description

Accepts either a single PKESchemeFeature enum value or a uint32_t bitwise-OR mask of PKESchemeFeature values (for matching the C++ Enable(uint32_t) overload). The two paths dispatch on the value itself: a mask is detected by being strictly larger than the largest single-feature value (Feature$SCHEMESWITCH = 0x80 = 128) or by having more than one bit set.

Usage

enable_feature(cc, ...)

Arguments

cc

A CryptoContext.

...

feature: a Feature value (single) or an integer mask (e.g. Feature$PKE + Feature$KEYSWITCH + Feature$LEVELEDSHE, i.e. 11L).

Value

cc invisibly.


Precompute CRT tables when a context is deserialized

Description

By default OpenFHE precomputes its CRT tables when it deserializes a context. disable_precompute_crt_tables_after_deserializaton() turns that off, which makes deserialization faster for a context that will only be inspected, and enable_precompute_crt_tables_after_deserializaton() turns it back on. The setting is global.

Usage

enable_precompute_crt_tables_after_deserializaton()

disable_precompute_crt_tables_after_deserializaton()

Details

The function names keep the spelling of the C++ functions they call.

Value

NULL, invisibly.


Encode or decode a plaintext

Description

A plaintext holds a value and its encoding as a ring element. The functions that make plaintexts encode them, and decrypt() decodes its result, so these are for code that manipulates the element directly.

Usage

encode(pt)

decode(
  pt,
  depth = NULL,
  scaling_factor = NULL,
  scal_tech = NULL,
  execution_mode = NULL
)

Arguments

pt

A Plaintext.

depth

Integer; the noise scale degree of the ciphertext.

scaling_factor

Numeric; its scaling factor.

scal_tech

A member of ScalingTechnique.

execution_mode

A member of ExecutionMode.

Details

encode() computes the element from the value and decode() the value from the element. The CKKS form of decode() takes what the decoder needs to know about the ciphertext the plaintext came from; give all four arguments or none. The result of decrypt() is already decoded, and decoding it again does not reproduce its value.

Value

TRUE on success.


Encrypt a plaintext

Description

encrypt dispatches on both the key type and the plaintext. The ⁠(PublicKey, Plaintext)⁠ method performs public-key encryption and is the canonical path used by every vignette. The ⁠(PrivateKey, Plaintext)⁠ method performs symmetric / secret-key encryption using the private key directly; it is useful in protocols that want the secret key to serve as both encryption and decryption key (e.g. one-party tests, single-user benchmarks).

Usage

encrypt(key, pt, ...)

Arguments

key

A PublicKey or PrivateKey.

pt

A Plaintext.

...

Additional arguments (cc = CryptoContext is required).

Value

A Ciphertext.

Examples

cc <- fhe_context("CKKS", multiplicative_depth = 2L,
                  scaling_mod_size = 50L, batch_size = 8L)
kp <- key_gen(cc, eval_mult = TRUE)
pt <- make_ckks_packed_plaintext(cc, c(0.5, 1.5, 2.5, 3.5))

## Public-key encryption -- the usual path, and the one that lets a
## party encrypt without holding the secret key:
ct <- encrypt(kp@public, pt, cc = cc)
ct

## Symmetric encryption with the secret key, for protocols where the
## same party encrypts and decrypts:
ct2 <- encrypt(kp@secret, pt, cc = cc)
ct2

Homomorphic addition

Description

Homomorphic addition

Usage

eval_add(x, y, ...)

Arguments

x, y

Ciphertext, Plaintext, or numeric values

...

Method-specific arguments

Value

A Ciphertext


Homomorphic addition in place

Description

Stores the sum of the two operands in the ciphertext operand, without allocating a new Ciphertext. One operand is a Ciphertext; the other is a Ciphertext, a Plaintext, or a single real or complex number (CKKS). The operands may be given in either order, as in the C++ library. When both are ciphertexts the first one receives the result.

Usage

eval_add_in_place(x, ...)

Arguments

x

A Ciphertext, a Plaintext, or a single real or complex number.

...

Method-specific arguments: y, the other operand.

Value

The modified Ciphertext, invisibly.


Arithmetic without the library's operand checks

Description

These call the C++ functions of the same names, which skip the checks OpenFHE normally makes on its operands (same context, same key, compatible levels) and do not adjust levels or scales. They are for code that has already established those conditions; with operands that do not meet them the result is not meaningful. Use eval_add_in_place(), eval_mult() and eval_mult_no_relin() otherwise.

Usage

eval_add_in_place_no_check(ct1, ct2)

eval_mult_no_check(ct, scalar)

eval_mult_no_relin_no_check(ct1, ct2)

Arguments

ct1, ct

A Ciphertext.

ct2

A Ciphertext.

scalar

A whole number of at most 2^53, or a string of decimal digits for a larger value.

Details

eval_add_in_place_no_check() adds ct2 into ct1. eval_mult_no_check() multiplies every element of a ciphertext by an integer scalar. eval_mult_no_relin_no_check() returns the tensor product of the elements of two ciphertexts, without relinearizing. That is their product in CKKS for two ciphertexts at the same level and scale. It is not the BFV product, which includes a scaling step this function does not perform.

Value

eval_add_in_place_no_check() returns ct1, invisibly; the other two return a new Ciphertext.


Add or multiply a list of ciphertexts

Description

eval_add_many() returns the sum of a list of ciphertexts and eval_mult_many() their product, each computed as a binary tree, which keeps the multiplicative depth of the product at ceiling(log2(n)). eval_mult_many() relinearizes after every multiplication and needs the relinearization key.

Usage

eval_add_many(ciphertexts)

eval_add_many_in_place(ciphertexts)

eval_mult_many(ciphertexts)

Arguments

ciphertexts

A non-empty list of Ciphertext objects.

Details

eval_add_many_in_place() computes the same sum but uses the given ciphertexts for its intermediate results: after the call they hold partial sums, and the first one holds the total.

Value

A Ciphertext.

Examples

cc <- fhe_context("BFV", plaintext_modulus = 65537, multiplicative_depth = 2,
                  features = Feature$ADVANCEDSHE)
kp <- key_gen(cc, eval_mult = TRUE)
cts <- lapply(1:4, function(i)
  encrypt(kp@public, make_packed_plaintext(cc, c(i, 2L * i)), cc = cc))
total <- decrypt(eval_add_many(cts), kp@secret, cc = cc)
get_packed_value(set_length(total, 2L))

Homomorphic add, mutable variant

Description

The Mutable* family exists so that operations that can safely mutate their inputs during evaluation (e.g. a temporary intermediate in a longer circuit) can do so without forcing a defensive copy. Semantically equivalent to the non-Mutable counterpart from the user's perspective; the difference is performance under specific workloads.

Usage

eval_add_mutable(x, ...)

Arguments

x

A Ciphertext or a Plaintext (may be modified internally).

...

Method-specific arguments: y, a Ciphertext or a Plaintext (may be modified internally). At least one of x and y is a Ciphertext.

Value

A new Ciphertext holding x + y.


Mutable arithmetic on two ciphertexts, in place

Description

The result of ct1 + ct2, ct1 - ct2 or ct1 * ct2 replaces the contents of ct1. As in the other mutable forms (eval_add_mutable()), the library may also adjust ct2.

Usage

eval_add_mutable_in_place(ct1, ct2)

eval_sub_mutable_in_place(ct1, ct2)

eval_mult_mutable_in_place(ct1, ct2)

Arguments

ct1

A Ciphertext; receives the result.

ct2

A Ciphertext; may be modified.

Value

ct1, invisibly.


Rotate the slots of a ciphertext by an index

Description

eval_at_index(ct, i) moves slot i + k to slot k: a positive index rotates to the left, a negative one to the right. Needs the key for that index (eval_at_index_key_gen()). eval_rotate() calls the C++ function EvalRotate, which does the same thing.

Usage

eval_at_index(ct, index)

Arguments

ct

A Ciphertext.

index

Integer; the rotation index.

Value

A Ciphertext.


Generate at-index (rotation) keys for a secret key

Description

Standalone wrapper around the CryptoContext::EvalAtIndexKeyGen(privateKey, indexList) C++ method. Functionally identical to eval_rotate_key_gen() (the C++ EvalRotateKeyGen is a thin inline wrapper around EvalAtIndexKeyGen) and both names are provided to mirror the C++ API.

Usage

eval_at_index_key_gen(cc, sk, index_list)

Arguments

cc

A CryptoContext.

sk

A PrivateKey whose tag will be used to key the generated rotation keys in the cc's internal registry.

index_list

Integer vector of rotation indices.

Value

NULL, invisibly.


Apply an automorphism to a ciphertext

Description

Evaluates the automorphism at the given index on ct using the eval-key map returned by eval_automorphism_key_gen(). The result is a new ciphertext whose decrypted slot vector is a permutation of ct's slot vector (the permutation determined by the automorphism group element).

Usage

eval_automorphism(ct, index, eval_key_map)

Arguments

ct

A Ciphertext.

index

Integer; the automorphism index (must match one of the indices passed to eval_automorphism_key_gen()).

eval_key_map

An EvalKeyMap from eval_automorphism_key_gen().

Value

A transformed Ciphertext.

See Also

eval_automorphism_key_gen(), eval_rotate()


Generate automorphism evaluation keys for a set of indices

Description

Generates the eval-key map needed to apply eval_automorphism() at the given set of slot indices. The generated keys are both inserted into the CryptoContext's internal eval-automorphism-key registry (keyed by sk's tag) and returned as an EvalKeyMap handle that the caller can pass directly to eval_automorphism().

Usage

eval_automorphism_key_gen(cc, sk, indices)

Arguments

cc

A CryptoContext.

sk

A PrivateKey.

indices

Integer vector of automorphism indices (not slot indices — use find_automorphism_indices() to compute them from slot indices).

Details

On the C++ side this is equivalent to calling EvalAutomorphismKeyGen(sk, indices) which internally calls CryptoContextImpl::InsertEvalAutomorphismKey with the generated map (cryptocontext.h line 2237). The dual return / registry-insert pattern mirrors the equivalent C++ entry point.

Companion to eval_rotate_key_gen() (reached via key_gen()'s rotations argument): both populate the same cc-internal storage. The automorphism form gives raw access to the automorphism group element (bypassing the rotate-to-automorphism slot mapping that eval_rotate_key_gen performs internally).

Value

An EvalKeyMap with one entry per input index.

See Also

eval_automorphism(), find_automorphism_indices()


Evaluate a binary gate on encrypted values

Description

Evaluate a binary gate on encrypted values

Usage

eval_bin_gate(ctx, gate, ct1, ct2 = NULL, extended = FALSE)

Arguments

ctx

A BinFHE context

gate

A BinGate value. Two-input gates: OR, AND, NOR, NAND, XOR, XNOR, XOR_FAST, XNOR_FAST. Three or more input gates (vector form): MAJORITY, AND3, OR3, AND4, OR4, CMUX.

ct1

An LWECiphertext, OR a list of LWECiphertext objects for the 3+-input vector form. When a list is supplied, ct2 must be left at its default (NULL).

ct2

An LWECiphertext for the 2-input form, or NULL (the default) when ct1 is a list. The vector dispatch follows binfhecontext.h line 322.

extended

Logical; if TRUE the result is left in the extended ring dimension N rather than switched back to n. Default FALSE, the C++ header default.

Value

An LWECiphertext


Perform CKKS bootstrapping

Description

Refreshes the ciphertext to allow further computation.

Usage

eval_bootstrap(ct, num_iterations = 1L, precision = 0L)

Arguments

ct

A Ciphertext

num_iterations

Number of bootstrap iterations (default: 1)

precision

Target precision (default: 0 = automatic)

Value

A refreshed Ciphertext


Generate bootstrapping keys

Description

Generate bootstrapping keys

Usage

eval_bootstrap_key_gen(cc, sk, slots)

Arguments

cc

A CryptoContext

sk

A PrivateKey

slots

Number of slots

Value

Invisibly, the cc crypto context that was passed in. Called for its side effect: the rotation and evaluation keys bootstrapping needs are generated from sk and stored inside the C++ context, after which eval_bootstrap() can be called.


Precompute the plaintexts of CKKS bootstrapping

Description

Computes and stores the encoding and decoding plaintexts that bootstrapping uses. eval_bootstrap_setup() does this itself unless it is called with precompute = FALSE; this function does it afterwards.

Usage

eval_bootstrap_precompute(cc, slots = 0L)

Arguments

cc

A CryptoContext.

slots

Integer; the number of slots to be bootstrapped. Default 0L.

Details

After a setup with precompute = FALSE, call this function before eval_bootstrap(). At OpenFHE 1.6.1 the library does not check that the plaintexts exist, and bootstrapping without them ends the R session.

Value

cc, invisibly.

See Also

eval_bootstrap_setup(), clear_bootstrap_precom()


Set up CKKS bootstrapping

Description

The multiplicative depth of cc must be at least get_bootstrap_depth() for level_budget. At OpenFHE 1.6.1 the library does not check this, and a setup with precompute = TRUE on a shallower context ends the R session.

Usage

eval_bootstrap_setup(
  cc,
  level_budget = c(5L, 4L),
  dim1 = c(0L, 0L),
  slots = 0L,
  correction_factor = 0L,
  precompute = TRUE,
  bt_slots_encoding = FALSE
)

Arguments

cc

A CryptoContext

level_budget

Integer vector of length 2 (default: c(5, 4))

dim1

Integer vector of length 2 (default: c(0, 0))

slots

Number of slots (default: 0 = automatic)

correction_factor

Correction factor (default: 0)

precompute

Logical; compute the encoding and decoding plaintexts of bootstrapping now (default: TRUE). With FALSE, call eval_bootstrap_precompute() before eval_bootstrap().

bt_slots_encoding

Logical; controls whether the bootstrap precomputes with slot-count encoding (the BTSlotsEncoding tail argument on cryptocontext.h line 3513). Default FALSE matching the C++ default.

Value

Invisibly, the cc crypto context that was passed in. Called for its side effect: the linear transforms bootstrapping needs are precomputed and cached inside the C++ context. Call it before eval_bootstrap_key_gen().


CKKS bootstrapping with slots-to-coefficients first

Description

The slots-encoding variant of CKKS bootstrapping: the slots-to-coefficients transform comes first, then the modulus raise, the coefficients-to-slots transform and the approximate modular reduction. It needs eval_bootstrap_setup() to have been called with bt_slots_encoding = TRUE; after such a setup eval_bootstrap() calls this variant itself.

Usage

eval_bootstrap_stc_first(ct, num_iterations = 1L, precision = 0L)

Arguments

ct

A Ciphertext.

num_iterations

Integer; number of iterations. Default 1L.

precision

Integer; precision of the initial bootstrapping, 0L (default) for the library's choice.

Details

Do not call it on a context with a regular setup. At OpenFHE 1.6.1 the library does not check the kind of setup, and the error it then raises ends the R session.

Value

A refreshed Ciphertext.

See Also

eval_bootstrap()


Evaluate a Chebyshev series on a ciphertext

Description

Uses OpenFHE's default algorithm selector, which routes to eval_chebyshev_linear() for degree < 5 and eval_chebyshev_ps() (Paterson-Stockmeyer) for higher degrees. Call the variants directly to force one algorithm or the other.

Usage

eval_chebyshev(ct, coefficients, a, b)

Arguments

ct

A Ciphertext

coefficients

Integer, double or complex vector of Chebyshev coefficients. Each type is evaluated with its own arithmetic, as for eval_poly(). Pass whole-number coefficients as doubles (c(1, 2, 3), not c(1L, 2L, 3L)): at OpenFHE 1.6.1 the Paterson-Stockmeyer evaluator, which this function uses from degree 5, returns wrong values for integer coefficients.

a

Lower bound of the approximation interval

b

Upper bound of the approximation interval

Value

A Ciphertext

See Also

eval_chebyshev_coefficients() and eval_chebyshev_function() for constructing the coefficient vector from a user-supplied function; eval_chebyshev_linear() / eval_chebyshev_ps() for forcing the algorithm.


Chebyshev coefficients for a real-valued function

Description

Computes the Chebyshev (first-kind) coefficients that approximate a univariate function func on the interval [a, b] using the discrete orthogonality formula at degree + 1 Chebyshev nodes. This is a direct port of the upstream routine EvalChebyshevCoefficients() in core/lib/math/chebyshev.cpp of openfhe-development, and the returned vector is in exactly the form that eval_chebyshev() (and the upstream EvalChebyshevSeries) expect — the zeroth coefficient is not halved.

Usage

eval_chebyshev_coefficients(func, a, b, degree)

Arguments

func

An R function taking a single numeric argument and returning a numeric scalar.

a

Lower bound of the approximation interval.

b

Upper bound of the approximation interval.

degree

Chebyshev polynomial degree (must be >= 1).

Value

Numeric vector of length degree + 1.

See Also

eval_chebyshev(), eval_chebyshev_function().


Evaluate a user-supplied function on a CKKS ciphertext via Chebyshev approximation

Description

Computes the Chebyshev coefficients for func on ⁠[a, b]⁠ via eval_chebyshev_coefficients() and applies the resulting series to ct via eval_chebyshev(). This mirrors the upstream CryptoContext::EvalChebyshevFunction helper, which is a thin wrapper around EvalChebyshevCoefficients followed by EvalChebyshevSeries on the C++ side.

Usage

eval_chebyshev_function(ct, func, a, b, degree)

Arguments

ct

A Ciphertext holding CKKS-encoded real values in ⁠[a, b]⁠.

func

An R function taking a single numeric argument and returning a numeric scalar. It is evaluated on cleartext Chebyshev nodes inside ⁠[a, b]⁠ to produce the approximating coefficients.

a

Lower bound of the approximation interval.

b

Upper bound of the approximation interval.

degree

Chebyshev polynomial degree (must be >= 1).

Value

A Ciphertext holding the elementwise approximation of func applied to the plaintext slots of ct.

See Also

eval_chebyshev(), eval_chebyshev_coefficients(), eval_logistic(), eval_sin(), eval_cos(), eval_divide().


Chebyshev approximation of a function, in the clear

Description

The cleartext counterpart of eval_chebyshev_function(): it evaluates the degree-degree Chebyshev approximation of func on ⁠[a, b]⁠ at the points ptxt, with the arithmetic OpenFHE uses on ciphertexts. Comparing its result with func(ptxt) gives the approximation error of a degree before any encrypted computation is run.

Usage

eval_chebyshev_function_ptxt(func, ptxt, a, b, degree)

Arguments

func

A function of one number returning one number.

ptxt

Numeric vector of points in ⁠[a, b]⁠.

a, b

Numeric; the interval.

degree

Integer; the degree of the approximation, at least 1.

Value

A numeric vector the length of ptxt.

Examples

x <- seq(-1, 1, by = 0.5)
eval_chebyshev_function_ptxt(exp, x, -1, 1, 8L) - exp(x)

Evaluate a Chebyshev series via the linear evaluator

Description

Forces the "linear" Chebyshev evaluator regardless of degree. Shallower circuit depth than Paterson-Stockmeyer but uses more multiplications at high degree.

Usage

eval_chebyshev_linear(ct, coefficients, a, b)

Arguments

ct

A Ciphertext

coefficients

Integer, double or complex vector of Chebyshev coefficients, as for eval_chebyshev()

a

Lower bound of the approximation interval

b

Upper bound of the approximation interval

Value

A Ciphertext

See Also

eval_chebyshev(), eval_chebyshev_ps()


Evaluate a Chebyshev series via the Paterson-Stockmeyer method

Description

Forces the Paterson-Stockmeyer Chebyshev evaluator regardless of degree. Efficient for high-degree polynomials.

Usage

eval_chebyshev_ps(ct, coefficients, a, b)

Arguments

ct

A Ciphertext

coefficients

Integer, double or complex vector of Chebyshev coefficients, as for eval_chebyshev(). Pass whole-number coefficients as doubles: at OpenFHE 1.6.1 this evaluator returns wrong values for integer coefficients.

a

Lower bound of the approximation interval

b

Upper bound of the approximation interval

Value

A Ciphertext

See Also

eval_chebyshev(), eval_chebyshev_linear()


Switch a CKKS ciphertext to FHEW ciphertexts

Description

Scheme switching takes the values in the slots of a CKKS ciphertext to one FHEW (LWE) ciphertext each, on which Boolean gates, the sign and look-up tables can be evaluated (CKKS with real data and Feature$SCHEMESWITCH).

Usage

eval_ckks_to_fhew_setup(cc, schswchparams)

eval_ckks_to_fhew_key_gen(cc, key_pair, lwesk)

eval_ckks_to_fhew_precompute(cc, scale = 1)

eval_ckks_to_fhew(ct, num_ctxts = 0L)

Arguments

cc

A CKKS CryptoContext.

schswchparams

A SchSwchParams object. The setup fills its CKKS fields from cc.

key_pair

The KeyPair of the CKKS context.

lwesk

The LWEPrivateKey of the FHEW context.

scale

Numeric; the scale. Default 1.

ct

A Ciphertext.

num_ctxts

Integer; the number of slots to switch, 0L (default) for all.

Details

eval_ckks_to_fhew_setup() creates the FHEW context inside cc (read it with get_bin_cc_for_scheme_switch()) and returns its secret key. eval_ckks_to_fhew_key_gen() generates the keys of the switch. eval_ckks_to_fhew_precompute() fixes the scale the values are multiplied by before the switch, normally one over the FHEW plaintext modulus. eval_ckks_to_fhew() does the switch.

Value

eval_ckks_to_fhew_setup(): an LWEPrivateKey. eval_ckks_to_fhew(): a list of LWECiphertext objects. The others: cc, invisibly.

See Also

eval_fhew_to_ckks() for the other direction; eval_scheme_switching_setup() for both at once.


A constant as an LWE ciphertext

Description

Returns a ciphertext of the Boolean value that needs no key: a trivial encryption, for use as a constant input of a gate.

Usage

eval_constant(ctx, value)

Arguments

ctx

A BinFHEContext.

value

Logical.

Value

An LWECiphertext.


Evaluate cosine on a ciphertext

Description

Evaluate cosine on a ciphertext

Usage

eval_cos(ct, a, b, degree)

Arguments

ct

A Ciphertext

a

Lower bound of the approximation interval

b

Upper bound of the approximation interval

degree

Chebyshev polynomial degree

Value

A Ciphertext holding the encrypted, slot-wise cosine of ct, approximated by a Chebyshev polynomial of the given degree on the interval ⁠[a, b]⁠. Accuracy degrades outside that interval, and the result sits ceiling(log2(degree)) + 1 levels below ct.


Decompose a large-precision ciphertext into digits

Description

Splits a ciphertext of large modulus into ciphertexts of its digits, each of the small modulus of the context (a context built with arb_func = TRUE).

Usage

eval_decomp(ctx, ct)

Arguments

ctx

A BinFHEContext.

ct

An LWECiphertext.

Value

A list of LWECiphertext objects, least significant digit first.

See Also

eval_sign(), eval_floor()


Evaluate division approximation on a ciphertext

Description

Evaluate division approximation on a ciphertext

Usage

eval_divide(ct, a, b, degree)

Arguments

ct

A Ciphertext

a

Lower bound of the approximation interval

b

Upper bound of the approximation interval

degree

Chebyshev polynomial degree

Value

A Ciphertext holding the encrypted, slot-wise reciprocal of ct, approximated by a Chebyshev polynomial of the given degree on the interval ⁠[a, b]⁠. The interval must exclude zero, accuracy degrades outside it, and the result sits ceiling(log2(degree)) + 1 levels below ct.


Hoisted slot rotation using precomputed digits

Description

Hoisted slot rotation using precomputed digits

Usage

eval_fast_rotation(ct, ...)

Arguments

ct

A Ciphertext

...

Method-specific arguments: index (rotation amount, positive = left, negative = right), m (cyclotomic order, typically 2 * ring_dimension(ctx)), precomp (a FastRotationPrecomputation from eval_fast_rotation_precompute())

Value

A Ciphertext


Extended hoisted slot rotation

Description

Applies a rotation using precomputed digit decomposition like eval_fast_rotation(), but with the extension that the first digit of the decomposition can be folded into the output before the rotation is applied (controlled by add_first). Used inside the CKKS bootstrap fast-rotation inner loop per openfhe-development's scheme/base-scheme.cpp. The eval-key map is pulled from the CryptoContext internal registry via the ciphertext's key tag, so there is no EvalKeyMap argument at the R boundary — the automorphism keys must already be resident on the cc (call key_gen(cc, rotations = ...) to populate them, then reuse the ct here).

Usage

eval_fast_rotation_ext(ct, ...)

Arguments

ct

A Ciphertext.

...

Method-specific arguments: index (rotation amount, positive = left, negative = right), precomp (a FastRotationPrecomputation from eval_fast_rotation_precompute()), add_first (logical, default FALSE).

Value

A Ciphertext.

See Also

eval_fast_rotation()


Precompute digit decomposition for hoisted fast rotations

Description

Computes the digit decomposition of a ciphertext once so that multiple eval_fast_rotation() calls against the same ciphertext avoid redoing it. The cyclotomic order m (typically 2 * N, where N is the ring dimension) is required by eval_fast_rotation().

Usage

eval_fast_rotation_precompute(ct, ...)

Arguments

ct

A Ciphertext

...

Reserved for future method-specific arguments

Value

A FastRotationPrecomputation


CKKS functional bootstrapping of a look-up table

Description

Functional bootstrapping refreshes a ciphertext and applies a look-up table to the encrypted integers in the same step. The input is an RLWE ciphertext converted to CKKS with schemelet_convert_rlwe_to_ckks(), and the output goes back with schemelet_convert_ckks_to_rlwe().

Usage

eval_fbt_setup(
  cc,
  coeffs,
  num_slots,
  p_in,
  p_out,
  big_q,
  pub_key,
  dim1,
  level_budget,
  lvls_after_boot = 0L,
  depth_leveled_computation = 0L,
  order = 1L
)

eval_fbt(
  ct,
  coeffs,
  digit_bit_size,
  initial_scaling,
  post_scaling,
  level_to_reduce = 0L,
  order = 1L
)

eval_fbt_no_decoding(ct, coeffs, digit_bit_size, initial_scaling, order = 1L)

eval_hom_decoding(ct, post_scaling, level_to_reduce = 0L)

Arguments

cc

A CKKS CryptoContext with Feature$FHE enabled.

coeffs

The coefficients of the look-up table; see Details.

num_slots

Integer; number of CKKS slots.

p_in, p_out

Input and output plaintext moduli.

big_q

The modulus of the RLWE ciphertext converted to CKKS.

pub_key

The PublicKey.

dim1

Integer vector of length 2; baby-step dimensions of the two linear transforms (0 for the library's choice).

level_budget

Integer vector of length 2; level budgets of the two linear transforms.

lvls_after_boot

Integer; levels available after bootstrapping. Default 0L.

depth_leveled_computation

Integer; levels of the computation done between eval_fbt_no_decoding() (or eval_mvb_no_decoding()) and eval_hom_decoding(). Default 0L.

order

Integer; order of the Hermite interpolation. Default 1L.

ct

A Ciphertext.

digit_bit_size

Integer; number of bits of the input modulus.

initial_scaling

The modulus the input is scaled by, usually get_modulus() of the element parameters from schemelet_get_element_params().

post_scaling

The scale applied to the coefficients (the scale of get_hermite_trig_coefficients()), undone here.

level_to_reduce

Integer; levels to drop before decoding. Default 0L.

Details

eval_fbt_setup() prepares the context; call eval_bootstrap_key_gen() and eval_mult_key_gen() after it. eval_fbt() applies the table. eval_fbt_no_decoding() stops before the return to coefficient encoding, leaving a slot-packed CKKS ciphertext on which leveled operations can be done; eval_hom_decoding() then finishes.

The R type of coeffs selects the form of the table, as the Python type does in openfhe-python. An integer vector is the optimized Boolean case (input modulus 2, order 1), with the two coefficients c(f(1), f(0) - f(1)); build it with as.integer(). A double or complex vector is the general case, with the coefficients from get_hermite_trig_coefficients().

p_in, p_out, big_q, initial_scaling and post_scaling are strings of decimal digits, or whole numbers of at most 2^53.

Value

eval_fbt_setup(): cc, invisibly. The others: a Ciphertext.

See Also

eval_mvb_precompute() to apply several tables to one input; get_fbt_depth().


CKKS functional bootstrapping of a Fourier series

Description

Refreshes a ciphertext and evaluates on its values the function whose Fourier coefficients are coefficients, in the same step (CKKS with CKKSDataType$COMPLEX).

Usage

eval_fe_func_bootstrap_setup(
  cc,
  level_budget = c(5L, 4L),
  dim1 = c(0L, 0L),
  slots = 0L
)

eval_fe_func_bootstrap(ct, coefficients)

eval_fe_func_bootstrap_precompute(ct, coefficients)

eval_fe_func_bootstrap_with_precomp(powers, coefficients)

Arguments

cc

A CKKS CryptoContext with Feature$FHE enabled.

level_budget

Integer vector of length 2. Default c(5L, 4L).

dim1

Integer vector of length 2. Default c(0L, 0L).

slots

Integer; number of slots, 0L (default) for full packing.

ct

A Ciphertext.

coefficients

Numeric or complex vector of Fourier coefficients.

powers

A SeriesPowers object from eval_fe_func_bootstrap_precompute().

Details

eval_fe_func_bootstrap_setup() prepares the context; call eval_bootstrap_key_gen() after it. eval_fe_func_bootstrap() does the whole evaluation. eval_fe_func_bootstrap_precompute() and eval_fe_func_bootstrap_with_precomp() split it, so that several series of the same length can be evaluated on one input.

The setup shares the bootstrapping precomputation of the context for slots with eval_bootstrap_setup() and eval_fbt_setup(): a context holds one of the three per slot count.

Value

eval_fe_func_bootstrap_setup(): cc, invisibly. eval_fe_func_bootstrap_precompute(): a SeriesPowers object. The others: a Ciphertext.

See Also

get_fefbt_depth()


Switch FHEW ciphertexts to a CKKS ciphertext

Description

Packs the messages of a list of FHEW (LWE) ciphertexts into the slots of one CKKS ciphertext (CKKS with real data and Feature$SCHEMESWITCH).

Usage

eval_fhew_to_ckks_setup(cc, cc_lwe, num_slots_ckks = 0L, log_q = 25L)

eval_fhew_to_ckks_key_gen(
  cc,
  key_pair,
  lwesk,
  num_slots = 0L,
  num_ctxts = 0L,
  dim1 = 0L,
  l = 0L
)

eval_fhew_to_ckks(
  cc,
  lwe_ciphertexts,
  num_ctxts = 0L,
  num_slots = 0L,
  p = 4L,
  pmin = 0,
  pmax = 2,
  dim1 = 0L
)

Arguments

cc

A CKKS CryptoContext.

cc_lwe

The BinFHEContext the ciphertexts come from.

num_slots_ckks, num_slots

Integer; number of CKKS slots, 0L (default) for the library's choice.

log_q

Integer; bits of the FHEW ciphertext modulus. Default 25L.

key_pair

The KeyPair of the CKKS context.

lwesk

The LWEPrivateKey of the FHEW context.

num_ctxts

Integer; number of ciphertexts to switch, 0L (default) for all.

dim1

Integer; baby-step dimension of the linear transform, 0L (default) for the library's choice.

l

Integer; level of the linear transform (the C++ argument L). Default 0L.

lwe_ciphertexts

A list of LWECiphertext objects.

p

Integer; plaintext modulus of the FHEW ciphertexts. Default 4L.

pmin, pmax

Numeric; the range of the messages. Defaults 0 and 2.

Details

eval_fhew_to_ckks_setup() records the FHEW context cc_lwe in the CKKS context, and eval_fhew_to_ckks_key_gen() generates the keys of the switch.

The messages are taken modulo p; pmin and pmax give the range they lie in, which sets the interval of the Chebyshev approximation the switch evaluates. The defaults are for bits.

Value

eval_fhew_to_ckks(): a Ciphertext. The others: cc, invisibly.

See Also

eval_ckks_to_fhew()


Evaluate a floor (rounding) function on an LWE ciphertext

Description

Performs the LWE equivalent of floor(ct / 2^roundbits) via functional bootstrapping. Used as a primitive in arbitrary- function evaluation pipelines where the bit-level rounding operation is needed separately from eval_func()'s LUT path.

Usage

eval_floor(ctx, ct, roundbits = 0L)

Arguments

ctx

A BinFHEContext

ct

An LWECiphertext

roundbits

Integer; the number of low-order bits to round off. Default 0L, the C++ header default.

Details

Binding-level note: the underlying BinFHEContext__EvalFloor cpp11 binding has been present since the earliest BinFHE work; the R wrapper was added later to close the latent gap (cpp11-only entry with no R path).

Value

A new LWECiphertext holding the rounded value.

See Also

eval_func(), eval_sign()


Evaluate an arbitrary function on an encrypted value

Description

Functional bootstrapping with a precomputed lookup table. The context must have been created with arb_func = TRUE.

Usage

eval_func(ctx, ct, lut)

Arguments

ctx

A BinFHE context built with arb_func = TRUE

ct

An LWECiphertext encrypted with output = BinFHEOutput$LARGE_DIM

lut

A numeric vector of length p (the plaintext modulus) typically produced by generate_lut_via_function()

Value

An LWECiphertext encrypting lut[plaintext(ct) + 1]


Evaluate a trigonometric Hermite series on a ciphertext

Description

The series evaluation inside functional bootstrapping. It approximates exp(i * pi / 2 * x) by the Chebyshev series coefficients_cheb on ⁠[a, b]⁠, squares it twice to get exp(2 * pi * i * x), evaluates the polynomial with coefficients coefficients_herm in that exponential, and returns twice the real part: ⁠2 * Re(sum_j h_j exp(2 * pi * i * j * x))⁠ (CKKS only).

Usage

eval_hermite_trig_series(
  ct,
  coefficients_cheb,
  a,
  b,
  coefficients_herm,
  precomp = 0L
)

Arguments

ct

A Ciphertext.

coefficients_cheb

Numeric or complex vector; Chebyshev coefficients of exp(i * pi / 2 * x) on ⁠[a, b]⁠.

a, b

Numeric; the interval of the Chebyshev approximation.

coefficients_herm

The coefficients of the Hermite series in powers of the exponential, divided by 2: an integer vector, or a double or complex vector.

precomp

Integer. 0L (default) or 1L: compute the exponential and keep it in the first or the second place. 2L: reuse the first one kept. Any other value: reuse the second.

Details

The exponential is kept in the bootstrapping precomputation of the context for the slot count of ct, in one of two places, so the context must have been set up for bootstrapping (eval_fbt_setup(), eval_bootstrap_setup() or eval_fe_func_bootstrap_setup()) and must hold the conjugation key (eval_bootstrap_key_gen()).

Value

A Ciphertext.


Inner product of two encrypted vectors

Description

Multiplies the two operands slot by slot and sums the first batch_size slots; the result is in the first slot. Needs the relinearization key and the summation keys (eval_sum_key_gen()).

Usage

eval_inner_product(ct1, ct2, batch_size)

Arguments

ct1

A Ciphertext.

ct2

A Ciphertext or a Plaintext.

batch_size

Integer; the number of slots to sum.

Value

A Ciphertext.


Weighted sum of ciphertexts (CKKS)

Description

Computes constants[1] * ciphertexts[[1]] + ... + constants[n] * ciphertexts[[n]].

Usage

eval_linear_wsum(ciphertexts, constants)

eval_linear_wsum_mutable(constants, ciphertexts)

Arguments

ciphertexts

A non-empty list of Ciphertext objects.

constants

One constant per ciphertext: an integer, double or complex vector. Each type is evaluated with its own arithmetic.

Details

eval_linear_wsum_mutable() may adjust the given ciphertexts (their level and scale) while it works, which saves copies. It takes the constants first, as the C++ function of that name does.

Value

A Ciphertext.


Evaluate logistic function on a ciphertext

Description

Evaluate logistic function on a ciphertext

Usage

eval_logistic(ct, a, b, degree)

Arguments

ct

A Ciphertext

a

Lower bound of the approximation interval

b

Upper bound of the approximation interval

degree

Chebyshev polynomial degree

Value

A Ciphertext holding the encrypted, slot-wise logistic function 1 / (1 + exp(-x)) of ct, approximated by a Chebyshev polynomial of the given degree on the interval ⁠[a, b]⁠. Accuracy degrades outside that interval, and the result sits ceiling(log2(degree)) + 1 levels below ct.


Merge the first slots of several ciphertexts into one

Description

Returns a ciphertext whose slot i holds the first slot of the i-th input. The other slots of each input must be zero. Needs the rotation keys for indices ⁠-1, ..., -(n - 1)⁠, where n is the number of ciphertexts (see eval_at_index_key_gen()).

Usage

eval_merge(ciphertexts)

Arguments

ciphertexts

A non-empty list of Ciphertext objects.

Value

A Ciphertext.


Homomorphic multiplication

Description

Homomorphic multiplication

Usage

eval_mult(x, y, ...)

Arguments

x, y

Ciphertext, Plaintext, or numeric values

...

Method-specific arguments

Value

A Ciphertext


Fused multiply-and-relinearize

Description

Equivalent to relinearize(eval_mult_no_relin(x, y)) but slightly more efficient in OpenFHE's implementation. Use this at the end of a multiplication chain.

Usage

eval_mult_and_relinearize(x, ...)

Arguments

x

A Ciphertext.

...

Method-specific arguments: y — a Ciphertext to multiply x by in a fused multiply-and-relinearize step.

Value

A relinearized Ciphertext.


Homomorphic multiplication by a number, in place

Description

Multiplies a ciphertext by a single real or complex number (CKKS) and stores the result in the ciphertext. The operands may be given in either order. OpenFHE declares no in-place product of two ciphertexts or of a ciphertext and a plaintext on the CryptoContext; use eval_mult() for those.

Usage

eval_mult_in_place(x, ...)

Arguments

x

A Ciphertext, or a single real or complex number.

...

Method-specific arguments: y, the other operand.

Value

The modified Ciphertext, invisibly.


Generate relinearization (eval-mult) keys for a secret key

Description

Standalone wrapper around the CryptoContext::EvalMultKeyGen(privateKey) C++ method. Populates the CryptoContext's internal eval-mult registry (keyed by the secret key's tag) so that ciphertext × ciphertext multiplication can be relinearized.

Usage

eval_mult_key_gen(cc, sk)

Arguments

cc

A CryptoContext.

sk

A PrivateKey whose tag will be used to key the generated eval-mult key in the cc's internal registry.

Details

key_gen() folds this into its eval_mult = TRUE branch as a convenience for fresh keypairs. The standalone wrapper is the right entry point when the secret key already exists — for example in any threshold or multi-party flow that holds a secret-key share but did not generate it through key_gen().

Value

NULL, invisibly.


Generate relinearization keys for higher powers of the secret key

Description

Generates the keys that relinearize a ciphertext of more than three elements, as eval_mult_no_relin() produces when it is applied repeatedly: one key for each power of the secret key up to the max_relin_sk_deg of the context. eval_mult_key_gen() generates the key for the second power only.

Usage

eval_mult_keys_gen(cc, sk)

Arguments

cc

A CryptoContext.

sk

A PrivateKey.

Value

NULL, invisibly.


Homomorphic multiply, mutable variant

Description

Homomorphic multiply, mutable variant

Usage

eval_mult_mutable(x, ...)

Arguments

x

A Ciphertext or a Plaintext (may be modified internally).

...

Method-specific arguments: y, a Ciphertext or a Plaintext (may be modified internally). At least one of x and y is a Ciphertext.

Value

A new Ciphertext holding x * y.


Homomorphic multiplication without relinearization

Description

Returns the raw product of two ciphertexts as a higher-degree ciphertext (the result has n1 + n2 - 1 polynomial components where the inputs had n1 and n2). The standard eval_mult() automatically relinearizes the result back to 2 components; this variant skips the relinearization step so that multiple multiplications can be chained at higher polynomial degree before a single relinearize() call at the end. Used by the EvalMultAndRelinearize fused variant and by EvalPolyWithPrecomp for noise-optimal polynomial evaluation.

Usage

eval_mult_no_relin(x, ...)

Arguments

x

A Ciphertext.

...

Method-specific arguments: y — a Ciphertext to multiply x by without relinearization.

Value

A Ciphertext at higher polynomial degree.


Several look-up tables on one input (multi-value bootstrapping)

Description

eval_mvb_precompute() does the part of functional bootstrapping that does not depend on the table: it computes the complex exponential of the input and its powers. eval_mvb() and eval_mvb_no_decoding() then apply a table to that precomputation, as eval_fbt() and eval_fbt_no_decoding() do to a ciphertext. Every table applied to one precomputation must have the input modulus and order of the coefficients the precomputation was made with.

Usage

eval_mvb_precompute(ct, coeffs, digit_bit_size, initial_scaling, order = 1L)

eval_mvb(
  ciphertexts,
  coeffs,
  digit_bit_size,
  post_scaling,
  level_to_reduce = 0L,
  order = 1L
)

eval_mvb_no_decoding(ciphertexts, coeffs, digit_bit_size, order = 1L)

Arguments

ct

A Ciphertext.

coeffs

The coefficients of the look-up table; see Details.

digit_bit_size

Integer; number of bits of the input modulus.

initial_scaling

The modulus the input is scaled by, usually get_modulus() of the element parameters from schemelet_get_element_params().

order

Integer; order of the Hermite interpolation. Default 1L.

ciphertexts

A SeriesPowers object from eval_mvb_precompute().

post_scaling

The scale applied to the coefficients (the scale of get_hermite_trig_coefficients()), undone here.

level_to_reduce

Integer; levels to drop before decoding. Default 0L.

Value

eval_mvb_precompute(): a SeriesPowers object. The others: a Ciphertext.

See Also

eval_fbt_setup(), eval_hom_decoding()


Homomorphic negation

Description

Homomorphic negation

Usage

eval_negate(x, ...)

Arguments

x

A Ciphertext

...

Method-specific arguments

Value

A Ciphertext


Homomorphic negation in place

Description

Homomorphic negation in place

Usage

eval_negate_in_place(x, ...)

Arguments

x

A Ciphertext (modified in place).

...

Reserved for future method-specific arguments.

Value

x invisibly.


Evaluate NOT on an encrypted value

Description

Evaluate NOT on an encrypted value

Usage

eval_not(ctx, ct)

Arguments

ctx

A BinFHE context

ct

An LWECiphertext

Value

An LWECiphertext


Evaluate a polynomial on a ciphertext

Description

Evaluates p(x) = c0 + c1x + c2x^2 + ... on encrypted x. Uses OpenFHE's default algorithm selector, which routes to eval_poly_linear() for degree < 5 and eval_poly_ps() (Paterson-Stockmeyer) for higher degrees. Call the variants directly to force one algorithm or the other — Linear is shallower for low-degree polynomials; PS has fewer multiplications for high-degree polynomials.

Usage

eval_poly(ct, coefficients)

Arguments

ct

A Ciphertext

coefficients

Vector of polynomial coefficients, constant term first. An integer, double or complex vector; OpenFHE evaluates each type with its own arithmetic (integer coefficients as exact 64-bit integers, complex coefficients for a context with CKKSDataType$COMPLEX).

Value

A Ciphertext

See Also

eval_poly_linear(), eval_poly_ps()


Evaluate a polynomial via the linear evaluator

Description

Forces the "linear" Horner-style polynomial evaluator regardless of degree. Shallower circuit depth than the Paterson-Stockmeyer variant but uses more multiplications at high degree. Cheaper for degree < 5; fall over to eval_poly_ps() above that.

Usage

eval_poly_linear(ct, coefficients)

Arguments

ct

A Ciphertext

coefficients

Integer, double or complex vector of polynomial coefficients, as for eval_poly()

Value

A Ciphertext

See Also

eval_poly(), eval_poly_ps()


Evaluate a polynomial via the Paterson-Stockmeyer method

Description

Forces the Paterson-Stockmeyer polynomial evaluator regardless of degree. Efficient for high-degree polynomials (fewer multiplications at the cost of more additions and a deeper circuit); for degree < 5 prefer eval_poly_linear().

Usage

eval_poly_ps(ct, coefficients)

Arguments

ct

A Ciphertext

coefficients

Integer, double or complex vector of polynomial coefficients, as for eval_poly()

Value

A Ciphertext

See Also

eval_poly(), eval_poly_linear()


Evaluate several series on one ciphertext

Description

Evaluating a polynomial or a Chebyshev series on a ciphertext spends most of its time computing the powers (or the Chebyshev polynomials) of the ciphertext. These functions separate the two steps, so that several series can be evaluated on the same ciphertext for the cost of one set of powers (CKKS only).

Usage

eval_powers(ct, coefficients)

eval_poly_with_precomp(powers, coefficients)

eval_cheby_polys(ct, coefficients, a, b)

eval_chebyshev_series_with_precomp(polys, coefficients)

Arguments

ct

A Ciphertext.

coefficients

Integer, double or complex vector of coefficients, constant term first, as for eval_poly() and eval_chebyshev(). Pass whole-number Chebyshev coefficients as doubles; see eval_chebyshev().

powers

A SeriesPowers object from eval_powers().

a, b

Numeric; the interval of the Chebyshev approximation.

polys

A SeriesPowers object from eval_cheby_polys().

Details

eval_powers() computes the powers that eval_poly() would compute for coefficients, and eval_poly_with_precomp() evaluates a polynomial from them. eval_cheby_polys() and eval_chebyshev_series_with_precomp() are the same pair for eval_chebyshev().

The precomputation depends on coefficients only through the degree (the length of the vector), so it can be reused for any series of that degree. Below degree 5 only the powers with a nonzero coefficient are computed, so there the nonzero terms must match as well.

Value

eval_powers() and eval_cheby_polys(): a SeriesPowers object. The other two: a Ciphertext.

Examples

cc <- fhe_context("CKKS", multiplicative_depth = 4L, scaling_mod_size = 50L,
                  batch_size = 8L, features = Feature$ADVANCEDSHE)
keys <- key_gen(cc, eval_mult = TRUE)
ct <- encrypt(keys@public, make_ckks_packed_plaintext(cc, c(0.5, 1, 2)), cc = cc)
p <- c(1, 0, 2, 0, 0, 1)
q <- c(0, 1, 0, 3, 0, -1)
powers <- eval_powers(ct, p)
ct_p <- eval_poly_with_precomp(powers, p)
ct_q <- eval_poly_with_precomp(powers, q)

Rotate ciphertext slots

Description

Rotate ciphertext slots

Usage

eval_rotate(ct, ...)

Arguments

ct

A Ciphertext

...

Method-specific arguments (index)

Value

A Ciphertext


Generate rotation keys for a secret key

Description

Standalone wrapper around the CryptoContext::EvalRotateKeyGen(privateKey, indexList) C++ method. Populates the CryptoContext's internal automorphism key registry for the supplied rotation indices so that eval_rotate() can consume them.

Usage

eval_rotate_key_gen(cc, sk, index_list)

Arguments

cc

A CryptoContext.

sk

A PrivateKey whose tag will be used to key the generated rotation keys in the cc's internal registry.

index_list

Integer vector of rotation indices.

Details

key_gen() folds this into its rotations = ... argument as a convenience for fresh keypairs. The standalone wrapper is the right entry point when the secret key already exists — for example as the lead-party rotation-key generation step in a multi-party rotation protocol, where subsequent parties contribute via multi_eval_at_index_key_gen().

Value

NULL, invisibly.


Comparison, minimum and maximum through scheme switching

Description

With switching set up in both directions, a comparison is done by switching CKKS values to FHEW, evaluating the sign there, and switching the result back (CKKS with real data and Feature$SCHEMESWITCH).

Usage

eval_scheme_switching_setup(cc, schswchparams)

eval_scheme_switching_key_gen(cc, key_pair, lwesk)

eval_compare_switch_precompute(cc, p_lwe = 0L, scale_sign = 1, unit = FALSE)

eval_compare_scheme_switching(
  ct1,
  ct2,
  num_ctxts = 0L,
  num_slots = 0L,
  p_lwe = 0L,
  scale_sign = 1,
  unit = FALSE
)

eval_min_scheme_switching(
  ct,
  public_key,
  num_values = 0L,
  num_slots = 0L,
  p_lwe = 0L,
  scale_sign = 1
)

eval_min_scheme_switching_alt(
  ct,
  public_key,
  num_values = 0L,
  num_slots = 0L,
  p_lwe = 0L,
  scale_sign = 1
)

eval_max_scheme_switching(
  ct,
  public_key,
  num_values = 0L,
  num_slots = 0L,
  p_lwe = 0L,
  scale_sign = 1
)

eval_max_scheme_switching_alt(
  ct,
  public_key,
  num_values = 0L,
  num_slots = 0L,
  p_lwe = 0L,
  scale_sign = 1
)

Arguments

cc

A CKKS CryptoContext.

schswchparams

A SchSwchParams object. The setup fills its CKKS fields from cc.

key_pair

The KeyPair of the CKKS context.

lwesk

The LWEPrivateKey of the FHEW context.

p_lwe

Integer; the FHEW plaintext modulus, 0L (default) for the library's choice.

scale_sign

Numeric; the scale applied before the sign is taken. Default 1.

unit

Logical; whether the input messages are normalized to the unit circle. Default FALSE.

ct1, ct2, ct

Ciphertext objects.

num_ctxts

Integer; number of values to compare, 0L (default) for all.

num_slots

Integer; number of CKKS slots, 0L (default) for the library's choice.

public_key

The PublicKey of the CKKS context.

num_values

Integer; number of values to take the minimum or maximum of, 0L (default) for all.

Details

eval_scheme_switching_setup() creates the FHEW context inside cc and returns its secret key; eval_scheme_switching_key_gen() generates the keys for both directions. eval_compare_switch_precompute() fixes the FHEW plaintext modulus and the scale of the comparison.

eval_compare_scheme_switching() returns a ciphertext whose slots hold 1 where ct1 < ct2 and 0 elsewhere. eval_min_scheme_switching() and eval_max_scheme_switching() return the minimum or maximum of the first num_values slots (a power of two) and its index; set up the context with set_compute_argmin(params, TRUE) for them. The index is one-hot encoded over num_values slots unless the parameters say otherwise (set_one_hot_encoding()). The slots after the first of the value, and after the index, hold no meaningful data. The ⁠_alt⁠ forms use more FHEW operations, for higher precision at a higher cost (set_use_alt_argmin(params, TRUE)).

Value

eval_scheme_switching_setup(): an LWEPrivateKey. eval_compare_scheme_switching(): a Ciphertext. The minimum and maximum functions: a list of two Ciphertext objects, the value and its index. The others: cc, invisibly.

See Also

eval_ckks_to_fhew(), eval_fhew_to_ckks()


Evaluate sign on an encrypted value (functional bootstrapping)

Description

Extracts the most-significant bit of an LWE ciphertext encrypted under the large modulus Q. The context must have been created with arb_func = TRUE.

Usage

eval_sign(ctx, ct, scheme_switch = FALSE)

Arguments

ctx

A BinFHE context built with arb_func = TRUE

ct

An LWECiphertext encrypted via bin_encrypt(..., mod = Q)

scheme_switch

Logical; when TRUE, the output ciphertext is encoded compatibly with the CKKS<->FHEW scheme-switching pipeline (the schemeSwitch flag at binfhecontext.h line 367). Default FALSE for the standalone FHEW path. Per the upstream header description, this is the "flag that indicates if it should be compatible to scheme switching".

Value

An LWECiphertext encrypting 0 if the input was negative (i.e. lay in the upper half of [0, Q)), 1 otherwise


Evaluate sine on a ciphertext (Chebyshev approximation)

Description

Evaluate sine on a ciphertext (Chebyshev approximation)

Usage

eval_sin(ct, a, b, degree)

Arguments

ct

A Ciphertext

a

Lower bound of the approximation interval

b

Upper bound of the approximation interval

degree

Chebyshev polynomial degree

Value

A Ciphertext


Homomorphic squaring

Description

Homomorphic squaring

Usage

eval_square(x, ...)

Arguments

x

A Ciphertext

...

Method-specific arguments

Value

A Ciphertext


Square, rescale or relinearize a ciphertext in place

Description

The in-place forms of eval_square(), rescale() and relinearize(): the result replaces the contents of the ciphertext.

Usage

eval_square_in_place(ct)

rescale_in_place(ct)

relinearize_in_place(ct)

Arguments

ct

A Ciphertext (modified in place).

Value

ct, invisibly.


Homomorphic square, mutable variant

Description

Homomorphic square, mutable variant

Usage

eval_square_mutable(x, ...)

Arguments

x

A Ciphertext (may be modified internally).

...

Reserved for future method-specific arguments.

Value

A new Ciphertext holding x * x.


Homomorphic subtraction

Description

Homomorphic subtraction

Usage

eval_sub(x, y, ...)

Arguments

x, y

Ciphertext, Plaintext, or numeric values

...

Method-specific arguments

Value

A Ciphertext


Homomorphic subtraction in place

Description

Stores x - y in the ciphertext operand. One operand is a Ciphertext; the other is a Ciphertext, a Plaintext, or a single real or complex number (CKKS). The operands may be given in either order, and the result is always x - y: with eval_sub_in_place(2, ct) the ciphertext becomes 2 - ct.

Usage

eval_sub_in_place(x, ...)

Arguments

x

A Ciphertext, a Plaintext, or a single real or complex number.

...

Method-specific arguments: y, the other operand.

Value

The modified Ciphertext, invisibly.


Homomorphic subtract, mutable variant

Description

Homomorphic subtract, mutable variant

Usage

eval_sub_mutable(x, ...)

Arguments

x

A Ciphertext or a Plaintext (may be modified internally).

...

Method-specific arguments: y, a Ciphertext or a Plaintext (may be modified internally). At least one of x and y is a Ciphertext.

Value

A new Ciphertext holding x - y.


Sum all slots in a ciphertext

Description

Sum all slots in a ciphertext

Usage

eval_sum(ct, ...)

Arguments

ct

A Ciphertext

...

Method-specific arguments (batch_size)

Value

A Ciphertext


Generate sum keys for a secret key

Description

Populates the CryptoContext's internal sum-key registry (keyed by the secret key's tag) so that eval_sum() and the multi-party sum-key protocol can consume the generated entries. Closes a long-standing gap: the underlying CryptoContext__EvalSumKeyGen cpp11 binding has been present since the early phases but had no standalone R wrapper — users had to go through key_gen()'s side-effects only. The wrapper lands so that the multi-party sum-key flow (which needs to call this on each party's secret share) has a direct R-level entry point.

Usage

eval_sum_key_gen(cc, sk)

Arguments

cc

A CryptoContext.

sk

A PrivateKey whose tag will be used to key the generated sum-key map in the cc's internal registry.

Value

NULL, invisibly.


Sum the rows or the columns of an encrypted matrix

Description

A matrix is packed into the slots row by row. eval_sum_rows() adds its rows together and eval_sum_cols() its columns. Each takes the keys made by the matching key generator, which returns them as an EvalKeyMap.

Usage

eval_sum_rows(ct, num_rows, eval_sum_key_map, subring_dim = 0L)

eval_sum_cols(ct, num_cols, eval_sum_key_map)

eval_sum_rows_key_gen(
  cc,
  sk,
  public_key = NULL,
  row_size = 0L,
  subring_dim = 0L
)

eval_sum_cols_key_gen(cc, sk)

Arguments

ct

A Ciphertext holding the matrix.

num_rows, num_cols

Integer; the number of rows, or columns, of the matrix.

eval_sum_key_map

An EvalKeyMap from eval_sum_rows_key_gen() or eval_sum_cols_key_gen().

subring_dim

Integer; the subring dimension, 0L (default) for the full ring.

cc

A CryptoContext.

sk

A PrivateKey.

public_key

A PublicKey, or NULL (default) for the form that takes no public key.

row_size

Integer; the length of a row, 0L (default) for the value the library derives.

Value

eval_sum_rows() and eval_sum_cols() return a Ciphertext; the key generators return an EvalKeyMap.


Per-test CKKS precision tolerance

Description

Computes a tolerance value suitable for comparing the cleartext result of a CKKS circuit against a decrypted ciphertext. The value is a function of the scheme's scaling factor, the circuit's multiplicative depth at the point of decryption, and the ScalingTechnique-specific precision loss per level.

Usage

fhe_ckks_tolerance(x, ...)

Arguments

x

For the numeric method: integer multiplicative depth at the point of decryption. For the Ciphertext method: a Ciphertext object whose associated context supplies all parameters.

...

Method-specific arguments. The numeric method accepts scaling_factor_bits (integer bit size of the scaling modulus, typical values 50/59/78), scaling_technique (a character string like "FLEXIBLEAUTO" or an integer from the ScalingTechnique enum), and k (conservative multiplicative factor, default 8). The Ciphertext method accepts only k.

Details

Two dispatch forms:

Value

Numeric scalar — the tolerance value to use as tolerance in tinytest::expect_equal() or as atol in a manual diff.

Examples

## Stage 1 -- pass the parameters directly:
fhe_ckks_tolerance(4L, 50L, "FLEXIBLEAUTO")

## Stage 2 -- pass a ciphertext and let it read the parameters
## off the associated context:
cc <- fhe_context("CKKS", multiplicative_depth = 4L,
                  scaling_mod_size = 50L, batch_size = 8L)
kp <- key_gen(cc, eval_mult = TRUE)
pt <- make_ckks_packed_plaintext(cc, c(0.1, 0.2, 0.3, 0.4))
ct <- encrypt(kp@public, pt, cc = cc)
fhe_ckks_tolerance(ct)

Create a fully homomorphic encryption context

Description

High-level constructor that creates a CryptoContext with sensible defaults. PKE, KEYSWITCH, and LEVELEDSHE features are enabled automatically.

Usage

fhe_context(scheme = c("BFV", "BGV", "CKKS"), ..., features = NULL)

Arguments

scheme

Character: "BFV", "BGV", or "CKKS".

...

Scheme-specific CCParams setter arguments. Forwarded to BFVParams(), BGVParams(), or CKKSParams(). Example: fhe_context("BFV", plaintext_modulus = 65537, multiplicative_depth = 2) or fhe_context("CKKS", multiplicative_depth = 4, scaling_mod_size = 50, scaling_technique = ScalingTechnique$FLEXIBLEAUTO).

features

Additional Feature values to enable on the context beyond the default PKE|KEYSWITCH|LEVELEDSHE triple.

Details

All scheme-specific CCParams setter arguments are accepted via ... and forwarded to the appropriate per-scheme constructor (BFVParams(), BGVParams(), or CKKSParams()). See those functions' argument lists for the valid per-scheme setter surface — each scheme accepts only the setters that are not disabled in its upstream ⁠CCParams<T>⁠ specialization. Passing an invalid scheme-specific argument produces an R-level "unused argument" error at the underlying ⁠*Params()⁠ call site.

Value

A CryptoContext object.

See Also

BFVParams(), BGVParams(), CKKSParams()

Examples

## An exact context over the integers modulo 65537 (BFV). The ring
## dimension is chosen for you from the security level.
bfv <- fhe_context("BFV", plaintext_modulus = 65537L,
                   multiplicative_depth = 2L)
ring_dimension(bfv)

## An approximate context over the reals (CKKS), which is what the
## statistical applications use.
ckks <- fhe_context("CKKS", multiplicative_depth = 2L,
                    scaling_mod_size = 50L, batch_size = 8L)
ring_dimension(ckks)

Deserialize an OpenFHE object from file

Description

Deserialize an OpenFHE object from file

Usage

fhe_deserialize(
  filename,
  type = c("CryptoContext", "PublicKey", "PrivateKey", "Ciphertext", "EvalKey",
    "EvalKeyMap", "BinFHEContext", "LWECiphertext", "LWEPrivateKey", "LWEPublicKey",
    "RingGSWBTKey"),
  format = "binary"
)

Arguments

filename

Path to serialized file

type

One of "CryptoContext", "PublicKey", "PrivateKey", "Ciphertext", "EvalKey", "EvalKeyMap", or, for Binary FHE, "BinFHEContext", "LWECiphertext", "LWEPrivateKey", "LWEPublicKey", "RingGSWBTKey".

format

"binary" (default) or "json"

Value

The deserialized object

See Also

fhe_deserialize_string() for data held in memory.


Deserialize an OpenFHE object held in memory

Description

The inverse of fhe_serialize() with filename = NULL.

Usage

fhe_deserialize_string(
  data,
  type = c("CryptoContext", "PublicKey", "PrivateKey", "Ciphertext", "EvalKey",
    "EvalKeyMap", "EvalKeyVector"),
  format = NULL
)

Arguments

data

A raw vector (binary format) or a character string (JSON), as fhe_serialize() returns.

type

One of "CryptoContext", "PublicKey", "PrivateKey", "Ciphertext", "EvalKey", "EvalKeyMap", or "EvalKeyVector" for a serialized list of EvalKey objects.

format

NULL (default) to take the format from data, or "binary" or "json", which must then agree with data.

Value

The deserialized object; for "EvalKeyVector" a list of EvalKey objects.


Serialize an OpenFHE object

Description

Writes an object to a file, or, with filename = NULL, returns its serialized form: a raw vector for the binary format and a character string for JSON.

Usage

fhe_serialize(x, ...)

Arguments

x

A CryptoContext, PublicKey, PrivateKey, Ciphertext, EvalKey or EvalKeyMap, or a list of EvalKey objects (in memory only). For Binary FHE, a BinFHEContext, LWECiphertext, LWEPrivateKey, LWEPublicKey or RingGSWBTKey (to a file only).

...

Method arguments: filename, a path, or NULL (default) to serialize in memory; format, "binary" (default) or "json".

Value

With a file name, TRUE invisibly. Otherwise a raw vector (format = "binary") or a character string (format = "json").

See Also

fhe_deserialize(), fhe_deserialize_string()

Examples

cc <- fhe_context("BFV", plaintext_modulus = 65537, multiplicative_depth = 1)
keys <- key_gen(cc)
bytes <- fhe_serialize(keys@public)
pk <- fhe_deserialize_string(bytes, "PublicKey")

Compute the automorphism index for a single slot index

Description

Maps a CKKS slot index to the corresponding automorphism index in the cyclotomic ring Z[X]/(X^N + 1). The automorphism group of the ring is isomorphic to the multiplicative group ⁠(Z/2N)*⁠; this function returns the representative of that group that corresponds to rotating the plaintext slots by the given amount.

Usage

find_automorphism_index(cc, index)

Arguments

cc

A CryptoContext.

index

Integer; the slot index (positive = left rotation, negative = right rotation).

Details

Used as a primitive by find_automorphism_indices() and by code that needs to address automorphism keys directly (for example, selectively generating eval keys for a sparse set of rotation amounts).

Value

Integer; the automorphism group element corresponding to that rotation.

See Also

find_automorphism_indices() for the vector form.


Compute the automorphism indices for a list of slot indices

Description

Vector form of find_automorphism_index(). Takes a vector of slot indices and returns the corresponding automorphism indices in the same order.

Usage

find_automorphism_indices(cc, indices)

Arguments

cc

A CryptoContext.

indices

Integer vector of slot indices.

Value

Integer vector of automorphism indices.

See Also

find_automorphism_index()


Generate a CryptoContext from a parameter object

Description

The counterpart of OpenFHE's GenCryptoContext(parameters). It returns the context with no feature enabled; call enable_feature() for each feature the computation needs, as the OpenFHE examples do. fhe_context() does both steps in one call and enables the three features most computations use.

Usage

gen_crypto_context(params)

Arguments

params

A BFVParams, BGVParams, or CKKSParams object.

Value

A CryptoContext with no feature enabled.

See Also

fhe_context(), enable_feature(), ccparams_setters

Examples

p <- BFVParams()
set_plaintext_modulus(p, 65537)
set_multiplicative_depth(p, 2L)
cc <- gen_crypto_context(p)
enable_feature(cc, Feature$PKE)
enable_feature(cc, Feature$KEYSWITCH)
enable_feature(cc, Feature$LEVELEDSHE)
ring_dimension(cc)

Generate a lookup table for an arbitrary plaintext function

Description

Computes f(0:(p-1), p) and returns it as a numeric vector suitable for eval_func(). This is the R-side analogue of OpenFHE's GenerateLUTviaFunction — we don't bind the C++ helper because its signature takes a raw function pointer that can't capture an R closure, and R is natively vectorised so a pure-R helper is both simpler and faster than wiring an R callback through cpp11.

Usage

generate_lut_via_function(f, p)

Arguments

f

A function ⁠function(m, p)⁠ that returns the table entry for input m under plaintext modulus p. Vectorised functions are supported.

p

The plaintext modulus (typically get_max_plaintext_space(ctx))

Value

A length-p numeric vector of LUT entries


All contexts the library currently holds

Description

OpenFHE keeps every context it has generated in a registry, and returns the registered one when asked for parameters it has seen. This function lists the registry.

Usage

get_all_contexts()

Value

A list of CryptoContext objects.

See Also

clear_fhe_state(), which can empty the registry.


Retrieve all registered EvalAutomorphism key maps

Description

Reads the entire CryptoContextImpl internal EvalAutomorphism key map — a named R list keyed by secret-key tag, where each element is an EvalKeyMap (the rotation/automorphism key map for that party). Used for rotation and EvalAtIndex under the EvalKeyMap wire format.

Usage

get_all_eval_automorphism_keys()

Value

A named list keyed by key-tag string. Each element is an EvalKeyMap (opaque wrapper around ⁠shared_ptr<map<uint32_t, EvalKey<DCRTPoly>>>⁠).

See Also

get_eval_automorphism_key_map() for per-tag lookup, insert_eval_automorphism_key() for the write path.


Retrieve all registered EvalMult key vectors

Description

Reads the entire CryptoContextImpl internal EvalMult key map — a named R list keyed by secret-key tag, where each element is itself a list of EvalKey objects (the vector of multiplication-eval keys registered under that tag).

Usage

get_all_eval_mult_keys()

Details

The returned list is a snapshot: each EvalKey wraps a fresh shared_ptr copy, so retained references survive subsequent clear_eval_mult_keys() calls. The underlying keys are still shared with the cc registry — modifications through other paths remain visible.

Primary consumer: checkpoint/resume workflows that need to audit which parties have keys registered before serializing the cc.

Value

A named list keyed by key-tag string. Each element is a list of EvalKey objects.

See Also

get_eval_mult_key_vector() for per-tag lookup, insert_eval_mult_key() for the write path.


Retrieve all registered EvalSum key maps

Description

Reads the entire CryptoContextImpl internal EvalSum key map. Structurally identical to get_all_eval_automorphism_keys(): both share backing storage on the C++ side, but the two accessors are exposed separately so callers can match whichever OpenFHE doc they are reading.

Usage

get_all_eval_sum_keys()

Value

A named list keyed by key-tag string. Each element is an EvalKeyMap.

See Also

get_eval_sum_key_map(), insert_eval_sum_key()


The FHEW side of a scheme-switching context

Description

get_bin_cc_for_scheme_switch() returns the FHEW context that a scheme-switching setup created inside the CKKS context cc, and set_bin_cc_for_scheme_switch() puts one there. get_swk_fc() and set_swk_fc() read and write the switching key from FHEW to CKKS, which is a CKKS ciphertext. The setters are for restoring a context in another session.

Usage

get_bin_cc_for_scheme_switch(cc)

set_bin_cc_for_scheme_switch(cc, bin_fhe_context)

get_swk_fc(cc)

set_swk_fc(cc, switching_key)

Arguments

cc

A CKKS CryptoContext.

bin_fhe_context

A BinFHEContext.

switching_key

A Ciphertext.

Value

get_bin_cc_for_scheme_switch(): a BinFHEContext, or NULL if cc holds none. get_swk_fc(): a Ciphertext, or NULL if cc holds none. The setters: cc, invisibly.


Get the required multiplicative depth for CKKS bootstrapping

Description

Get the required multiplicative depth for CKKS bootstrapping

Usage

get_bootstrap_depth(
  level_budget,
  secret_key_dist = SecretKeyDist$UNIFORM_TERNARY,
  approx_mod_depth = NULL
)

Arguments

level_budget

Integer vector of length 2

secret_key_dist

Secret key distribution, an element of SecretKeyDist (default: SecretKeyDist$UNIFORM_TERNARY)

approx_mod_depth

Optional integer: the depth of the Chebyshev interpolation of the approximate modular reduction. When given, the three-argument C++ form is called, which OpenFHE keeps for backward compatibility. NULL (default) calls the two-argument form, which derives that depth from secret_key_dist.

Value

Integer: required depth


The bootstrapping keys of a BinFHE context

Description

get_bt_key() returns the keys bin_bt_key_gen() generated, as one RingGSWBTKey; bin_bt_key_load() puts such an object into a context, and bin_clear_bt_keys() removes the keys of a context. Together with fhe_serialize() and fhe_deserialize() they move bootstrapping keys between sessions.

Usage

get_bt_key(ctx)

get_bt_key_map(ctx)

bin_bt_key_load(ctx, key, internal32 = TRUE)

bin_bt_key_map_load_single_element(ctx, base_g, key)

bin_clear_bt_keys(ctx)

get_switch_key(ctx)

has_internal32_refresh_key(ctx)

has_internal32_switch_key(ctx)

Arguments

ctx

A BinFHEContext.

key

A RingGSWBTKey.

internal32

Logical; if TRUE (default) keys whose moduli fit are converted to the 32-bit internal form on loading.

base_g

Integer; the gadget base the key is for.

Details

A context for large-precision evaluation keeps one key per gadget base. get_bt_key_map() returns them, and bin_bt_key_map_load_single_element() loads one.

get_switch_key() returns the switching key among the bootstrapping keys, and get_public_key() the public key.

has_internal32_refresh_key() and has_internal32_switch_key() say whether the refreshing and the switching key are held in the library's 32-bit internal form.

Value

get_bt_key(): a RingGSWBTKey. get_bt_key_map(): a list of them, named by gadget base. get_switch_key(): an LWESwitchingKey, or NULL if the context holds none in the 64-bit form. The has_ functions: a logical. The others: ctx, invisibly.

Memory

The bootstrapping keys of a context can occupy several gigabytes (about 5.8 GB for STD128 with arb_func = TRUE and log_q = 12). R's garbage collector does not see this memory, so removing a context with rm() does not release it until a collection happens to run.


Get the CKKS bootstrap correction factor

Description

Reads the current correction factor the scheme uses during the bootstrap EvalModReduceInternal step. Companion of set_ckks_boot_correction_factor(). Changes here affect all subsequent bootstrap operations on this CryptoContext until another call to set_ckks_boot_correction_factor().

Usage

get_ckks_boot_correction_factor(cc)

Arguments

cc

A CryptoContext.

Value

Integer; the current correction factor.

See Also

set_ckks_boot_correction_factor(), eval_bootstrap_setup()


Get complex values from a CKKS plaintext

Description

Reads the CKKS plaintext's internal slot vector as complex numbers. Every CKKS plaintext slot carries a ⁠std::complex<double>⁠ internally; when a plaintext was constructed from a real-valued vector via make_ckks_packed_plaintext(), the imaginary parts are all zero (up to CKKS encoding noise). When a plaintext was constructed from a complex vector (the is-complex dispatch path), both real and imaginary parts carry information.

Usage

get_complex_packed_value(pt)

Arguments

pt

A Plaintext.

Value

A native R complex vector.

See Also

get_real_packed_value() for the real-only view, make_ckks_packed_plaintext() for the matching constructor.


Associated CryptoContext of a Ciphertext

Description

Returns the CryptoContext that was used to construct ct. OpenFHE ciphertexts carry a back-pointer to their context so that homomorphic operations can dispatch to the correct scheme implementation without requiring the user to pass the context explicitly.

Usage

get_crypto_context(ct, ...)

Arguments

ct

A Ciphertext.

...

Reserved for future method-specific arguments.

Details

Naming note: get_crypto_context is distinct from get_crypto_parameters. The former returns the high-level CryptoContext S7 wrapper; the latter returns the opaque CryptoParameters S7 wrapper.

Value

A CryptoContext S7 object.


Crypto parameters of a CryptoContext

Description

Returns the CryptoParameters S7 object carrying the opaque ⁠std::shared_ptr<CryptoParametersBase<DCRTPoly>>⁠ at the C++ level. Useful for introspection; most R users will prefer to call the individual lambda-routed getters (e.g. get_scaling_technique(cc), get_batch_size(cc)) directly instead of going through the CryptoParameters object.

Usage

get_crypto_parameters(cc, ...)

Arguments

cc

A CryptoContext.

...

Reserved for future method-specific arguments.

Value

A CryptoParameters S7 object.


Cyclotomic order of a CryptoContext

Description

Integer m such that the underlying polynomial ring is Z[x]/(x^n + 1) with n = m/2 (the ring dimension). Always 2 * ring_dimension(cc) for power-of-two cyclotomics.

Usage

get_cyclotomic_order(cc, ...)

Arguments

cc

A CryptoContext.

...

Reserved for future method-specific arguments.

Value

Integer.


Modulus and representation of a plaintext's element

Description

get_element_modulus() returns the modulus of the ring element that encodes the plaintext, as a string of decimal digits. set_format() converts that element between the evaluation and coefficient representations.

Usage

get_element_modulus(pt)

set_format(pt, format)

Arguments

pt

A Plaintext.

format

A member of Format.

Value

get_element_modulus(): a character string of decimal digits. set_format(): pt, invisibly.

See Also

get_modulus()


Element parameters of a CryptoContext

Description

Returns the ElementParams S7 object wrapping ⁠std::shared_ptr<typename DCRTPoly::Params>⁠. This is the object that can be passed as the params argument to make_ckks_packed_plaintext() to build a plaintext against a specific parameter set rather than the context default.

Usage

get_element_params(cc, ...)

Arguments

cc

A CryptoContext.

...

Reserved for future method-specific arguments.

Details

This is the first R-side way to obtain a non-default ElementParams (the class itself has existed as a scaffold but had no constructor path until now).

Value

An ElementParams S7 object.


Encoding parameters of a CryptoContext

Description

Returns the EncodingParams S7 object wrapping ⁠std::shared_ptr<EncodingParamsImpl>⁠. Holds the plaintext modulus, batch size, and other encoding-level parameters.

Usage

get_encoding_params(cc, ...)

Arguments

cc

A CryptoContext.

...

Reserved for future method-specific arguments.

Value

An EncodingParams S7 object.


Retrieve the automorphism-key map for a given key tag

Description

Accessor for the cc-internal static automorphism-key map. The underlying C++ call returns a shared_ptr directly (no copy), so the returned EvalKeyMap is a live view of the cc registry.

Usage

get_eval_automorphism_key_map(key_tag)

Arguments

key_tag

Character; the key tag used when the map was originally generated.

Value

An EvalKeyMap.


Retrieve the EvalMult key vector for a given key tag

Description

Reads the vector of EvalMult keys registered under key_tag. Errors (via catch_openfhe) if the tag is not present in the registry.

Usage

get_eval_mult_key_vector(key_tag)

Arguments

key_tag

Character; the tag to look up (typically get_key_tag(sk) of a generated PrivateKey).

Value

A list of EvalKey objects.

See Also

get_all_eval_mult_keys(), insert_eval_mult_key()


Retrieve the sum-key map for a given key tag

Description

Accessor for the cc-internal static map populated by eval_sum_key_gen(). Used by the multi-party sum protocol to pull the lead party's initial eval-sum map so other parties can produce their shares.

Usage

get_eval_sum_key_map(key_tag)

Arguments

key_tag

Character; the key tag used when the map was originally generated. Typically the get_key_tag() of the secret key that produced it.

Details

The underlying C++ call returns a ⁠const std::map&⁠; the R wrapper copies the map into a fresh shared_ptr to give the returned EvalKeyMap owning semantics. The returned map is a snapshot: subsequent modifications to the cc registry are not reflected.

Value

An EvalKeyMap.


Which automorphism keys exist

Description

get_existing_eval_automorphism_key_indices() returns the automorphism indices for which keys are registered under a key tag. get_eval_automorphism_no_key_indices() returns those of a given set of indices that have no key yet. get_unique_values() is the set difference they are built on: the values of new_values that are not in old_values.

Usage

get_existing_eval_automorphism_key_indices(key_tag)

get_eval_automorphism_no_key_indices(key_tag, indices)

get_unique_values(old_values, new_values)

Arguments

key_tag

Character string; the tag of the secret key the keys were generated for (see get_key_tag()).

indices, old_values, new_values

Integer vectors.

Details

The indices are automorphism indices, as find_automorphism_index() returns, not rotation amounts.

Value

An integer vector in increasing order.


Multiplicative depth of functional bootstrapping

Description

get_fbt_depth() gives the depth eval_fbt() consumes for a look-up table, and get_fefbt_depth() the depth eval_fe_func_bootstrap() consumes for a Fourier series. Add the levels wanted after bootstrapping to get the multiplicative_depth of the context.

Usage

get_fbt_depth(
  level_budget,
  coefficients,
  p_input,
  order,
  skd,
  first_mod_size = 60L
)

get_fefbt_depth(
  level_budget,
  coefficients,
  skd = SecretKeyDist$SPARSE_TERNARY,
  first_mod_size = 60L
)

Arguments

level_budget

Integer vector of length 2; the levels spent on the coefficients-to-slots and slots-to-coefficients transforms.

coefficients

The coefficients of the look-up table (as for eval_fbt()) or of the Fourier series.

p_input

The input plaintext modulus: a string of decimal digits, or a whole number of at most 2^53.

order

Integer; the order of the Hermite interpolation.

skd

Secret key distribution, an element of SecretKeyDist.

first_mod_size

Integer; size of the first modulus in bits (read only for SecretKeyDist$SPARSE_ENCAPSULATED). Default 60L.

Value

An integer.


Trigonometric Hermite interpolation of a look-up table

Description

Computes the coefficients of the trigonometric Hermite interpolation of a function on the integers modulo p. They are the coeffs argument of eval_fbt() and its relatives in the general case.

Usage

get_hermite_trig_coefficients(func, p, order, scale)

Arguments

func

A function of one whole number in ⁠0, ..., p - 1⁠ returning one whole number: the look-up table.

p

Integer; the input plaintext modulus.

order

Integer; the order of the interpolation (1, 2 or 3).

scale

Numeric; the coefficients are divided by it. A scale that brings their magnitude near one is recommended; it is undone by the post_scaling argument of eval_fbt().

Value

A complex vector.

Examples

get_hermite_trig_coefficients(function(x) x %% 4, p = 8L, order = 1L,
                              scale = 1)

Hop level and encoding type of a ciphertext

Description

The hop level is the number of proxy re-encryptions recorded on a ciphertext. The encoding type records which plaintext encoding the ciphertext carries (see get_encoding_type()).

Usage

get_hop_level(ct)

set_hop_level(ct, hop_level)

set_encoding_type(ct, encoding_type)

Arguments

ct

A Ciphertext.

hop_level

Integer.

encoding_type

A member of PlaintextEncodings.

Value

get_hop_level(): an integer. The setters return ct, invisibly.


Key-generation level of a CryptoContext

Description

Integer level at which subsequent key_gen() calls will generate keys. Defaults to 0L. Useful when generating keys at a non-fresh level for deep circuit protocols.

Usage

get_key_gen_level(cc, ...)

Arguments

cc

A CryptoContext.

...

Reserved for future method-specific arguments.

Value

Integer.


Maximum supported plaintext space for functional bootstrapping

Description

Maximum supported plaintext space for functional bootstrapping

Usage

get_max_plaintext_space(ctx)

Arguments

ctx

A BinFHE context built with arb_func = TRUE

Value

A numeric scalar (q / (2 * beta))


The ciphertext modulus

Description

The modulus of an object, as a string of decimal digits, because it normally exceeds what an R number holds exactly.

Usage

get_modulus(x, ...)

Arguments

x

A CryptoContext or an ElementParams object.

...

Reserved for future method-specific arguments.

Details

For a CryptoContext or an ElementParams object it is the composite ciphertext modulus Q, the product of the RNS moduli. openfhe-python returns this value for a CryptoContext as a floating-point number; R returns it exactly.

Value

A character string of decimal digits.

See Also

get_modulus_ckks(), get_root_of_unity(), get_element_modulus()

Examples

cc <- fhe_context("BFV", plaintext_modulus = 65537, multiplicative_depth = 1)
get_modulus(cc)

Moduli and root of unity of a CryptoContext

Description

get_modulus_ckks() returns the first RNS modulus q_0 of a CKKS context. get_root_of_unity() returns the root of unity recorded in the context's element parameters, which is "0" for the composite (double-CRT) parameters the RNS schemes use. Both are strings of decimal digits.

Usage

get_modulus_ckks(cc)

get_root_of_unity(cc)

Arguments

cc

A CryptoContext.

Value

A character string of decimal digits.

See Also

get_modulus()


Multiplicative depth of a polynomial evaluation

Description

The depth the Paterson-Stockmeyer evaluation of a polynomial or Chebyshev series with the given coefficient vector consumes. It depends only on the number of coefficients.

Usage

get_multiplicative_depth_by_coeff_vector(vec, is_normalized = FALSE)

Arguments

vec

The coefficient vector (numeric or complex).

is_normalized

Logical; TRUE if the coefficients are normalized, which saves one level. Default FALSE.

Value

An integer.

See Also

eval_poly(), eval_chebyshev()


Parameters of a BinFHE context

Description

The LWE parameters of a context. OpenFHE names them by letter case, which R function names do not carry: get_n() is the lattice dimension n and get_big_n() the ring dimension N; get_q() is the small ciphertext modulus q and get_big_q() the large modulus Q (the C++ Getn(), GetN(), Getq() and GetQ()). get_beta() is the bound beta in the plaintext space q / (2 * beta).

Usage

get_n(ctx)

get_big_n(ctx)

get_q(ctx)

get_big_q(ctx)

get_beta(ctx)

Arguments

ctx

A BinFHEContext.

Value

get_n() and get_big_n(): an integer. The others: a number, or a string of decimal digits if the value is above 2^53.

See Also

get_max_plaintext_space()

Examples

ctx <- bin_fhe_context(BinFHEParamSet$TOY)
c(n = get_n(ctx), N = get_big_n(ctx), q = get_q(ctx), Q = get_big_q(ctx))

Get the native integer size of the OpenFHE build

Description

Returns 64 or 128 depending on how OpenFHE was compiled.

Usage

get_native_int()

Value

integer


Report the number of OpenMP threads available to OpenFHE

Description

Returns the cap OpenFHE currently applies to its parallel regions: the number of hardware threads at load, or the value most recently passed to set_num_threads(). Returns 1 when the package was built without OpenMP.

Usage

get_num_threads()

Value

integer; the current thread cap.

See Also

set_num_threads()

Examples

get_num_threads()

Get packed integer values from a plaintext

Description

Get packed integer values from a plaintext

Usage

get_packed_value(pt)

Arguments

pt

A Plaintext

Value

Integer vector


An empty plaintext of the type a decryption will fill

Description

The counterpart of the C++ static GetPlaintextForDecrypt(): a plaintext of the given encoding with no value yet, for code that decrypts by hand.

Usage

get_plaintext_for_decrypt(
  encoding_type,
  element_params,
  encoding_params,
  ckks_data_type = CKKSDataType$REAL
)

Arguments

encoding_type

A member of PlaintextEncodings.

element_params

An ElementParams object.

encoding_params

An EncodingParams object.

ckks_data_type

A member of CKKSDataType; default CKKSDataType$REAL.

Value

A Plaintext.


The plaintext generator of an encoding

Description

The generator of the cyclic group used to order the plaintext slots, as recorded in an EncodingParams object.

Usage

get_plaintext_generator(encoding_params)

Arguments

encoding_params

An EncodingParams object, from get_encoding_params().

Value

A number.


Moduli of an LWE ciphertext

Description

get_modulus() of an LWECiphertext is its ciphertext modulus, and get_pt_modulus() its plaintext modulus. set_modulus() and set_pt_modulus() change the values recorded in the ciphertext, in place; they do not rescale it.

Usage

get_pt_modulus(ct)

set_modulus(ct, modulus)

set_pt_modulus(ct, plaintext_modulus)

Arguments

ct

An LWECiphertext.

modulus, plaintext_modulus

The new value: a whole number of at most 2^53, or a string of decimal digits.

Details

get_modulus() and get_length() also work on an LWEPrivateKey and an LWEPublicKey, and == and != compare two LWE ciphertexts, two secret keys or two public keys by content.

Value

get_pt_modulus(): a number, or a string of decimal digits if the value is above 2^53. The setters: ct, invisibly.


Extract pointer with validation

Description

Extract pointer with validation

Usage

get_ptr(x)

Arguments

x

An OpenFHEObject

Value

The external pointer


The public key an object holds

Description

For a BinFHEContext, the LWE public key among its bootstrapping keys, present after bin_bt_key_gen() with KeygenMode$PUB_ENCRYPT. For a SchemeSwitchingDataDeserializer, the CKKS public key it has read.

Usage

get_public_key(x, ...)

Arguments

x

A BinFHEContext or a SchemeSwitchingDataDeserializer.

...

Not used.

Value

An LWEPublicKey or a PublicKey, or NULL if the object holds none.

See Also

get_bt_key()


Get real values from a CKKS plaintext

Description

Get real values from a CKKS plaintext

Usage

get_real_packed_value(pt)

Arguments

pt

A Plaintext

Value

Numeric vector

See Also

get_complex_packed_value() for the complex-view accessor on the same underlying plaintext (each slot internally carries a complex pair — this function returns only the real parts).


Real-valued CKKS scaling factor at a modulus-chain level

Description

Returns cryptoParams->GetScalingFactorReal(level) — the double-valued scaling factor at the given level of the CKKS modulus chain. Meaningful only for CKKS contexts; BFV/BGV contexts return the default field value (effectively 1.0).

Usage

get_scaling_factor_real(cc, ...)

Arguments

cc

A CryptoContext.

...

Method-specific arguments. The CryptoContext method accepts level (integer level in the RNS modulus chain, default 0L — the top of the chain = the scaling factor at fresh encryption time).

Details

Used by ckks_scaling_factor_bits() (which takes log2 of the level-0 value to recover the bit size originally set via set_scaling_mod_size()) and by the Stage 2 form of fhe_ckks_tolerance().

Value

Numeric scalar.


Insert a joined automorphism-key map into the cc registry

Description

After combining multi-party automorphism-key shares via multi_add_eval_automorphism_keys(), insert the joined map into the cc-internal registry so that eval_rotate() / eval_fast_rotation() can consume it.

Usage

insert_eval_automorphism_key(eval_key_map, key_tag = "")

Arguments

eval_key_map

An EvalKeyMap.

key_tag

Character; default "".

Value

NULL, invisibly.


Insert an EvalMult key vector into the cc registry

Description

Adds a vector of EvalKey objects to the CryptoContext's internal EvalMult-key map under key_tag. Silently replaces any existing matching keys. If key_tag is the empty string ("", the default), the tag is retrieved from the eval-key vector itself (each EvalKey carries its own tag).

Usage

insert_eval_mult_key(eval_keys, key_tag = "")

Arguments

eval_keys

A list of EvalKey objects (from multi_key_switch_gen(), multi_add_eval_mult_keys(), or from a deserialization).

key_tag

Character; the tag to register the vector under. Default "" (auto-detect from the first eval key in the vector).

Details

Used in checkpoint/resume workflows: after fhe_deserialize_eval_keys() or multi_add_eval_mult_keys() produces a combined eval-mult key vector, this function registers it into the cc's internal storage so that subsequent eval_mult() calls on ciphertexts encrypted under the associated party's key can consume it.

Value

NULL, invisibly.

See Also

insert_eval_sum_key(), insert_eval_automorphism_key()


Insert a joined sum-key map into the cc registry

Description

After combining multi-party shares via multi_add_eval_sum_keys(), the joined map has to be inserted back into the cc's internal static registry before eval_sum() can consume it. insert_eval_sum_key() routes the map through CryptoContextImpl::InsertEvalSumKey (which delegates internally to InsertEvalAutomorphismKey — the same static storage is shared between the two surfaces).

Usage

insert_eval_sum_key(eval_key_map, key_tag = "")

Arguments

eval_key_map

An EvalKeyMap from multi_add_eval_sum_keys() or constructed through the distributed key-gen flow.

key_tag

Character; the tag to register the map under. Default "".

Value

NULL, invisibly.


Combine encrypted and unencrypted masked decryptions

Description

Final step of the two-party interactive bootstrap protocol. Adds the server's masked decryption to the client's re-encryption to produce the refreshed ciphertext.

Usage

int_boot_add(ct1, ct2)

Arguments

ct1, ct2

Ciphertext objects — typically the outputs of int_boot_decrypt() and int_boot_encrypt().

Value

A refreshed Ciphertext.


Prepare a ciphertext for interactive bootstrap

Description

Adjusts a ciphertext's scale to meet the scheme's requirements before entering the interactive bootstrap protocol. Typically called before int_boot_decrypt().

Usage

int_boot_adjust_scale(ct)

Arguments

ct

A Ciphertext.

Value

A Ciphertext ready for int_boot_decrypt().


Server-side masked decryption for interactive bootstrap

Description

First step of the single-party interactive bootstrap protocol. The server applies its secret key share to produce a "masked" partial decryption that the client can finish off-line. Pairs with int_boot_encrypt() / int_boot_add() / int_boot_adjust_scale() to complete the refresh.

Usage

int_boot_decrypt(sk, ct)

Arguments

sk

A PrivateKey (server's share).

ct

A Ciphertext to refresh.

Value

A Ciphertext holding the masked decryption.

See Also

int_boot_encrypt(), int_boot_add(), int_boot_adjust_scale()


Client-side re-encryption for interactive bootstrap

Description

Encrypts the client's masked decryption result under the public key, raising the ciphertext modulus back to a fresh level.

Usage

int_boot_encrypt(pk, ct)

Arguments

pk

A PublicKey.

ct

A Ciphertext from the client (typically the masked-decryption output processed off-line).

Value

A refreshed Ciphertext.

See Also

int_boot_decrypt()


Aggregate multi-party shares pairs

Description

Combines the shares-pair lists produced by each party's call to int_mp_boot_decrypt() into a single aggregated shares pair for use in int_mp_boot_encrypt(). The input is a list of per-party shares-pair lists (a list of lists of Ciphertext).

Usage

int_mp_boot_add(cc, shares_pair_list)

Arguments

cc

A CryptoContext.

shares_pair_list

A list where each element is a list of Ciphertext objects from one party's int_mp_boot_decrypt() call.

Value

A list of Ciphertext objects — the aggregated shares pair.


Prepare a ciphertext for multi-party interactive bootstrap

Description

Multi-party analogue of int_boot_adjust_scale(). Adjusts the ciphertext's scale before entering the distributed bootstrap protocol.

Usage

int_mp_boot_adjust_scale(ct)

Arguments

ct

A Ciphertext.

Value

A Ciphertext ready for the multi-party bootstrap protocol.


Multi-party masked decryption for interactive bootstrap

Description

Each party calls this with their own secret share, the ciphertext being refreshed, and the common random element from int_mp_boot_random_element_gen(). Returns a list of two Ciphertext objects — the party's masked-decryption "shares pair". Each party's shares pair gets collected and fed into int_mp_boot_add().

Usage

int_mp_boot_decrypt(sk, ct, a)

Arguments

sk

A PrivateKey (this party's share).

ct

A Ciphertext to refresh.

a

A Ciphertext holding the common random element from int_mp_boot_random_element_gen().

Value

A list of two Ciphertext objects (the party's shares pair).


Final re-encryption for multi-party interactive bootstrap

Description

Lead party's final step in the multi-party interactive bootstrap. Takes the aggregated shares pair from int_mp_boot_add() plus the common random element and the original ciphertext, produces the refreshed ciphertext at a fresh modulus level.

Usage

int_mp_boot_encrypt(pk, shares_pair, a, ct)

Arguments

pk

The lead party's PublicKey.

shares_pair

A list of Ciphertext objects — the aggregated shares pair from int_mp_boot_add().

a

The common random element Ciphertext used in the per-party int_mp_boot_decrypt() calls.

ct

The original Ciphertext being refreshed.

Value

A refreshed Ciphertext.


Generate a common random element for multi-party bootstrap

Description

Generates a common random polynomial used by all parties in a multi-party interactive bootstrap round. Two overloads:

Usage

int_mp_boot_random_element_gen(cc, source)

Arguments

cc

A CryptoContext. Only used by the PublicKey overload; the Ciphertext overload ignores it and uses the source's internal cc.

source

Either a PublicKey or a Ciphertext.

Details

Value

A Ciphertext holding the common random element.


Is a KeyPair valid?

Description

Returns TRUE when both the public and secret keys of a KeyPair are non-null external pointers. The C++ KeyPair::good() predicate performs the same check on the C++ side; because R's KeyPair is a pure-R aggregate that wraps an already-constructed PublicKey and PrivateKey, the R-level check is equivalent.

Usage

is_good(kp, ...)

Arguments

kp

A KeyPair.

...

Reserved for future method-specific arguments (currently unused).

Value

TRUE or FALSE.


Generate key pair

Description

Generate key pair

Usage

key_gen(cc, ...)

Arguments

cc

A CryptoContext

...

Method-specific arguments (eval_mult, rotations)

Value

A KeyPair

Examples

cc <- fhe_context("CKKS", multiplicative_depth = 2L,
                  scaling_mod_size = 50L, batch_size = 8L)

## Encryption keys only:
kp <- key_gen(cc)
kp

## Also generate the relinearization key homomorphic multiplication
## needs and the rotation keys for shifts by one slot either way.
## These are stored inside the context, not in the returned pair.
kp <- key_gen(cc, eval_mult = TRUE, rotations = c(1L, -1L))
kp@public
kp@secret

Scale a ciphertext down from extended CRT basis to Q

Description

Brings a ciphertext that lives in the extended PQ basis (for example, the output of eval_fast_rotation_ext() with hybrid key switching) back to the standard Q basis. Only supported when the scheme is configured with hybrid key switching — other key-switching techniques have no round-trip to extended PQ and therefore nothing to scale back from.

Usage

key_switch_down(ct)

Arguments

ct

A Ciphertext in the extended P*Q basis.

Value

A Ciphertext in the Q basis.

See Also

eval_fast_rotation_ext()


Steps of hybrid key switching

Description

Hybrid key switching works in an extended basis P*Q and comes back to Q at the end. These functions expose two of its steps, for code that hoists or defers them (CKKS). key_switch_ext() takes a ciphertext to the extended basis, multiplying its elements by P; with add_first = FALSE the first element of the result is left at zero. key_switch_down_first_element() brings only the first element back to Q and returns it as a ring element. key_switch_down() brings a whole ciphertext back.

Usage

key_switch_ext(ct, add_first)

key_switch_down_first_element(ct)

Arguments

ct

A Ciphertext.

add_first

Logical.

Value

key_switch_ext(): a Ciphertext in the extended basis. key_switch_down_first_element(): a DCRTPoly.


Switch a ciphertext from one secret key to another

Description

key_switch_gen() makes the key that switches ciphertexts under old_private_key to ciphertexts under new_private_key. key_switch() applies it and returns the switched ciphertext; key_switch_in_place() switches the ciphertext it is given.

Usage

key_switch_gen(cc, old_private_key, new_private_key)

key_switch(ct, eval_key)

key_switch_in_place(ct, eval_key)

Arguments

cc

A CryptoContext.

old_private_key, new_private_key

PrivateKey objects.

ct

A Ciphertext.

eval_key

The EvalKey from key_switch_gen().

Value

key_switch_gen(): an EvalKey. key_switch(): a Ciphertext. key_switch_in_place(): ct, invisibly.

See Also

re_key_gen() for the form that needs only the public key of the receiving party.


Key tag accessors

Description

Every PublicKey / PrivateKey carries a string "key tag" identifying which key pair it belongs to. The tag is set at key-generation time by OpenFHE and can be inspected or overwritten via these accessors. In threshold / multiparty protocols the tag is used to associate a key with the party that owns it; in single-user protocols it is typically left at its default.

Usage

get_key_tag(key, ...)

set_key_tag(key, ...)

Arguments

key

A PublicKey or PrivateKey.

...

Reserved for future method-specific arguments. set_key_tag accepts a value argument here.

Value

get_key_tag: character scalar. set_key_tag: the key invisibly.


Reduce the modulus chain by multiple levels

Description

Drops levels levels from x's modulus chain in a single operation. Useful when x is at a deeper level than the ciphertext it will interact with next; level-reducing brings them onto the same rung of the chain.

Usage

level_reduce(x, ...)

Arguments

x

A Ciphertext.

...

Method-specific arguments: eval_key (an EvalKey, or NULL for no key), levels (integer, default 1L).

Details

The C++ signature takes an evaluation key, which the RNS schemes do not use. Pass NULL, as the OpenFHE examples pass a null key, or an EvalKey.

Value

A Ciphertext at x$level + levels.


Reduce the modulus chain by multiple levels, in place

Description

Reduce the modulus chain by multiple levels, in place

Usage

level_reduce_in_place(x, ...)

Arguments

x

A Ciphertext (modified in place).

...

Method-specific arguments: eval_key (an EvalKey, or NULL for no key), levels (integer, default 1L).

Value

x invisibly.


Make a CKKS packed plaintext from real numbers

Description

Encode a real-valued numeric vector as a CKKS packed plaintext. The result is an unencrypted Plaintext object that can then be passed to encrypt().

Usage

make_ckks_packed_plaintext(
  cc,
  values,
  noise_scale_deg = 1L,
  level = 0L,
  params = NULL,
  slots = 0L
)

Arguments

cc

A CryptoContext built with scheme = "CKKS".

values

A numeric vector to pack. Length must not exceed slots (or batch_size / 2 when slots is left at 0L).

noise_scale_deg

Integer degree of the initial scaling factor applied to the encoded plaintext, expressed as a power of the scheme's scaling factor. Defaults to 1L, meaning "scale by the base scaling factor once", which is the value every current vignette implicitly uses. Setting noise_scale_deg = 2L encodes at scaling factor squared, which is occasionally useful when the plaintext is about to be subtracted from a ciphertext that has already been rescaled once and the two noise levels must agree. Under FLEXIBLEAUTO scaling the scheme's auto-rescale logic overrides this argument at context-generation time, so this parameter is only meaningful under FIXEDMANUAL. Couples tightly to level: a plaintext at ⁠(noise_scale_deg = k, level = L)⁠ may only interact with ciphertexts at the same ⁠(k, L)⁠.

level

Integer target encryption level of the encoded plaintext. Defaults to 0L, meaning "encode at the fresh level, matching a just-encrypted ciphertext". When performing an operation between an encoded plaintext and a ciphertext that has already been rescaled L times, the plaintext must be encoded at level = L so the two sit at the same level of the modulus chain; otherwise the evaluator will silently mismatch or error depending on the scheme variant. The canonical case for setting this is encoding a constant vector for use inside a deep CKKS circuit, not for fresh-input computation. Couples to noise_scale_deg and to the multiplicative depth of the crypto context, which bounds the maximum valid level.

params

Advanced. An ElementParams object to encode against, or NULL to use the cryptocontext's own parameters at the chosen level. Defaults to NULL, which is the only value any current vignette or test uses. There is no R-side way to construct a fresh ElementParams (only to wrap one returned by get_element_params(cc)), so in practice the argument is accepted for compatibility with the C++ API but is normally left at its default.

slots

Integer number of CKKS slots to pack into. Defaults to 0L, which is the upstream sentinel for "use the batch_size set on the context's params". Setting slots to a smaller power of two produces a plaintext that leaves the upper half of the packing register zero, which the evaluator exploits to reduce rotation cost in algorithms like eval_sum. The value must be a power of two and must not exceed batch_size. The natural time to set this is when you have a short input vector and rotations dominate the circuit cost, as in the CKKS-inner-product idiom; the natural time to leave it at 0L is when you are encoding a full-width vector.

Value

A Plaintext.

Examples

cc <- fhe_context("CKKS", multiplicative_depth = 2L,
                  scaling_mod_size = 50L, batch_size = 8L)

## Encode four reals into the CKKS slots. The remaining slots are
## zero-padded out to `batch_size`.
pt <- make_ckks_packed_plaintext(cc, c(0.25, 0.5, 0.75, 1))
pt
get_real_packed_value(set_length(pt, 4L))

Make a coefficient-packed integer plaintext

Description

Encode an integer vector as a coefficient-packed plaintext. Coefficient packing places each input value in a separate polynomial coefficient and is the alternative to the SIMD batched packing produced by make_packed_plaintext(). Used by the integer-modulus Ring-LWE vignettes where per-coefficient access is needed.

Usage

make_coef_packed_plaintext(cc, values, noise_scale_deg = 1L, level = 0L)

Arguments

cc

A CryptoContext (BFV or BGV).

values

An integer vector whose length must not exceed the ring dimension of cc.

noise_scale_deg

See the make_packed_plaintext() entry.

level

See the make_packed_plaintext() entry.

Value

A Plaintext.


Make a packed integer plaintext

Description

Encode an integer vector as a BFV / BGV packed plaintext. The result is an unencrypted Plaintext object that can then be passed to encrypt().

Usage

make_packed_plaintext(cc, values, noise_scale_deg = 1L, level = 0L)

Arguments

cc

A CryptoContext.

values

An integer vector to pack. Length must not exceed batch_size set at context creation.

noise_scale_deg

Integer degree of the initial scaling factor applied to the encoded plaintext. Defaults to 1L; only meaningful under FIXEDMANUAL scaling (under FLEXIBLEAUTO the scheme overrides this value). Every current vignette leaves it at the default.

level

Integer target level in the RNS modulus chain. Defaults to 0L, meaning "fresh level, matching a just-encrypted ciphertext". Set to match the level of a ciphertext the plaintext will interact with if the ciphertext has already been rescaled.

Value

A Plaintext.


Encode a character string as a plaintext

Description

Each character becomes one coefficient, so the plaintext modulus must be large enough for the character codes; the OpenFHE examples use 256. Read the string back with get_string_value().

Usage

make_string_plaintext(cc, str)

Arguments

cc

A CryptoContext (BFV or BGV).

str

A single character string.

Value

A Plaintext.


Reduce the modulus chain by one level

Description

Synonym for rescale(). Both names dispatch to the same C++ operation (CryptoContextImpl::Rescale delegates to ModReduce internally); the R binding keeps both so callers can use whichever name matches the OpenFHE documentation they're following.

Usage

mod_reduce(x, ...)

Arguments

x

A Ciphertext.

...

Reserved for future method-specific arguments.

Value

A Ciphertext at one lower level.

See Also

rescale(), mod_reduce_in_place()


Reduce the modulus chain by one level, in place

Description

Reduce the modulus chain by one level, in place

Usage

mod_reduce_in_place(x, ...)

Arguments

x

A Ciphertext (modified in place).

...

Reserved for future method-specific arguments.

Value

x invisibly.


Combine two automorphism-key map shares

Description

Combine two automorphism-key map shares

Usage

multi_add_eval_automorphism_keys(
  cc,
  eval_key_map1,
  eval_key_map2,
  key_tag = ""
)

Arguments

cc

A CryptoContext.

eval_key_map1, eval_key_map2

EvalKeyMap shares from two parties.

key_tag

Character; default "".

Value

A combined EvalKeyMap suitable for insertion into the cc registry via insert_eval_automorphism_key().


Combine evaluation keys from multiple parties

Description

Combines two partial key-switching eval keys into a joint eval key. See multi_add_eval_mult_keys() for the eval-mult variant — the two functions consume keys produced by different generators and are not interchangeable.

Usage

multi_add_eval_keys(cc, ek1, ek2, key_tag = "")

Arguments

cc

A CryptoContext

ek1, ek2

EvalKey objects to combine

key_tag

Character; optional tag to associate with the combined key. Default "".

Value

A combined EvalKey


Combine partial eval-mult keys from multiple parties

Description

The eval-mult flavor of multi_add_eval_keys(). Consumes keys produced by a multi-party eval-mult key generator rather than by multi_key_switch_gen(). Where the R generator is not yet exposed, the wrapper still lets downstream code exercise the add-keys flow against keys constructed through the underlying cpp11 binding.

Usage

multi_add_eval_mult_keys(cc, ek1, ek2, key_tag = "")

Arguments

cc

A CryptoContext

ek1, ek2

EvalKey objects (eval-mult partials) to combine

key_tag

Character; optional tag to associate with the combined key. Default "".

Value

A combined EvalKey


Combine two sum-key map shares into a joint sum-key map

Description

Combine two sum-key map shares into a joint sum-key map

Usage

multi_add_eval_sum_keys(cc, eval_key_map1, eval_key_map2, key_tag = "")

Arguments

cc

A CryptoContext.

eval_key_map1, eval_key_map2

EvalKeyMap shares from two parties.

key_tag

Character; default "".

Value

A combined EvalKeyMap suitable for insertion into the cc registry via insert_eval_sum_key().


Combine public keys from multiple parties

Description

Combine public keys from multiple parties

Usage

multi_add_pub_keys(cc, pk1, pk2, key_tag = "")

Arguments

cc

A CryptoContext

pk1, pk2

PublicKey objects to combine

key_tag

Character; optional tag to associate with the combined key. Default "" (empty tag) to match the C++ header default. Round-trips through get_key_tag().

Value

A combined PublicKey


Generate a joint rotation-at-index key share

Description

The EvalAtIndex flavor of multi_eval_automorphism_key_gen(); takes signed rotation indices rather than automorphism indices. Semantically equivalent but lives on a distinct C++ entry point.

Usage

multi_eval_at_index_key_gen(cc, sk, eval_key_map, index_list, key_tag = "")

Arguments

cc

A CryptoContext.

sk

This party's PrivateKey share.

eval_key_map

An existing EvalKeyMap.

index_list

Integer vector of signed rotation indices.

key_tag

Character; default "".

Value

An EvalKeyMap.


Generate a joint automorphism-key share for multi-party rotation

Description

Produces this party's share of the joined automorphism eval key map for the supplied index_list. Each other party calls the same method with their own secret share, and the shares are combined via multi_add_eval_automorphism_keys() to produce the final joined map.

Usage

multi_eval_automorphism_key_gen(cc, sk, eval_key_map, index_list, key_tag = "")

Arguments

cc

A CryptoContext with the MULTIPARTY feature enabled.

sk

This party's PrivateKey share.

eval_key_map

An existing EvalKeyMap carrying the prior-party automorphism key state, obtained via get_eval_automorphism_key_map() after the lead party has populated the cc registry through key_gen(cc, rotations = ...).

index_list

Integer vector of rotation indices.

key_tag

Character; optional tag to associate with the produced map. Default "".

Value

An EvalKeyMap holding this party's joint share.


Generate a joint sum-key share for multi-party EvalSum

Description

Generate a joint sum-key share for multi-party EvalSum

Usage

multi_eval_sum_key_gen(cc, sk, eval_key_map, key_tag = "")

Arguments

cc

A CryptoContext.

sk

This party's PrivateKey share.

eval_key_map

An existing EvalKeyMap carrying the prior-party sum-key state, obtained via get_eval_sum_key_map() after the lead party has populated the cc registry through eval_sum_key_gen().

key_tag

Character; default "".

Value

An EvalKeyMap.


Multi-party key-switch eval-key generation

Description

Generates an eval key that switches ciphertexts encrypted under sk_orig into a form decryptable by sk_new, starting from an existing eval key that carries the key-switch auxiliary information. Used by threshold protocols to route partial decryptions across a re-keyed party set.

Usage

multi_key_switch_gen(cc, sk_orig, sk_new, eval_key)

Arguments

cc

A CryptoContext

sk_orig

The original party's PrivateKey

sk_new

The new party's PrivateKey

eval_key

An EvalKey carrying key-switch auxiliary data

Value

An EvalKey suitable for routing through multi_add_eval_keys() to combine with other parties' key-switch shares


A party's share of the joint multiplication key (threshold FHE)

Description

In the threshold protocol each party multiplies the combined key-switching key by its own secret share; the results are then added with multi_add_eval_mult_keys() to give the joint relinearization key.

Usage

multi_mult_eval_key(cc, sk, eval_key, key_tag = "")

Arguments

cc

A CryptoContext.

sk

The party's PrivateKey (its secret share).

eval_key

The combined EvalKey from multi_add_eval_keys().

key_tag

Character string; the tag for the result, "" (default) to keep the library's choice.

Value

An EvalKey.


Fuse partial decryptions into final plaintext

Description

Combines partial decryptions from any number of parties (n >= 2). The lead party's partial decryption (from multiparty_decrypt_lead()) must be supplied first; subsequent partials (from multiparty_decrypt_main()) follow in any order.

Usage

multiparty_decrypt_fusion(cc, ...)

Arguments

cc

A CryptoContext

...

Two or more partially decrypted Ciphertext objects. The first must be from the lead party.

Value

A Plaintext with the final decrypted result


Lead party's partial decryption

Description

In threshold decryption, the lead party calls this first. Accepts either a single Ciphertext or a list of Ciphertext objects:

Usage

multiparty_decrypt_lead(cc, sk, ct)

Arguments

cc

A CryptoContext

sk

This party's PrivateKey

ct

A Ciphertext or a list of Ciphertexts

Details

Value

A partially decrypted Ciphertext or list of Ciphertexts, mirroring the input shape.


Non-lead party's partial decryption

Description

Other parties call this after the lead. Accepts either a single Ciphertext or a list of Ciphertext objects with the same semantics as multiparty_decrypt_lead().

Usage

multiparty_decrypt_main(cc, sk, ct)

Arguments

cc

A CryptoContext

sk

This party's PrivateKey

ct

A Ciphertext or a list of Ciphertexts

Value

A partially decrypted Ciphertext or list of Ciphertexts, mirroring the input shape.


Generate a key pair for a secondary party in threshold FHE

Description

The lead party uses key_gen() to generate the initial keypair. Subsequent parties call this with the lead's public key.

Usage

multiparty_key_gen(cc, lead_pk, make_sparse = FALSE, fresh = FALSE)

Arguments

cc

A CryptoContext (must have MULTIPARTY feature enabled)

lead_pk

The lead party's PublicKey, or a list of PrivateKey objects for the form that combines secret keys.

make_sparse

Logical; if TRUE, produce an LWE-sparse secret. Default FALSE to match the C++ header default. RLWE-only semantics; BFV/BGV/CKKS accept both values.

fresh

Logical; if TRUE, sample a fresh secret rather than deriving one from the existing key material. Default FALSE.

Details

OpenFHE declares a second form that takes the secret keys of all parties and returns the key pair of their sum. Pass a list of PrivateKey objects as lead_pk to call it; make_sparse and fresh do not apply to that form.

Value

A KeyPair for this party, or, for a list of secret keys, the key pair of the combined secret.


The ring elements of a ciphertext

Description

A ciphertext is a list of ring elements: two when fresh, three after a multiplication that has not been relinearized.

Usage

number_ciphertext_elements(ct)

get_elements(ct)

get_elements_mutable(ct)

set_elements(ct, elements)

set_elements_move(ct, elements)

remove_element(ct, index)

Arguments

ct

A Ciphertext.

elements

A list of DCRTPoly objects.

index

Integer; which element to remove, counting from 1.

Details

number_ciphertext_elements() counts them. get_elements() returns copies of them as a list of DCRTPoly handles, and set_elements() replaces the elements of a ciphertext with copies of the ones given. remove_element() deletes one. get_elements_mutable() and set_elements_move() are the names openfhe-python gives to the same two operations; in R, as in Python, they exchange copies.

Value

number_ciphertext_elements(): an integer. get_elements() and get_elements_mutable(): a list of DCRTPoly objects. The others return ct, invisibly.


Plaintext accessors

Description

Retrieve or set fields on a Plaintext object. Each accessor wraps the corresponding upstream ⁠PlaintextImpl::Get*⁠/⁠Set*⁠ method and returns its value unchanged.

Usage

get_noise_scale_deg(x, ...)

get_length(x, ...)

get_level(x, ...)

get_scaling_factor(x, ...)

get_log_precision(x, ...)

get_formatted_values(x, ...)

set_ckks_data_type(x, ...)

get_encoding_type(x, ...)

get_scaling_factor_int(x, ...)

get_scheme_id(x, ...)

is_encoded(x, ...)

low_bound(x, ...)

high_bound(x, ...)

get_slots(x, ...)

get_log_error(x, ...)

get_coef_packed_value(x, ...)

get_string_value(x, ...)

get_element_ring_dimension(x, ...)

set_scaling_factor(x, ...)

set_scaling_factor_int(x, ...)

set_noise_scale_deg(x, ...)

set_level(x, ...)

set_slots(x, ...)

set_string_value(x, ...)

set_int_vector_value(x, ...)

Arguments

x

A Plaintext.

...

Reserved for future method-specific arguments. Setters accept a value argument here; get_formatted_values accepts a precision integer.

Details

Several base-class accessors are declared virtual and throw OPENFHE_THROW in the base implementation (e.g. get_string_value on a non-string plaintext, get_log_precision on a non-CKKS plaintext). Calling an accessor on the wrong kind of plaintext therefore raises an R error via cli::cli_abort, not a silent wrong value.

Value

The underlying field value. Types vary per accessor.

Functions


Deterministic hash of a plaintext's identifying parameters

Description

Combines the plaintext's encoding type, scaling factor, noise scale degree, level, and slot count into a deterministic string representation. Two plaintexts with identical parameters produce identical strings; any parameter change produces a different string.

Usage

plaintext_params_hash(x)

Arguments

x

A Plaintext.

Details

Not a cryptographic hash — equality comparison is the only guarantee. The returned string's format is implementation detail and may change without notice.

Value

Character scalar.


Check if an external pointer is valid (non-NULL)

Description

Check if an external pointer is valid (non-NULL)

Usage

ptr_is_valid(x)

Arguments

x

An OpenFHEObject

Value

logical


Proxy re-encryption

Description

re_key_gen() makes a re-encryption key from one party's secret key and another party's public key. With it, re_encrypt() turns a ciphertext under the first party's key into one the second party can decrypt, without decrypting it. The context needs Feature$PRE.

Usage

re_key_gen(cc, old_private_key, new_public_key)

re_encrypt(ct, eval_key, public_key = NULL)

Arguments

cc

A CryptoContext.

old_private_key

The PrivateKey the ciphertexts are currently encrypted under.

new_public_key

The PublicKey of the party who is to decrypt.

ct

A Ciphertext.

eval_key

The EvalKey from re_key_gen().

public_key

The PublicKey of the party the ciphertext is currently encrypted for, or NULL (default). It is used to re-randomize the result in the security modes that require it.

Value

re_key_gen() returns an EvalKey; re_encrypt() a Ciphertext.


Recover a secret key from distributed shares

Description

Inverse of share_keys(). Given a SecretShareMap holding at least threshold shares, reconstructs a PrivateKey equivalent to the original secret at the point of sharing. The reconstructed key participates in distributed decryption identically to the original, so a dropped-out party's share of a threshold decryption can still be completed by the remaining parties.

Usage

recover_shared_key(
  cc,
  share_map,
  n_parties,
  threshold,
  sharing_scheme = "additive"
)

Arguments

cc

A CryptoContext. Used to construct the empty placeholder key that the scheme routine fills in.

share_map

A SecretShareMap from share_keys().

n_parties

Integer; must match the value used at share_keys() time.

threshold

Integer; must match the value used at share_keys() time.

sharing_scheme

Character; must match the value used at share_keys() time.

Details

Under the hood, the C++ API takes a mutable PrivateKey reference that must be pre-allocated as an empty PrivateKeyImpl bound to cc. The R wrapper constructs that empty placeholder internally so R users do not have to know about the in-place-fill convention.

Value

A PrivateKey holding the reconstructed secret.

See Also

share_keys()


Relinearize a higher-degree ciphertext

Description

Reduces a ciphertext to 2 polynomial components. Needed after a sequence of eval_mult_no_relin() calls to restore a decryptable form. A relinearization key must have been generated via key_gen(cc, eval_mult = TRUE) before calling this.

Usage

relinearize(x, ...)

Arguments

x

A Ciphertext (may have more than 2 components).

...

Reserved for future method-specific arguments.

Value

A Ciphertext with exactly 2 components.


Rescale a CKKS ciphertext (alias for ModReduce)

Description

Reduces the modulus chain by one level. Required after eval_mult under FIXEDMANUAL scaling; automatic under FIXEDAUTO / FLEXIBLEAUTO.

Usage

rescale(ct, ...)

Arguments

ct

A Ciphertext

...

Reserved for future method-specific arguments

Value

A Ciphertext at one lower level


Ring dimension of a CryptoContext

Description

Returns N, the cyclotomic ring dimension. The cyclotomic order M used by eval_fast_rotation() is 2 * N.

Usage

ring_dimension(cc, ...)

Arguments

cc

A CryptoContext

...

Reserved for future method-specific arguments

Value

Integer ring dimension


Convert between RLWE and CKKS ciphertexts

Description

schemelet_convert_rlwe_to_ckks() embeds an RLWE ciphertext modulo big_q into a CKKS ciphertext with slots slots at level, so that eval_fbt() can process it. schemelet_convert_ckks_to_rlwe() extracts an RLWE ciphertext modulo q from a CKKS ciphertext. Both ciphertexts are under the same secret key.

Usage

schemelet_convert_rlwe_to_ckks(cc, coeffs, pub_key, big_q, slots, level = 0L)

schemelet_convert_ckks_to_rlwe(ctxt, q)

Arguments

cc

A CKKS CryptoContext.

coeffs

A PolyVector; the RLWE ciphertext.

pub_key

The PublicKey, used for an encryption of zero that supplies the metadata of the CKKS ciphertext.

big_q

The modulus of the RLWE ciphertext: a string of decimal digits, or a whole number of at most 2^53.

slots

Integer; number of slots of the CKKS ciphertext.

level

Integer; level of the CKKS ciphertext. Default 0L.

ctxt

A CKKS Ciphertext with two elements.

q

The modulus of the RLWE ciphertext to produce, as for big_q.

Value

schemelet_convert_rlwe_to_ckks(): a Ciphertext. schemelet_convert_ckks_to_rlwe(): a PolyVector.

See Also

schemelet_encrypt_coeff(), eval_fbt()


RLWE encryption under a CKKS secret key

Description

The RLWE schemelet of OpenFHE (SchemeletRLWEMP): integers modulo p are encrypted as the coefficients of an RLWE ciphertext over one large modulus q, under the secret key of a CKKS context. It is the input and output format of CKKS functional bootstrapping; see eval_fbt().

Usage

schemelet_get_element_params(private_key, level = 0L)

schemelet_encrypt_coeff(
  input,
  q,
  p,
  private_key,
  element_params,
  bit_reverse = FALSE
)

schemelet_decrypt_coeff(
  input,
  q,
  p,
  private_key,
  element_params,
  num_slots,
  length = 0L,
  bit_reverse = FALSE
)

schemelet_mod_switch(input, q1, q2)

schemelet_get_q_prime(pub_key, lvls)

Arguments

private_key

A PrivateKey of a CKKS context.

level

Integer; number of levels to remove. Default 0L.

input

For schemelet_encrypt_coeff(), a vector of whole numbers, each reduced modulo p as a signed value. For schemelet_decrypt_coeff() and schemelet_mod_switch(), a PolyVector.

q, p, q1, q2

Moduli: strings of decimal digits, or whole numbers of at most 2^53. q is the ciphertext modulus and p the plaintext modulus.

element_params

An ElementParams object from schemelet_get_element_params().

bit_reverse

Logical; encode the input in bit-reversed order (and undo it at decryption). Default FALSE.

num_slots

Integer; the number of slots used in the CKKS computation, which sets the stride between message coefficients.

length

Integer; number of values to return, 0L (default) for num_slots.

pub_key

A PublicKey of a CKKS context.

lvls

Integer; number of moduli after q_0 to include.

Details

schemelet_get_element_params() returns the element parameters of the key's context with level levels removed. Its modulus is the one schemelet_encrypt_coeff() samples its encryption of zero over.

schemelet_encrypt_coeff() encrypts input and returns the RLWE ciphertext modulo q. schemelet_decrypt_coeff() decrypts one, returning values in ⁠(-p/2, p/2]⁠.

schemelet_mod_switch() switches a ciphertext from modulus q2 to modulus q1 in place, scaling by q1/q2 with rounding.

schemelet_get_q_prime() returns the product q_0 * q_1 * ... * q_lvls of the first lvls + 1 RNS moduli of the key's parameters.

Value

schemelet_get_element_params(): an ElementParams object. schemelet_encrypt_coeff(): a PolyVector. schemelet_decrypt_coeff(): a numeric vector. schemelet_mod_switch(): input, invisibly. schemelet_get_q_prime(): a string of decimal digits.

See Also

schemelet_convert_rlwe_to_ckks()

Examples

cc <- fhe_context("CKKS", multiplicative_depth = 2L, scaling_mod_size = 50L,
                  batch_size = 8L)
keys <- key_gen(cc)
ep <- schemelet_get_element_params(keys@secret)
q <- "1152921504606846976"   # 2^60
ct <- schemelet_encrypt_coeff(c(1, 2, 3, 4, 5, 6, 7, 0), q, 16,
                              keys@secret, ep)
schemelet_decrypt_coeff(ct, q, 16, keys@secret, ep, num_slots = 8L)

Serialize the keys CKKS bootstrapping uses

Description

serialize_eval_bootstrap_key() writes to a file the automorphism keys that bootstrapping with slots slots uses, out of those registered for cc under key_tag. deserialize_eval_bootstrap_key() reads such a file into the registry: with cc and slots, the keys that bootstrapping setup asks for; without cc, the keys with the automorphism indices in index_list.

Usage

serialize_eval_bootstrap_key(filename, cc, key_tag, slots, format = "binary")

deserialize_eval_bootstrap_key(
  filename,
  cc = NULL,
  key_tag,
  slots = NULL,
  index_list = NULL,
  format = "binary"
)

Arguments

filename

Path to the file.

cc

A CryptoContext on which eval_bootstrap_setup() has been called. For deserialize_eval_bootstrap_key(), NULL to select keys by index_list.

key_tag

Character string; the key tag.

slots

Integer; the number of slots.

format

"binary" (default) or "json"

index_list

Integer vector of automorphism indices; used when cc is NULL.

Value

TRUE on success, FALSE otherwise.


Serialize evaluation keys from the key registry

Description

Writes the registered multiplication, automorphism or summation keys to a file, or, with filename = NULL, returns them serialized in memory. The keys are those under key_tag, or, when cc is given, those of that context.

Usage

serialize_eval_keys(
  filename = NULL,
  type = c("mult", "automorphism", "sum"),
  format = "binary",
  key_tag = "",
  cc = NULL
)

Arguments

filename

Path to the output file, or NULL (default) to serialize in memory.

type

"mult", "automorphism" or "sum".

format

"binary" (default) or "json"

key_tag

Key tag; "" (default) for the keys of every tag.

cc

A CryptoContext, or NULL (default). When given, key_tag is not used.

Value

With a file name, TRUE invisibly. Otherwise a raw vector (format = "binary") or a character string (format = "json").

See Also

deserialize_eval_keys(), deserialize_eval_keys_string()


Name and version of a serialized object

Description

The name under which OpenFHE writes an object of this class in its serialized form, and the version number of that form.

Usage

serialized_object_name(x, ...)

serialized_version(x, ...)

Arguments

x

A CryptoContext or a BinFHEContext.

...

Reserved for future method-specific arguments.

Value

serialized_object_name(): a character string. serialized_version(): an integer.


Set the CKKS bootstrap correction factor

Description

Sets the scheme-level correction factor used by subsequent bootstraps. Normally this is set via the correction_factor argument to eval_bootstrap_setup() at bootstrap setup time; this pair exists for post-setup programmatic control.

Usage

set_ckks_boot_correction_factor(cc, cf)

Arguments

cc

A CryptoContext.

cf

Integer; the new correction factor.

Value

The cc, invisibly.

See Also

get_ckks_boot_correction_factor()


Set the key-generation level of a CryptoContext

Description

Set the key-generation level of a CryptoContext

Usage

set_key_gen_level(cc, ...)

Arguments

cc

A CryptoContext.

...

Method-specific arguments; the level integer is passed here.

Value

cc invisibly.


Set the effective length of a plaintext

Description

Set the effective length of a plaintext

Usage

set_length(pt, len)

Arguments

pt

A Plaintext

len

Integer length

Value

Invisibly, the pt plaintext that was passed in. Called for its side effect: the plaintext is truncated in place so that the accessors report only the first len slots, which is how the padding introduced by encoding is trimmed after decryption.


Set the number of OpenMP threads OpenFHE may use

Description

OpenFHE parallelizes its core arithmetic with OpenMP and, by default, uses every hardware thread the machine reports. set_num_threads() sets the cap through OpenFHE's own thread controls, which every parallel region in the library consults when it starts, so the change takes effect immediately, on every platform, and regardless of which thread the work runs on. It is a no-op when the package was built without OpenMP.

Usage

set_num_threads(n)

Arguments

n

integer; the requested maximum number of threads (at least 1).

Details

Requests above the number of threads available when the library was loaded (the hardware count, or OMP_NUM_THREADS if that was set before R started) are reduced to that number. The value in effect is returned, so a reduced request is visible to the caller; get_num_threads() reports the same value later.

The package default is uncapped, so interactive users get full parallelism. Under ⁠R CMD check⁠, which sets ⁠_R_CHECK_LIMIT_CORES_⁠, the package caps itself at two threads when it is loaded, in line with CRAN's two-thread policy. This also covers packages that depend on 'openfhe.R', which therefore need no thread handling of their own.

Value

integer; the cap now in effect, invisibly.

See Also

get_num_threads()

Examples

old <- get_num_threads()
set_num_threads(2L)
set_num_threads(old)

Fill scheme-switching parameters from a CKKS context

Description

Copies the first modulus, the ring dimension, the scaling modulus size and the batch size of cc into params, and marks params as filled. eval_ckks_to_fhew_setup() and eval_scheme_switching_setup() do this themselves.

Usage

set_params_from_ckks_cryptocontext(cc, params)

Arguments

cc

A CKKS CryptoContext.

params

A SchSwchParams object; changed in place.

Value

params, invisibly.


Set the scheme identifier of a CryptoContext

Description

The counterpart of the C++ setSchemeId(). The identifier is set when the context is generated; this function is for code that assembles a context by hand.

Usage

set_scheme_id(cc, scheme_tag)

Arguments

cc

A CryptoContext.

scheme_tag

A member of SchemeId.

Value

cc, invisibly.


Distribute a secret key into shares

Description

Produces the set of shares that party index would distribute to the other parties under the chosen sharing_scheme. The returned SecretShareMap is opaque; in a real deployment the shares would be serialized and routed over the network to each receiving party, and the receiving parties would store them for use in an abort recovery.

Usage

share_keys(cc, sk, n_parties, threshold, index, sharing_scheme = "additive")

Arguments

cc

A CryptoContext with the MULTIPARTY feature.

sk

The PrivateKey to share.

n_parties

Integer; total number of parties.

threshold

Integer; minimum number of shares needed to reconstruct. For "additive" this must be n_parties - 1; for "shamir" it is typically floor(n_parties/2) + 1.

index

Integer; the 1-based index of the party owning sk (the "my share index").

sharing_scheme

Character; either "additive" (default) or "shamir".

Details

Two sharing schemes are supported:

Value

A SecretShareMap suitable for passing to recover_shared_key(). length() of it is the number of shares.

See Also

recover_shared_key()


Generate a sparse key pair

Description

Calls the C++ SparseKeyGen(), which the OpenFHE header describes as a key pair "with special structure and without full entropy" for uses such as ring reduction, and as not supported by any scheme at present. Use key_gen() for ordinary keys.

Usage

sparse_key_gen(cc)

Arguments

cc

A CryptoContext.

Value

A KeyPair.


Switch a public-key ciphertext to the small modulus and dimension

Description

A ciphertext encrypted under a public key has modulus Q and dimension N. switch_ct_to_qn() converts it to modulus q and dimension n, the form the gates take.

Usage

switch_ct_to_qn(ctx, ksk, ct)

Arguments

ctx

A BinFHEContext.

ksk

An LWESwitchingKey, from get_switch_key() or bin_key_switch_gen().

ct

An LWECiphertext of modulus Q and dimension N.

Value

An LWECiphertext.


Threshold decryption convenience: lead + main + fusion in one call

Description

Performs a full n-of-n threshold decryption of ct given the ordered list of party secret keys. The first key in sks is used for multiparty_decrypt_lead(); the remaining keys for multiparty_decrypt_main(); the resulting partials are then fused with multiparty_decrypt_fusion().

Usage

threshold_decrypt(cc, sks, ct)

Arguments

cc

A CryptoContext

sks

A list of PrivateKey objects, lead first

ct

The Ciphertext to decrypt

Details

Use this when you have all secret keys in one place (testing, simulation, single-process demos). In a real distributed deployment each site holds only its own secret key and the partials travel over the network — that flow uses the lead / main / fusion functions directly.

Value

A Plaintext


Execute code with automatic cleanup of FHE state

Description

Clears eval keys and releases contexts on exit (even on error).

Usage

with_fhe_context(expr)

Arguments

expr

Expression to evaluate

Value

Result of expr