{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "14b9392e-bb4a-4335-a51d-4db27ab4bfee",
   "metadata": {},
   "outputs": [],
   "source": [
    "import pqlattice as pq\n",
    "import numpy as np"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "f48a3572-2a96-4bc5-a867-294b55923389",
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 512\n",
    "m = 1024\n",
    "q = 3329\n",
    "sigma = 3.0\n",
    "\n",
    "secret_dist = \"ternary\""
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "id": "ecd4d4be-d75c-492f-bcfe-3647fc9e5123",
   "metadata": {},
   "outputs": [],
   "source": [
    "lwe = pq.random.LWE(n, q, sigma, secret_dist, 80)\n",
    "secret = lwe.secret\n",
    "A, b = lwe.sample_matrix(m)\n",
    "\n",
    "public_key = A, b\n",
    "secret_key = secret"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "id": "34705d5a-3365-4784-8836-c4c3b077cf6e",
   "metadata": {},
   "outputs": [],
   "source": [
    "M = 1\n",
    "U = pq.random.distribution.Uniform(0, 1)\n",
    "r = U.sample_vector(m)\n",
    "u = pq.integer.mod(r @ public_key[0], q)\n",
    "vp = pq.integer.mod(np.dot(b, r), q)\n",
    "v = pq.integer.mod(vp + M * (q // 2), q)\n",
    "\n",
    "encrypted_msg = (u, v)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "id": "f7fe17fb-c423-44d5-83c0-cfcd4dba9ed2",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n"
     ]
    }
   ],
   "source": [
    "u, v = encrypted_msg\n",
    "noisy_m = pq.integer.mod(v - np.dot(secret, u), q)\n",
    "dist_0 = min(noisy_m, q - noisy_m)\n",
    "dist_1 = abs(noisy_m - (q // 2))\n",
    "\n",
    "encrypted_msg = 0 if dist_0 < dist_1 else 1\n",
    "print(encrypted_msg)"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.12"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
