Load libraries that will be used.
Set some parameters.
Set a working seed for random numbers
Here we create the polynomial modulo.
Create the secret key and the polynomials a and e, which will go into the public key
# generate a secret key
s = GenSecretKey(n)
print(s)
#> 1 + x + x^2 + x^4 + x^8 - x^9 - x^12 + x^14 - x^15
# generate a
a = GenA(n, q)
print(a)
#> 91 + 348*x + 649*x^2 + 355*x^3 + 840*x^4 + 26*x^5 + 519*x^6 + 426*x^7 + 649*x^8
#> + 766*x^9 + 211*x^10 + 590*x^11 + 593*x^12 + 555*x^13 + 871*x^14 + 373*x^15
Generate the error for the public key.
e = GenError(n)
print(e)
#> -4 - x - 2*x^2 - 6*x^3 + 6*x^5 - x^6 - 6*x^7 - 4*x^8 + 4*x^9 - 2*x^10 - 7*x^11
#> - 3*x^12 - x^13 + 5*x^14 - x^15
Generate the public key.
pk0 = GenPubKey0(a, s, e, pm, q)
print(pk0)
#> 560 + 287*x + 70*x^2 + 788*x^3 + 534*x^4 + 150*x^5 + 43*x^6 + 331*x^7 + 328*x^8
#> + 318*x^9 + 184*x^10 + 519*x^11 + 504*x^12 + 783*x^13 + 79*x^14 + 425*x^15
Create a polynomial message
Create polynomials for the encryption
# polynomials for encryption
e1 = GenError(n)
e2 = GenError(n)
u = GenU(n)
print(u)
#> x^3 - x^5 + x^9 + x^11 + x^13 - x^14
Generate the ciphertext.
ct0 = EncryptPoly0(m, pk0, u, e1, p, pm, q)
print(ct0)
#> 157 + 787*x + 337*x^2 + 236*x^3 + 454*x^4 + 575*x^5 + 87*x^6 + 14*x^7 + 448*x^8
#> + 640*x^10 + 747*x^11 + 711*x^12 + 564*x^13 + 866*x^14 + 678*x^15
ct1 = EncryptPoly1( pk1, u, e2, pm, q)
print(ct1)
#> 760 + 698*x + 679*x^2 + 477*x^3 + 329*x^4 + 414*x^5 + 487*x^6 + 165*x^7 +
#> 111*x^8 + 642*x^9 + 409*x^10 + 565*x^11 + 660*x^12 + 644*x^13 + 469*x^14 +
#> 297*x^15
Decrypt
decrypt = (ct1 * s) + ct0
decrypt = decrypt %% pm
decrypt = CoefMod(decrypt, q)
# rescale
decrypt = decrypt * p/q
Round (remove the error) then mod p
Which is indeed the message that we first encrypted.
Next, look at the vignette BFV-2 which does the exact same process, but unpacks all the functions used here into basic mathematical operations.