---
title: "BGV"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{BGV}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

```{r setup}
library(polynom)
library(HomomorphicEncryption)
```

Set some parameters.
```{r params}
d  =   4
n  =   2^d
p  =   (n/2)-1
t  =   p
q  = 868
pm = GenPolyMod(n)
```

Set a working seed for random numbers
```{r}
set.seed(123)
```

Create the secret key and the polynomials a and e, which will go into the public key
```{r}
# generate a secret key
s = GenSecretKey(n)

# generate a
a = GenA(n, q)

# generate the error
e = GenError(n)
```

Generate the public key.
```{r}
pk0 = GenPubKey0(a, s, e*p, pm, q)
pk1 = GenPubKey1(a)
```

Create a polynomial message
```{r}
# create a message
m = polynomial( coef=c(1, 1, 1) )
```

Create polynomials for the encryption
```{r}
# polynomials for encryption
e1 = GenError(n)
e2 = GenError(n)
u  = GenU(n)
```

Generate the ciphertext
```{r}
ct0 = pk0*u + p*e1 + m
ct0 = ct0 %% pm
ct0 = CoefMod(ct0, q)
  
ct1 = pk1*u + p*e2
ct1 = ct1 %% pm
ct1 = CoefMod(ct1, q)
```

Decrypt
```{r}
decrypt = (ct1 * s) + ct0
decrypt = decrypt %% pm
decrypt = CoefMod(decrypt, q)
decrypt = CoefMod(round(decrypt), p)
print(decrypt)
```
