From 71b8f4cbeb80a298e59e058f00db5b6e191909b4 Mon Sep 17 00:00:00 2001 From: Malte Date: Thu, 17 Apr 2014 18:26:18 +0200 Subject: [PATCH] Added static mp_digit get_rnd_int_small(int *sign) but it takes about ~40minutes to generate a x^500 polynom with /dev/random. --- src/Makefile | 2 +- src/rand.c | 48 +++++++++++++++++++++++++++++++++++++++++++----- 2 files changed, 44 insertions(+), 6 deletions(-) diff --git a/src/Makefile b/src/Makefile index 95b5320..fd3ce31 100644 --- a/src/Makefile +++ b/src/Makefile @@ -57,7 +57,7 @@ endif %.o: %.c $(CC) -fPIC $(CFLAGS) $(CPPFLAGS) $(INCS) -c $*.c -all: libpqc.a libpqc.so +all: libpqc.a libpqc.so main # test: $(CUNIT_OBJS) $(PQC_LIBS) diff --git a/src/rand.c b/src/rand.c index d698164..0f88a85 100644 --- a/src/rand.c +++ b/src/rand.c @@ -37,7 +37,45 @@ * static declarations */ static mp_digit get_urnd_int_small(int *sign); +static mp_digit get_rnd_int_small(int *sign); +/** + * Gets randomly a small integer + * from the set {-1, 0, 1} using /dev/random. + * + * @param sign stores the signness [out] + * @return random small integer + */ +static mp_digit get_rnd_int_small(int *sign) +{ + int random_data; + mp_digit random_int; + size_t randomDataLen = 0; + random_data = open("/dev/random", O_RDONLY); + + while (randomDataLen < sizeof(random_int)) { + ssize_t result = read(random_data, + ((char*) &random_int) + randomDataLen, + (sizeof(random_int)) - randomDataLen); + if (result < 0) { + NTRU_ABORT("Unable to read /dev/random"); + } + randomDataLen += result; + } + close(random_data); + + random_int = random_int % 3; + + if (random_int == 1) { + *sign = 0; + } else if (random_int == 2) { + random_int = 1; + *sign = 1; + } else { + *sign = 0; + } + return random_int; +} /** * Gets randomly a small integer @@ -57,14 +95,14 @@ static mp_digit get_urnd_int_small(int *sign) NTRU_ABORT("Unable to read /dev/urandom"); close(random_data); - if ((random_int % 2) == 0) { - random_int = 0; + random_int = random_int % 3; + + if (random_int == 1) { *sign = 0; - } else if (random_int % 3) { + } else if (random_int == 2) { random_int = 1; *sign = 1; } else { - random_int = 1; *sign = 0; } @@ -90,7 +128,7 @@ pb_poly *ntru_get_urnd_poly_small(ntru_context *ctx) int sign; int c = get_urnd_int_small(&sign); - mp_set(&(poly->terms[i]), (mp_digit)c); + mp_set(&(poly->terms[i]), (mp_digit) c); if (sign == 1) poly->terms[i].sign = 1;