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.
# generate a secret key
s = polynomial( sample.int(3, n, replace=TRUE)-2 )
print(s)
#> 1 + x + x^2 + x^4 + x^8 - x^9 - x^12 + x^14 - x^15
Create a (part of the public key)
# generate a
a = polynomial(sample.int(q, n, replace=TRUE))
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
Create the error term e
to be used to generate the
public key.
# generate the error
e = polynomial( coef=round(stats::rnorm(n, 0, n/3)) )
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 Part 1 of the Public Key.
pk1 = -(a*s + e)
pk1 = pk1 %% pm
pk1 = CoefMod(pk1, q)
print(pk1)
#> 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
Generate Part 2 of the Public Key (which is actually just equal to a).
Create a polynomial message
Create polynomials for the encryption of the message. Since e1 and e2 are constructed the same way as e, we don’t print them, we just print u.
# polynomials for encryption
e1 = polynomial( coef=round(stats::rnorm(n, 0, n/3)) )
e2 = polynomial( coef=round(stats::rnorm(n, 0, n/3)) )
u = polynomial( coef=sample.int(3, (n-1), replace=TRUE)-2 )
print(u)
#> x^3 - x^5 + x^9 + x^11 + x^13 - x^14
Generate Part 1 of the ciphertext version of the message.
ct1 = pk1 * u + e1 + floor(q/p) * m
ct1 = ct1 %% pm
ct1 = CoefMod(ct1, q)
print(ct1)
#> 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
Generate Part 2 of the ciphertext version of the message.
ct2 = pk2 * u + e2
ct2 = ct2 %% pm
ct2 = CoefMod(ct2, q)
print(ct2)
#> 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 = (ct2 * s) + ct1
decrypt = decrypt %% pm
decrypt = CoefMod(decrypt, q)
# rescale
decrypt = decrypt * p/q
Round (remove the error) then mod p