ckks

package
v6.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 14, 2024 License: Apache-2.0 Imports: 15 Imported by: 2

README

CKKS

The package CKKS is an RNS-accelerated version of the Homomorphic Encryption for Arithmetic of Approximate Numbers (HEAAN, a.k.a. CKKS) scheme originally proposed by Cheon, Kim, Kim and Song. The package supports two variants of the scheme: the standard one that encrypts vectors of complex numbers, and the conjugate-invariant one that encrypts vectors of real numbers, as proposed by Kim and Song.The RingType field of the Parameter struct controls which variant is instantiated:

For RingType: ring.Standard, the standard variant of CKKS is used. This requires that all moduli in the chain are congruent to 1 modulo 2N for N the ring degree. This variant supports packing of up to N/2 plaintext complex values into a single ciphertext.

For RingType: ring.ConjugateInvariant, the conjugate-invariant variant of CKKS is used. This requires that all moduli in the chain are congruent to 1 modulo 4N for N the ring degree. This variant supports packing of up to N plaintext real values into a single ciphertext.

Brief description of the Standard variant

This scheme can be used to do arithmetic over equation. The plaintext space and the ciphertext space share the same domain

,

with a power of 2.

The batch encoding of this scheme

.

maps an array of complex numbers to a polynomial with the property:

,

where represents a component-wise product, and represents a nega-cyclic convolution.

Security parameters

equation: the ring dimension, which defines the degree of the cyclotomic polynomial, and the number of coefficients of the plaintext/ciphertext polynomials; it should always be a power of two. This parameter has an impact on both security and performance (security increases with N and performance decreases with N). It should be chosen carefully to suit the intended use of the scheme.

equation: the ciphertext modulus. In Lattigo, it is chosen to be the product of a chain of small coprime moduli equation that verify equation in order to enable both the RNS and NTT representation. The used moduli equation are chosen to be of size 30 to 60 bits for the best performance. This parameter has an impact on both security and performance (for a fixed equation, a larger equation implies both lower security and lower performance). It is closely related to equation and should be carefully chosen to suit the intended use of the scheme.

equation: the variance used for the error polynomials. This parameter is closely tied to the security of the scheme (a larger equation implies higher security).

Other parameters

equation: the plaintext scale. Since complex numbers are encoded on polynomials with integer coefficients, the original values must be scaled during the encoding, before being rounded to the nearest integer. The equation parameter is the power of two by which the values are multiplied during the encoding. It has an impact on the precision of the output and on the amount of operations a fresh encryption can undergo before overflowing.

Choosing the right parameters for a given application

There are 3 application-dependent parameters:

  • LogN: it determines (a) how many values can be encoded (batched) at once (maximum N/2) in one plaintext, and (b) the maximum total modulus bit size (the product of all the moduli) for a given security parameter.
  • Modulichain: it determines how many consecutive scalar and non-scalar multiplications (the depth of the arithmetic circuit) can be evaluated before requiring decryption. Since Lattigo features an RNS implementation, this parameter requires careful fine-tuning depending on the application; i.e., the rescaling procedure can only rescale by one of the RNS modulus at a time, whose size has to be chosen when creating the CKKS context. Additionally, the individual size of each of the moduli also has an effect on the error introduced during the rescaling, since they cannot be powers of 2, so they should be chosen as NTT primes as close as possible to a power of 2 instead.
  • LogDefaultScale: it determines the scale of the plaintext, affecting both the precision and the maximum allowed depth for a given security parameter.

Configuring parameters for CKKS is very application dependent, requiring a prior analysis of the circuit to be executed under encryption. The following example illustrates how this parametrization can be done, showing that it is possible to come up with different parameter sets for a given circuit, each set having pros and cons.

Let us define the evaluation of an arbitrary smooth function f(x) on an array of ~4000 complex elements contained in a square of side 2 centered at the complex origin (with values ranging between -1-1i and 1+1i). We first need to find a good polynomial approximation for the given range. Lattigo provides an automatic Chebyshev approximation for any given polynomial degree, which can be used for this purpose (it is also possible to define a different polynomial approximation of lower degree with an acceptable error).

Let us assume that we find an approximation of degree 5, i.e., a + bx + cx^3 + dx^5. This function can be evaluated with 3 scalar multiplications, 3 additions and 3 non-scalar multiplications, consuming a total of 4 levels (one for the scalar multiplications and 3 for the non-scalar multiplications).

We then need to chose a scale for the plaintext, that will influence both the bit consumption for the rescaling, and the precision of the computation. If we choose a scale of 2^40, we need to consume at least 160 bits (4 levels) during the evaluation, and we still need some bits left to store the final result with an acceptable precision. Let us assume that the output of the approximation lies always in the square between -20-20i and 20+20i; then, the final modulus must be at least 5 bits larger than the final scale (to preserve the integer precision).

The following parameters will work for the posed example:

  • LogN = 13
  • Modulichain = [45, 40, 40, 40, 40], for a logQ <= 205
  • LogDefaultScale = 40

But it is also possible to use less levels to have ciphertexts of smaller size and, therefore, a faster evaluation, at the expense of less precision. This can be achieved by using a scale of 30 bits and squeezing two multiplications in a single level, while pre-computing the last scalar multiplication already in the plaintext. Instead of evaluating a + bx + cx^3 + dx^5, we pre-multiply the plaintext by d^(1/5) and evaluate a + b/(d^(1/5))x + c/(d^(3/5)) + x^5.

The following parameters are enough to evaluate this modified function:

  • LogN = 13
  • Modulichain = [35, 60, 60], for a logQ <= 155
  • LogDefaultScale = 30

To summarize, several parameter sets can be used to evaluate a given function, achieving different trade-offs for space and time versus precision.

Choosing secure parameters

The CKKS scheme supports the standard recommended parameters chosen to offer a security of 128 bits for a secret key with uniform ternary distribution equation, according to the Homomorphic Encryption Standards group (https://homomorphicencryption.org/standard/).

Each set of security parameters is defined by the tuple equation :

  • {12, 109, 3.2}
  • {13, 218, 3.2}
  • {14, 438, 3.2}
  • {15, 881, 3.2}

As mentioned, setting parameters for CKKS involves not only choosing this tuple, but also defining the actual moduli chain depending on the application at hand, which is why the provided default parameter sets have to be fine-tuned, preserving the values of the aforementioned tuples, in order to maintain the required security level of 128 bits. That is, Lattigo provides a set of default parameters for CKKS, including example moduli chains, ensuring 128 bit security. The user might want to choose different values in the moduli chain optimized for a specific application. As long as the total modulus is equal or below the above values for a given logN, the scheme will still provide a security of at least 128 bits against the current best known attacks.

Finally, it is worth noting that these security parameters are computed for fully entropic ternary keys (with probability distribution {1/3,1/3,1/3} for values {-1,0,1}). Lattigo uses this fully-entropic key configuration by default. It is possible, though, to generate keys with lower entropy, by modifying their distribution to {(1-p)/2, p, (1-p)/2}, for any p between 0 and 1, which for p>>1/3 can result in low Hamming weight keys (sparse keys). We recall that it has been shown that the security of sparse keys can be considerably lower than that of fully entropic keys, and the CKKS security parameters should be re-evaluated if sparse keys are used.

References

  1. Homomorphic Encryption for Arithmetic of Approximate Numbers (https://eprint.iacr.org/2016/421)
  2. A Full RNS Variant of Approximate Homomorphic Encryption (https://eprint.iacr.org/2018/931)
  3. Approximate Homomorphic Encryption over the Conjugate-invariant Ring (https://eprint.iacr.org/2018/952)
  4. Approximate Homomorphic Encryption with Reduced Approximation Error (https://eprint.iacr.org/2020/1118)
  5. On the precision loss in approximate homomorphic encryption (https://eprint.iacr.org/2022/162)

Documentation

Overview

Package ckks implements a RNS-accelerated version of the Homomorphic Encryption for Arithmetic for Approximate Numbers (HEAAN, a.k.a. CKKS) scheme. It provides approximate arithmetic over the complex numbers.package ckks

Index

Constants

View Source
const (
	NTTFlag = true
	PREC64  = PrecisionMode(0)
	PREC128 = PrecisionMode(1)
)
View Source
const GaloisGen uint64 = ring.GaloisGen

GaloisGen is an integer of order N/2 modulo M and that spans Z_M with the integer -1. The j-th ring automorphism takes the root zeta to zeta^(5j).

Variables

View Source
var (
	// ExampleParameters128BitLogN14LogQP438 is an example parameters set with logN=14, logQP=435
	// offering 128-bit of security.
	ExampleParameters128BitLogN14LogQP438 = ParametersLiteral{

		LogN: 14,

		Q: []uint64{
			0x80000000080001,
			0x2000000a0001,
			0x2000000e0001,
			0x2000001d0001,
			0x1fffffcf0001,
			0x1fffffc20001,
			0x200000440001,
		},

		LogDefaultScale: 45,

		P: []uint64{
			0x80000000130001,
			0x7fffffffe90001,
		},

		RingType: ring.Standard,

		Xs: rlwe.DefaultXs,

		Xe: rlwe.DefaultXe,
	}
)

Functions

func BigFloatToFixedPointCRT

func BigFloatToFixedPointCRT(r *ring.Ring, values []*big.Float, scale *big.Float, coeffs [][]uint64)

func Complex128ToFixedPointCRT

func Complex128ToFixedPointCRT(r *ring.Ring, values []complex128, scale float64, coeffs [][]uint64)

Complex128ToFixedPointCRT encodes a vector of complex128 on a CRT polynomial. The real part is put in a left N/2 coefficient and the imaginary in the right N/2 coefficients.

func ComplexArbitraryToFixedPointCRT

func ComplexArbitraryToFixedPointCRT(r *ring.Ring, values []*bignum.Complex, scale *big.Float, coeffs [][]uint64)

func Float64ToFixedPointCRT

func Float64ToFixedPointCRT(r *ring.Ring, values []float64, scale float64, coeffs [][]uint64)

Float64ToFixedPointCRT encodes a vector of floats on a CRT polynomial.

func GetRootsBigComplex

func GetRootsBigComplex(NthRoot int, prec uint) (roots []*bignum.Complex)

GetRootsBigComplex returns the roots e^{2*pi*i/m *j} for 0 <= j <= NthRoot with prec bits of precision.

func GetRootsComplex128

func GetRootsComplex128(NthRoot int) (roots []complex128)

GetRootsComplex128 returns the roots e^{2*pi*i/m *j} for 0 <= j <= NthRoot.

func NewCiphertext

func NewCiphertext(params Parameters, degree, level int) (ct *rlwe.Ciphertext)

NewCiphertext allocates a new rlwe.Ciphertext.

inputs:

  • params: an rlwe.ParameterProvider interface
  • degree: the degree of the ciphertext
  • level: the level of the Ciphertext

output: a newly allocated rlwe.Ciphertext of the specified degree and level.

func NewDecryptor

func NewDecryptor(params Parameters, key *rlwe.SecretKey) *rlwe.Decryptor

NewDecryptor instantiates a new rlwe.Decryptor.

inputs:

output: an rlwe.Decryptor instantiated with the provided key.

func NewEncryptor

func NewEncryptor(params Parameters, key rlwe.EncryptionKey) *rlwe.Encryptor

NewEncryptor instantiates a new rlwe.Encryptor.

inputs:

output: an rlwe.Encryptor instantiated with the provided key.

func NewKeyGenerator

func NewKeyGenerator(params Parameters) *rlwe.KeyGenerator

NewKeyGenerator instantiates a new rlwe.KeyGenerator.

inputs:

output: an rlwe.KeyGenerator.

func NewPlaintext

func NewPlaintext(params Parameters, level int) (pt *rlwe.Plaintext)

NewPlaintext allocates a new rlwe.Plaintext.

inputs:

output: a newly allocated rlwe.Plaintext at the specified level.

Note: the user can update the field MetaData to set a specific scaling factor, plaintext dimensions (if applicable) or encoding domain, before encoding values on the created plaintext.

func SingleFloat64ToFixedPointCRT

func SingleFloat64ToFixedPointCRT(r *ring.Ring, i int, value float64, scale float64, coeffs [][]uint64)

SingleFloat64ToFixedPointCRT encodes a single float64 on a CRT polynomialon in the i-th coefficient.

func SpecialFFTArbitrary

func SpecialFFTArbitrary(values []*bignum.Complex, N, M int, rotGroup []int, roots []*bignum.Complex)

SpecialFFTArbitrary evaluates the decoding matrix on a slice of ring.Complex values.

func SpecialFFTDouble

func SpecialFFTDouble(values []complex128, N, M int, rotGroup []int, roots []complex128)

SpecialFFTDouble performs the CKKS special FFT transform in place.

func SpecialFFTDoubleUL8

func SpecialFFTDoubleUL8(values []complex128, N, M int, rotGroup []int, roots []complex128)

SpecialFFTDoubleUL8 performs the CKKS special FFT transform in place with unrolled loops of size 8.

func SpecialIFFTArbitrary

func SpecialIFFTArbitrary(values []*bignum.Complex, N, M int, rotGroup []int, roots []*bignum.Complex)

SpecialIFFTArbitrary evaluates the encoding matrix on a slice of ring.Complex values.

func SpecialIFFTDouble

func SpecialIFFTDouble(values []complex128, N, M int, rotGroup []int, roots []complex128)

SpecialIFFTDouble performs the CKKS special inverse FFT transform in place.

func SpecialiFFTDoubleUnrolled8

func SpecialiFFTDoubleUnrolled8(values []complex128, N, M int, rotGroup []int, roots []complex128)

SpecialiFFTDoubleUnrolled8 performs the CKKS special inverse FFT transform in place with unrolled loops of size 8.

func StandardDeviation

func StandardDeviation(vec interface{}, scale rlwe.Scale) (std float64)

StandardDeviation computes the scaled standard deviation of the input vector.

func VerifyTestVectors

func VerifyTestVectors(params Parameters, encoder *Encoder, decryptor *rlwe.Decryptor, valuesWant, valuesHave interface{}, log2MinPrec int, logprec float64, printPrecisionStats bool, t *testing.T)

Types

type DomainSwitcher

type DomainSwitcher struct {
	// contains filtered or unexported fields
}

DomainSwitcher is a type for switching between the standard CKKS domain (which encrypts vectors of complex numbers) and the conjugate invariant variant of CKKS (which encrypts vectors of real numbers).

func NewDomainSwitcher

func NewDomainSwitcher(params Parameters, comlexToRealEvk, realToComplexEvk *rlwe.EvaluationKey) (DomainSwitcher, error)

NewDomainSwitcher instantiate a new DomainSwitcher type. It may be instantiated from parameters from either RingType. The method returns an error if the parameters cannot support the switching (e.g., the NTTs are undefined for either of the two ring types). The comlexToRealEvk and comlexToRealEvk EvaluationKeys can be generated using rlwe.KeyGenerator.GenEvaluationKeysForRingSwap.

func (DomainSwitcher) ComplexToReal

func (switcher DomainSwitcher) ComplexToReal(eval *Evaluator, ctIn, opOut *rlwe.Ciphertext) (err error)

ComplexToReal switches the provided ciphertext ctIn from the standard domain to the conjugate invariant domain and writes the result into opOut. Given ctInCKKS = enc(real(m) + imag(m)) in Z[X](X^N + 1), returns opOutCI = enc(real(m)) in Z[X+X^-1]/(X^N + 1) in compressed form (N/2 coefficients). The scale of the output ciphertext is twice the scale of the input one. Requires the ring degree of opOut to be half the ring degree of ctIn. The security is changed from Z[X]/(X^N+1) to Z[X]/(X^N/2+1). The method will return an error if the DomainSwitcher was not initialized with a the appropriate EvaluationKeys.

func (DomainSwitcher) RealToComplex

func (switcher DomainSwitcher) RealToComplex(eval *Evaluator, ctIn, opOut *rlwe.Ciphertext) (err error)

RealToComplex switches the provided ciphertext ctIn from the conjugate invariant domain to the standard domain and writes the result into opOut. Given ctInCI = enc(real(m)) in Z[X+X^-1]/(X^2N+1) in compressed form (N coefficients), returns opOutCKKS = enc(real(m) + imag(0)) in Z[X]/(X^2N+1). Requires the ring degree of opOut to be twice the ring degree of ctIn. The security is changed from Z[X]/(X^N+1) to Z[X]/(X^2N+1). The method will return an error if the DomainSwitcher was not initialized with a the appropriate EvaluationKeys.

type Encoder

type Encoder struct {
	// contains filtered or unexported fields
}

Encoder is a type that implements the encoding and decoding interface for the CKKS scheme. It provides methods to encode/decode []complex128/[]*bignum.Complex and []float64/[]*big.Float types into/from Plaintext types.

Two different encodings domains are provided:

  • Coefficients: The coefficients are directly embedded on the plaintext. This encoding only allows to encode []float64/[]*big.Float slices, but of size up to N (N being the ring degree) and does not preserve the point-wise multiplication. A ciphertext multiplication will result in a negacyclic polynomial convolution in the plaintext domain. This encoding does not provide native slot cyclic rotation. Other operations, like addition or constant multiplication, behave as usual.

  • Slots: The coefficients are first subjected to a special Fourier transform before being embedded in the plaintext by using Coeffs encoding. This encoding can embed []complex128/[]*bignum.Complex and []float64/[]*big.Float slices of size at most N/2 (N being the ring degree) and leverages the convolution property of the DFT to preserve point-wise complex multiplication in the plaintext domain, i.e. a ciphertext multiplication will result in an element-wise multiplication in the plaintext domain. It also enables cyclic rotations on plaintext slots. Other operations, like constant multiplication, behave as usual. It is considered the default encoding method for CKKS.

The figure bellow illustrates the relationship between these two encodings:

                                                    Z_Q[X]/(X^N+1)
	Coefficients: ---------------> Real^{N} ---------> Plaintext
                                      |
                                      |
	Slots: Complex^{N/2} -> iDFT -----┘

func NewEncoder

func NewEncoder(parameters Parameters, precision ...uint) (ecd *Encoder)

NewEncoder creates a new Encoder from the target parameters. Optional field `precision` can be given. If precision is empty or <= 53, then float64 and complex128 types will be used to perform the encoding. Else *big.Float and *bignum.Complex will be used.

func (Encoder) Decode

func (ecd Encoder) Decode(pt *rlwe.Plaintext, values interface{}) (err error)

Decode decodes the input plaintext on a new FloatSlice.

func (Encoder) DecodePublic

func (ecd Encoder) DecodePublic(pt *rlwe.Plaintext, values FloatSlice, logprec float64) (err error)

DecodePublic decodes the input plaintext on a FloatSlice. It adds, before the decoding step (i.e. in the Ring) noise that follows the given distribution parameters. If the underlying ringType is ring.ConjugateInvariant, the imaginary part (and its related error) are zero.

func (Encoder) Embed

func (ecd Encoder) Embed(values interface{}, metadata *rlwe.MetaData, polyOut interface{}) (err error)

Embed is a generic method to encode a FloatSlice on the target polyOut. This method it as the core of the slot encoding. Values are encoded according to the provided metadata. Accepted polyOut.(type) are ringqp.Poly and ring.Poly. The imaginary part will be discarded if ringType == ring.ConjugateInvariant.

func (Encoder) Encode

func (ecd Encoder) Encode(values interface{}, pt *rlwe.Plaintext) (err error)

Encode encodes a FloatSlice on the target plaintext. Encoding is done at the level and scale of the plaintext. Encoding domain is done according to the metadata of the plaintext. User must ensure that 1 <= len(values) <= 2^pt.LogMaxDimensions < 2^logN. The imaginary part will be discarded if ringType == ring.ConjugateInvariant.

func (Encoder) FFT

func (ecd Encoder) FFT(values FloatSlice, logN int) (err error)

FFT evaluates the special 2^{LogN}-th decoding discrete Fourier transform on FloatSlice.

func (Encoder) GetParameters added in v6.1.0

func (ecd Encoder) GetParameters() Parameters

func (Encoder) GetRLWEParameters

func (ecd Encoder) GetRLWEParameters() rlwe.Parameters

func (Encoder) IFFT

func (ecd Encoder) IFFT(values FloatSlice, logN int) (err error)

IFFT evaluates the special 2^{LogN}-th encoding discrete Fourier transform on FloatSlice.

func (Encoder) Prec

func (ecd Encoder) Prec() uint

Prec returns the precision in bits used by the target Encoder. A precision <= 53 will use float64, else *big.Float.

func (Encoder) ShallowCopy

func (ecd Encoder) ShallowCopy() *Encoder

ShallowCopy returns a lightweight copy of the target object that can be used concurrently with the original object.

type Evaluator

type Evaluator struct {
	*Encoder

	*rlwe.Evaluator
	// contains filtered or unexported fields
}

Evaluator is a struct that holds the necessary elements to execute the homomorphic operations between Ciphertexts and/or Plaintexts. It also holds a memory buffer used to store intermediate computations.

func NewEvaluator

func NewEvaluator(parameters Parameters, evk rlwe.EvaluationKeySet) *Evaluator

NewEvaluator creates a new Evaluator, that can be used to do homomorphic operations on the Ciphertexts and/or Plaintexts. It stores a memory buffer and Ciphertexts that will be used for intermediate values.

func (Evaluator) Add

func (eval Evaluator) Add(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)

Add adds op1 to op0 and returns the result in opOut. The following types are accepted for op1:

Passing an invalid type will return an error.

func (Evaluator) AddNew

func (eval Evaluator) AddNew(op0 *rlwe.Ciphertext, op1 rlwe.Operand) (opOut *rlwe.Ciphertext, err error)

AddNew adds op1 to op0 and returns the result in a newly created element opOut. The following types are accepted for op1:

Passing an invalid type will return an error.

func (Evaluator) ApplyEvaluationKeyNew

func (eval Evaluator) ApplyEvaluationKeyNew(op0 *rlwe.Ciphertext, evk *rlwe.EvaluationKey) (opOut *rlwe.Ciphertext, err error)

ApplyEvaluationKeyNew applies the rlwe.EvaluationKey on op0 and returns the result on a new ciphertext opOut.

func (Evaluator) Average

func (eval Evaluator) Average(ctIn *rlwe.Ciphertext, logBatchSize int, opOut *rlwe.Ciphertext) (err error)

Average returns the average of vectors of batchSize elements. The operation assumes that ctIn encrypts SlotCount/batchSize sub-vectors of size batchSize. It then replaces all values of those sub-vectors by the component-wise average between all the sub-vectors. Example for batchSize=4 and slots=8: [{a, b, c, d}, {e, f, g, h}] -> [0.5*{a+e, b+f, c+g, d+h}, 0.5*{a+e, b+f, c+g, d+h}] Operation requires log2(SlotCout/batchSize) rotations. Required rotation keys can be generated with RotationsForInnerSumLog(batchSize, SlotCount/batchSize).

func (Evaluator) BuffQ

func (eval Evaluator) BuffQ() [3]ring.Poly

BuffQ returns a pointer to the internal memory buffer buffQ.

func (Evaluator) Conjugate

func (eval Evaluator) Conjugate(op0 *rlwe.Ciphertext, opOut *rlwe.Ciphertext) (err error)

Conjugate conjugates op0 (which is equivalent to a row rotation) and returns the result in opOut. The method will return an error if the evaluator hasn't been given an evaluation key set with the appropriate GaloisKey.

func (Evaluator) ConjugateNew

func (eval Evaluator) ConjugateNew(op0 *rlwe.Ciphertext) (opOut *rlwe.Ciphertext, err error)

ConjugateNew conjugates op0 (which is equivalent to a row rotation) and returns the result in a newly created element. The method will return an error if the evaluator hasn't been given an evaluation key set with the appropriate GaloisKey.

func (Evaluator) DropLevel

func (eval Evaluator) DropLevel(op0 *rlwe.Ciphertext, levels int)

DropLevel reduces the level of op0 by levels and returns the result in op0. No rescaling is applied during this procedure.

func (Evaluator) DropLevelNew

func (eval Evaluator) DropLevelNew(op0 *rlwe.Ciphertext, levels int) (opOut *rlwe.Ciphertext)

DropLevelNew reduces the level of op0 by levels and returns the result in a newly created element. No rescaling is applied during this procedure.

func (Evaluator) GetParameters

func (eval Evaluator) GetParameters() *Parameters

GetParameters returns a pointer to the underlying ckks.Parameters.

func (Evaluator) GetRLWEParameters

func (eval Evaluator) GetRLWEParameters() *rlwe.Parameters

GetRLWEParameters returns a pointer to the underlying rlwe.Parameters.

func (Evaluator) Mul

func (eval Evaluator) Mul(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)

Mul multiplies op0 with op1 without relinearization and returns the result in opOut.

The following types are accepted for op1:

Passing an invalid type will return an error.

If op1.(type) == rlwe.ElementInterface[ring.Poly]:

  • The procedure will return an error if either op0 or op1 are have a degree higher than 1.
  • The procedure will return an error if opOut.Degree != op0.Degree + op1.Degree.

func (Evaluator) MulNew

func (eval Evaluator) MulNew(op0 *rlwe.Ciphertext, op1 rlwe.Operand) (opOut *rlwe.Ciphertext, err error)

MulNew multiplies op0 with op1 without relinearization and returns the result in a newly created element opOut.

op1.(type) can be

If op1.(type) == rlwe.ElementInterface[ring.Poly]:

  • The procedure will return an error if either op0.Degree or op1.Degree > 1.

func (Evaluator) MulRelin

func (eval Evaluator) MulRelin(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)

MulRelin multiplies op0 with op1 with relinearization and returns the result in opOut.

The following types are accepted for op1:

Passing an invalid type will return an error.

The procedure will return an error if either op0.Degree or op1.Degree > 1. The procedure will return an error if opOut.Degree != op0.Degree + op1.Degree. The procedure will return an error if the evaluator was not created with an relinearization key.

func (Evaluator) MulRelinNew

func (eval Evaluator) MulRelinNew(op0 *rlwe.Ciphertext, op1 rlwe.Operand) (opOut *rlwe.Ciphertext, err error)

MulRelinNew multiplies op0 with op1 with relinearization and returns the result in a newly created element.

The following types are accepted for op1:

Passing an invalid type will return an error.

The procedure will return an error if either op0.Degree or op1.Degree > 1. The procedure will return an error if the evaluator was not created with an relinearization key.

func (Evaluator) MulRelinThenAdd

func (eval Evaluator) MulRelinThenAdd(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)

MulRelinThenAdd multiplies op0 with op1 with relinearization and adds the result on opOut.

The following types are accepted for op1:

Passing an invalid type will return an error.

User must ensure that opOut.Scale <= op0.Scale * op1.Scale.

If opOut.Scale < op0.Scale * op1.Scale, then scales up opOut before adding the result.

The procedure will return an error if either op0.Degree or op1.Degree > 1. The procedure will return an error if opOut.Degree != op0.Degree + op1.Degree. The procedure will return an error if the evaluator was not created with an relinearization key. The procedure will return an error if opOut = op0 or op1.

func (Evaluator) MulThenAdd

func (eval Evaluator) MulThenAdd(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)

MulThenAdd evaluate opOut = opOut + op0 * op1.

The following types are accepted for op1:

Passing an invalid type will return an error.

If op1.(type) is complex128, float64, int, int64, uint64. *big.Float, *big.Int or *ring.Complex:

This function will not modify op0 but will multiply opOut by Q[min(op0.Level(), opOut.Level())] if:

  • op0.Scale == opOut.Scale
  • constant is not a Gaussian integer.

If op0.Scale == opOut.Scale, and constant is not a Gaussian integer, then the constant will be scaled by Q[min(op0.Level(), opOut.Level())] else if opOut.Scale > op0.Scale, the constant will be scaled by opOut.Scale/op0.Scale.

To correctly use this function, make sure that either op0.Scale == opOut.Scale or opOut.Scale = op0.Scale * Q[min(op0.Level(), opOut.Level())].

If op1.(type) is []complex128, []float64, []*big.Float or []*bignum.Complex:

  • If opOut.Scale == op0.Scale, op1 will be encoded and scaled by Q[min(op0.Level(), opOut.Level())]
  • If opOut.Scale > op0.Scale, op1 will be encoded ans scaled by opOut.Scale/op1.Scale.

Then the method will recurse with op1 given as rlwe.ElementInterface[ring.Poly].

If op1.(type) is rlwe.ElementInterface[ring.Poly], the multiplication is carried outwithout relinearization and:

This function will return an error if op0.Scale > opOut.Scale and user must ensure that opOut.Scale <= op0.Scale * op1.Scale. If opOut.Scale < op0.Scale * op1.Scale, then scales up opOut before adding the result. Additionally, the procedure will return an error if:

  • either op0 or op1 are have a degree higher than 1.
  • opOut.Degree != op0.Degree + op1.Degree.
  • opOut = op0 or op1.

func (Evaluator) RelinearizeNew

func (eval Evaluator) RelinearizeNew(op0 *rlwe.Ciphertext) (opOut *rlwe.Ciphertext, err error)

RelinearizeNew applies the relinearization procedure on op0 and returns the result in a newly created Ciphertext. The input Ciphertext must be of degree two.

func (Evaluator) Rescale

func (eval Evaluator) Rescale(op0, opOut *rlwe.Ciphertext) (err error)

Rescale divides op0 by the last prime of the moduli chain and repeats this procedure params.LevelsConsumedPerRescaling() times.

Returns an error if:

  • Either op0 or opOut MetaData are nil
  • The level of op0 is too low to enable a rescale

func (Evaluator) RescaleTo

func (eval Evaluator) RescaleTo(op0 *rlwe.Ciphertext, minScale rlwe.Scale, opOut *rlwe.Ciphertext) (err error)

RescaleTo divides op0 by the last prime in the moduli chain, and repeats this procedure (consuming one level each time) and stops if the scale reaches `minScale` or if it would go below `minscale/2`, and returns the result in opOut. Returns an error if: - minScale <= 0 - ct.Scale <= 0 - ct.Level() = 0

func (Evaluator) Rotate

func (eval Evaluator) Rotate(op0 *rlwe.Ciphertext, k int, opOut *rlwe.Ciphertext) (err error)

Rotate rotates the columns of op0 by k positions to the left and returns the result in opOut. The method will return an error if the evaluator hasn't been given an evaluation key set with the appropriate GaloisKey.

func (Evaluator) RotateHoisted

func (eval Evaluator) RotateHoisted(ctIn *rlwe.Ciphertext, rotations []int, opOut map[int]*rlwe.Ciphertext) (err error)

RotateHoisted takes an input Ciphertext and a list of rotations and populates a map of pre-allocated Ciphertexts, where each element of the map is the input Ciphertext rotation by one element of the list. It is much faster than sequential calls to Evaluator.Rotate.

func (Evaluator) RotateHoistedLazyNew

func (eval Evaluator) RotateHoistedLazyNew(level int, rotations []int, ct *rlwe.Ciphertext, c2DecompQP []ringqp.Poly) (cOut map[int]*rlwe.Element[ringqp.Poly], err error)

func (Evaluator) RotateHoistedNew

func (eval Evaluator) RotateHoistedNew(ctIn *rlwe.Ciphertext, rotations []int) (opOut map[int]*rlwe.Ciphertext, err error)

RotateHoistedNew takes an input Ciphertext and a list of rotations and returns a map of Ciphertext, where each element of the map is the input Ciphertext rotation by one element of the list. It is much faster than sequential calls to Evaluator.Rotate.

func (Evaluator) RotateNew

func (eval Evaluator) RotateNew(op0 *rlwe.Ciphertext, k int) (opOut *rlwe.Ciphertext, err error)

RotateNew rotates the columns of op0 by k positions to the left, and returns the result in a newly created element. The method will return an error if the evaluator hasn't been given an evaluation key set with the appropriate GaloisKey.

func (Evaluator) ScaleUp

func (eval Evaluator) ScaleUp(op0 *rlwe.Ciphertext, scale rlwe.Scale, opOut *rlwe.Ciphertext) (err error)

ScaleUp multiplies op0 by scale and sets its scale to its previous scale times scale returns the result in opOut.

func (Evaluator) ScaleUpNew

func (eval Evaluator) ScaleUpNew(op0 *rlwe.Ciphertext, scale rlwe.Scale) (opOut *rlwe.Ciphertext, err error)

ScaleUpNew multiplies op0 by scale and sets its scale to its previous scale times scale returns the result in opOut.

func (Evaluator) SetScale

func (eval Evaluator) SetScale(ct *rlwe.Ciphertext, scale rlwe.Scale) (err error)

SetScale sets the scale of the ciphertext to the input scale (consumes a level).

func (Evaluator) ShallowCopy

func (eval Evaluator) ShallowCopy() *Evaluator

ShallowCopy creates a shallow copy of this evaluator in which all the read-only data-structures are shared with the receiver and the temporary buffers are reallocated. The receiver and the returned Evaluators can be used concurrently.

func (Evaluator) Sub

func (eval Evaluator) Sub(op0 *rlwe.Ciphertext, op1 rlwe.Operand, opOut *rlwe.Ciphertext) (err error)

Sub subtracts op1 from op0 and returns the result in opOut. The following types are accepted for op1:

Passing an invalid type will return an error.

func (Evaluator) SubNew

func (eval Evaluator) SubNew(op0 *rlwe.Ciphertext, op1 rlwe.Operand) (opOut *rlwe.Ciphertext, err error)

SubNew subtracts op1 from op0 and returns the result in a newly created element opOut. The following types are accepted for op1:

Passing an invalid type will return an error.

func (Evaluator) TraceNew

func (eval Evaluator) TraceNew(ctIn *rlwe.Ciphertext, logSlots int) (opOut *rlwe.Ciphertext, err error)

TraceNew maps X -> sum((-1)^i * X^{i*n+1}) for 0 <= i < N and returns the result on a new ciphertext. For log(n) = logSlots.

func (Evaluator) WithKey

func (eval Evaluator) WithKey(evk rlwe.EvaluationKeySet) *Evaluator

WithKey creates a shallow copy of the receiver Evaluator for which the new EvaluationKey is evaluationKey and where the temporary buffers are shared. The receiver and the returned Evaluators cannot be used concurrently.

type Float

type Float interface {
	float64 | complex128 | *big.Float | *bignum.Complex
}

type FloatSlice

type FloatSlice interface {
}

FloatSlice is an empty interface whose goal is to indicate that the expected input should be []Float. See Float for information on the type constraint.

type Parameters

type Parameters struct {
	rlwe.Parameters
}

Parameters represents a parameter set for the CKKS cryptosystem. Its fields are private and immutable. See ParametersLiteral for user-specified parameters.

func NewParametersFromLiteral

func NewParametersFromLiteral(pl ParametersLiteral) (Parameters, error)

NewParametersFromLiteral instantiate a set of CKKS parameters from a ParametersLiteral specification. It returns the empty parameters Parameters{} and a non-nil error if the specified parameters are invalid.

If the LogSlots field is left unset, its value is set to LogN-1 for the Standard ring and to LogN for the conjugate-invariant ring.

See rlwe.NewParametersFromLiteral for default values of the other optional fields.

func (Parameters) EncodingPrecision

func (p Parameters) EncodingPrecision() (prec uint)

EncodingPrecision returns the encoding precision in bits of the plaintext values which is max(53, log2(DefaultScale)).

func (Parameters) Equal

func (p Parameters) Equal(other *Parameters) bool

Equal compares two sets of parameters for equality.

func (Parameters) GaloisElementForComplexConjugation

func (p Parameters) GaloisElementForComplexConjugation() uint64

GaloisElementForComplexConjugation returns the Galois element for generating the automorphism X -> X^{-1 mod NthRoot} mod (X^{N} + 1). This automorphism acts as a swapping the rows of the plaintext algebra when the plaintext is batched.

Example: Recall that batched plaintexts are 2xN/2 matrices of the form [m, conjugate(m)] (the conjugate is implicitly ignored) thus given the following plaintext matrix:

[a, b, c, d][conj(a), conj(b), conj(c), conj(d)]

the complex conjugation will return the following plaintext matrix:

[conj(a), conj(b), conj(c), conj(d)][a, b, c, d]

Note that when using the ConjugateInvariant variant of the scheme, the conjugate is dropped and this operation is not defined.

func (Parameters) GaloisElementForRotation

func (p Parameters) GaloisElementForRotation(k int) uint64

GaloisElementForRotation returns the Galois element for generating the automorphism phi(k): X -> X^{5^k mod 2N} mod (X^{N} + 1), which acts as a cyclic rotation by k position to the left on batched plaintexts.

Example: Recall that batched plaintexts are 2xN/2 matrices of the form [m, conjugate(m)] (the conjugate is implicitly ignored) thus given the following plaintext matrix:

[a, b, c, d][conj(a), conj(b), conj(c), conj(d)]

a rotation by k=3 will change the plaintext to:

[d, a, b, c][conj(d), conj(a), conj(b), conj(c)]

Providing a negative k will change direction of the cyclic rotation to the right.

Note that when using the ConjugateInvariant variant of the scheme, the conjugate is dropped and the matrix becomes an 1xN matrix.

func (Parameters) GaloisElementsForInnerSum

func (p Parameters) GaloisElementsForInnerSum(batch, n int) []uint64

GaloisElementsForInnerSum returns the list of Galois elements necessary to apply the method `InnerSum` operation with parameters batch and n.

func (Parameters) GaloisElementsForReplicate

func (p Parameters) GaloisElementsForReplicate(batch, n int) []uint64

GaloisElementsForReplicate returns the list of Galois elements necessary to perform the `Replicate` operation with parameters batch and n.

func (Parameters) GaloisElementsForTrace

func (p Parameters) GaloisElementsForTrace(logN int) []uint64

GaloisElementsForTrace returns the list of Galois elements required for the for the Trace operation. Trace maps X -> sum((-1)^i * X^{i*n+1}) for 2^{LogN} <= i < N.

func (Parameters) GetOptimalScalingFactor

func (p Parameters) GetOptimalScalingFactor(a, c rlwe.Scale, level int) (b rlwe.Scale)

GetOptimalScalingFactor returns a scaling factor b such that Rescale(a * b) = c

func (Parameters) GetRLWEParameters

func (p Parameters) GetRLWEParameters() *rlwe.Parameters

GetRLWEParameters returns a pointer to the underlying RLWE parameters.

func (Parameters) LevelsConsumedPerRescaling

func (p Parameters) LevelsConsumedPerRescaling() int

LevelsConsumedPerRescaling returns the number of levels (i.e. primes) consumed per rescaling. This value is 1 if the precision mode is PREC64 and is 2 if the precision mode is PREC128.

func (Parameters) LogDefaultScale

func (p Parameters) LogDefaultScale() int

LogDefaultScale returns the log2 of the default plaintext scaling factor (rounded to the nearest integer).

func (Parameters) LogMaxDimensions

func (p Parameters) LogMaxDimensions() ring.Dimensions

LogMaxDimensions returns the log2 of maximum dimension of the matrix that can be SIMD packed in a single plaintext polynomial.

func (Parameters) LogMaxSlots

func (p Parameters) LogMaxSlots() int

LogMaxSlots returns the total number of entries (slots) that a plaintext can store. This value is obtained by summing all log dimensions from LogDimensions.

func (Parameters) LogQLvl

func (p Parameters) LogQLvl(level int) int

LogQLvl returns the size of the modulus Q in bits at a specific level

func (Parameters) MarshalBinary

func (p Parameters) MarshalBinary() ([]byte, error)

MarshalBinary returns a []byte representation of the parameter set. This representation corresponds to the one returned by MarshalJSON.

func (Parameters) MarshalJSON

func (p Parameters) MarshalJSON() ([]byte, error)

MarshalJSON returns a JSON representation of this parameter set. See Marshal from the encoding/json package.

func (Parameters) MaxDepth

func (p Parameters) MaxDepth() int

MaxDepth returns the maximum depth enabled by the parameters, which is obtained as p.MaxLevel() / p.LevelsConsumedPerRescaling().

func (Parameters) MaxDimensions

func (p Parameters) MaxDimensions() ring.Dimensions

MaxDimensions returns the maximum dimension of the matrix that can be SIMD packed in a single plaintext polynomial.

func (Parameters) MaxLevel

func (p Parameters) MaxLevel() int

MaxLevel returns the maximum ciphertext level

func (Parameters) MaxSlots

func (p Parameters) MaxSlots() int

MaxSlots returns the total number of entries (slots) that a plaintext can store. This value is obtained by multiplying all dimensions from MaxDimensions.

func (Parameters) ParametersLiteral

func (p Parameters) ParametersLiteral() (pLit ParametersLiteral)

ParametersLiteral returns the ParametersLiteral of the target Parameters.

func (Parameters) PrecisionMode

func (p Parameters) PrecisionMode() PrecisionMode

PrecisionMode returns the precision mode of the parameters. This value can be ckks.PREC64 or ckks.PREC128.

func (Parameters) QLvl

func (p Parameters) QLvl(level int) *big.Int

QLvl returns the product of the moduli at the given level as a big.Int

func (Parameters) StandardParameters

func (p Parameters) StandardParameters() (pckks Parameters, err error)

StandardParameters returns the CKKS parameters corresponding to the receiver parameter set. If the receiver is already a standard parameter set (i.e., RingType==Standard), then the method returns the receiver.

func (*Parameters) UnmarshalBinary

func (p *Parameters) UnmarshalBinary(data []byte) (err error)

UnmarshalBinary decodes a []byte into a parameter set struct

func (*Parameters) UnmarshalJSON

func (p *Parameters) UnmarshalJSON(data []byte) (err error)

UnmarshalJSON reads a JSON representation of a parameter set into the receiver Parameter. See Unmarshal from the encoding/json package.

type ParametersLiteral

type ParametersLiteral struct {
	LogN            int
	LogNthRoot      int
	Q               []uint64
	P               []uint64
	LogQ            []int `json:",omitempty"`
	LogP            []int `json:",omitempty"`
	Xe              ring.DistributionParameters
	Xs              ring.DistributionParameters
	RingType        ring.Type
	LogDefaultScale int
}

ParametersLiteral is a literal representation of CKKS parameters. It has public fields and is used to express unchecked user-defined parameters literally into Go programs. The NewParametersFromLiteral function is used to generate the actual checked parameters from the literal representation.

Users must set the polynomial degree (in log_2, LogN) and the coefficient modulus, by either setting the Q and P fields to the desired moduli chain, or by setting the LogQ and LogP fields to the desired moduli sizes (in log_2). Users must also specify a default initial scale for the plaintexts.

Optionally, users may specify the error variance (Sigma), the secrets' density (H), the ring type (RingType) and the number of slots (in log_2, LogSlots). If left unset, standard default values for these field are substituted at parameter creation (see NewParametersFromLiteral).

func (ParametersLiteral) GetRLWEParametersLiteral

func (p ParametersLiteral) GetRLWEParametersLiteral() rlwe.ParametersLiteral

GetRLWEParametersLiteral returns the rlwe.ParametersLiteral from the target ckks.ParameterLiteral.

func (*ParametersLiteral) UnmarshalJSON

func (p *ParametersLiteral) UnmarshalJSON(b []byte) (err error)

type PrecisionMode

type PrecisionMode int

PrecisionMode is a variable that defines how many primes (one per machine word) are required to store initial message values. This also sets how many primes are consumed per rescaling.

There are currently two modes supported:

  • PREC64 (one 64-bit word)
  • PREC128 (two 64-bit words)

PREC64 is the default mode and supports reference plaintext scaling factors of up to 2^{64}, while PREC128 scaling factors of up to 2^{128}.

The PrecisionMode is chosen automatically based on the provided initial `LogDefaultScale` value provided by the user.

type PrecisionStats

type PrecisionStats struct {
	MINLog2Prec Stats
	MAXLog2Prec Stats
	AVGLog2Prec Stats
	MEDLog2Prec Stats
	STDLog2Prec Stats

	MINLog2Err Stats
	MAXLog2Err Stats
	AVGLog2Err Stats
	MEDLog2Err Stats
	STDLog2Err Stats

	Log2Scale float64

	RealDist, ImagDist, L2Dist []struct {
		Prec  float64
		Count int
	}
	// contains filtered or unexported fields
}

PrecisionStats is a struct storing statistic about the precision of a CKKS plaintext

func GetPrecisionStats

func GetPrecisionStats(params Parameters, encoder *Encoder, decryptor *rlwe.Decryptor, want, have interface{}, logprec float64, computeDCF bool) (prec PrecisionStats)

GetPrecisionStats generates a PrecisionStats struct from the reference values and the decrypted values vWant.(type) must be either []complex128 or []float64 element.(type) must be either *Plaintext, *Ciphertext, []complex128 or []float64. If not *Ciphertext, then decryptor can be nil.

func (PrecisionStats) String

func (prec PrecisionStats) String() string

type Stats

type Stats struct {
	Real, Imag, L2 float64
}

Stats is a struct storing the real, imaginary and L2 norm (modulus) about the precision of a complex value.

type TestContext

type TestContext struct {
	Params Parameters
	Ecd    *Encoder

	Prng sampling.PRNG

	Kgen *rlwe.KeyGenerator
	Sk   *rlwe.SecretKey
	Pk   *rlwe.PublicKey

	Enc *rlwe.Encryptor
	Dec *rlwe.Decryptor

	Evl *Evaluator
}

func NewTestContext

func NewTestContext(params ParametersLiteral) *TestContext

func (*TestContext) NewTestVector

func (tc *TestContext) NewTestVector(a, b complex128) (values []*bignum.Complex, pt *rlwe.Plaintext, ct *rlwe.Ciphertext)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL