Skip to content

Instantly share code, notes, and snippets.

@harieamjari
Last active March 1, 2023 16:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save harieamjari/d43de9bdfb480291b6b7b81b5e102436 to your computer and use it in GitHub Desktop.
Save harieamjari/d43de9bdfb480291b6b7b81b5e102436 to your computer and use it in GitHub Desktop.
Minimal ring-lwe encryption
#include <math.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define M 256
#define P 2048
/* Possible 256 values from 0 to 255*/
#define V 256
typedef struct vec3D_t vec3D_t;
struct vec3D_t {
int x, y, z;
};
typedef struct pkey_t pkey_t;
struct pkey_t {
int x, y, z, s;
};
int mod(int a, int b){
int ret = 0;
if (a > 0) return a%b;
ret = a;
while (ret < 0)
ret += b;
return ret;
}
int stepfunc(int x) {
// if (x > ((P/V)-1))
// return 1;
// return 0;
return x / ((P / V) - 1);
}
pkey_t encrypt(int msg, pkey_t *pkey, int n) {
pkey_t ret;
/* randomly pick three vectors */
pkey_t v0 = pkey[rand() % n], v1 = pkey[rand() % n], v2 = pkey[rand() % n];
// pkey_t v0 = pkey[0], v1 = {0}, v2 = {0}, v3 = {0};
ret.x = (v0.x + v1.x + v2.x) % P;
ret.y = (v0.y + v1.y + v2.y) % P;
ret.z = (v0.z + v1.z + v2.z) % P;
ret.s = ((v0.s + v1.s + v2.s) + msg * ((P / V) - 1)) % P;
printf("encrypted %d as u=%d v=%d,%d,%d\n", msg, ret.s, ret.x, ret.y, ret.z);
return ret;
}
int decrypt(pkey_t msg, vec3D_t skey) {
int sol = (msg.x * skey.x + msg.y * skey.y + msg.z * skey.z) % P;
int ret = stepfunc(mod(msg.s - sol, P));
printf("decrypted %d from u=%d v=%d,%d,%d\n", ret, msg.s, msg.x, msg.y,
msg.z);
return ret;
};
int main() {
srand(time(NULL));
vec3D_t skey = (vec3D_t){1091, 1203, 792};
pkey_t pkey[M] = {0};
printf("skey: %d %d %d\n", skey.x, skey.y, skey.z);
for (int i = 0; i < M; i++) {
pkey[i].x = rand() % P;
pkey[i].y = rand() % P;
pkey[i].z = rand() % P;
pkey[i].s =
((pkey[i].x * skey.x + pkey[i].y * skey.y + pkey[i].z * skey.z));
/* introduce cute noises */
pkey[i].s += ((rand() % 3));
pkey[i].s %= P;
printf("%dx %dy %dz = %d\n", pkey[i].x, pkey[i].y, pkey[i].z, pkey[i].s);
}
for (int i = 0; i < V; i++){
int msg = i;
int testv = decrypt(encrypt(msg, pkey, M), skey);
printf("-----------\n");
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment