BGV ModSwitch

library(polynom)
library(HomomorphicEncryption)

Set some parameters.

d  =   4
n  =   2^d
p  =   (n/2)-1
t  =   p
q  = 868
pm = GenPolyMod(n)

Set a working seed for random numbers

set.seed(123)

Create the secret key and the polynomials a and e, which will go into the public key

# generate a secret key
s = GenSecretKey(n)

# generate a
a = GenA(n, q)

# generate the error
e = GenError(n)

Generate the public key.

pk0 = GenPubKey0(a, s, e*p, pm, q)
pk1 = GenPubKey1(a)

Generate the evaluation key (EvalKey, EK).

ek0 = GenEvalKey0(a, s, e)
ek1 = a

Create a polynomial message

# create a message
m1 = polynomial( coef=c(1, 1, 1) )
m2 = polynomial( coef=c(0, 1   ) )

Create polynomials for the encryption

# polynomials for encryption
e1 = GenError(n)
e2 = GenError(n)
u  = GenU(n)

Generate the ciphertext

m1_ct0 = pk0*u + p*e1 + m1
m1_ct0 = m1_ct0 %% pm
m1_ct0 = CoefMod(m1_ct0, q)
  
m1_ct1 = pk1*u + p*e2
m1_ct1 = m1_ct1 %% pm
m1_ct1 = CoefMod(m1_ct1, q)

m2_ct0 = pk0*u + p*e1 + m2
m2_ct0 = m2_ct0 %% pm
m2_ct0 = CoefMod(m2_ct0, q)
  
m2_ct1 = pk1*u + p*e2
m2_ct1 = m2_ct1 %% pm
m2_ct1 = CoefMod(m2_ct1, q)

EvalMult

multi_ct0 = m1_ct0 * m2_ct0
multi_ct0 = multi_ct0 %% pm
multi_ct0 = CoefMod(multi_ct0, q)
multi_ct0 = round(multi_ct0)

multi_ct1 = (m1_ct0 * m2_ct1 + m1_ct1 * m2_ct0)
multi_ct1 = multi_ct1 %% pm
multi_ct1 = CoefMod(multi_ct1, q)
multi_ct1 = round(multi_ct1)

multi_ct2 = (m1_ct1 * m2_ct1)
multi_ct2 = multi_ct2 %% pm
multi_ct2 = CoefMod(multi_ct2, q)
multi_ct2 = round(multi_ct2)

Relinearize:

ct0hat = CoefMod(multi_ct0 + ek0 * multi_ct2 %% pm, q)
ct1hat = CoefMod(multi_ct1 + ek1 * multi_ct2 %% pm, q)

Attemtp to modswitch (note at this point relinearization doesn’t even work yet)

q_prime = q - 1
ct0hat_prime = round(ct0hat * q_prime/q)
ct1hat_prime = round(ct1hat * q_prime/q)

Decrypt the multiple

decrypt = ct0hat_prime + ct1hat_prime * s
decrypt = decrypt %% pm
decrypt = CoefMod(decrypt, q_prime)
decrypt = decrypt * p/q_prime
decrypt = CoefMod(round(decrypt), p)
print(decrypt)
#> 2 + 6*x + 2*x^2 + 4*x^3 + 5*x^4 + 3*x^5 + 4*x^6 + 6*x^7 + 4*x^8 + 5*x^9 + x^10  
#> + x^11 + x^12 + 4*x^13 + 5*x^14 + 4*x^15