From 00954da5fe9123f4df398568267c07f1273eb712 Mon Sep 17 00:00:00 2001 From: Pavol Rusnak Date: Mon, 4 May 2015 19:53:06 +0200 Subject: [PATCH] fix /dev/urandom problem --- rand.c | 22 ++++++++++++---------- rand.h | 1 - test-openssl.c | 1 - tests.c | 1 - 4 files changed, 12 insertions(+), 13 deletions(-) diff --git a/rand.c b/rand.c index eb74ae45a..6bb72c35d 100644 --- a/rand.c +++ b/rand.c @@ -26,17 +26,13 @@ #include "rand.h" -static FILE *f; - -void init_rand(void) -{ - f = fopen("/dev/urandom", "r"); -} +static FILE *frand = NULL; int finalize_rand(void) { - int err = fclose(f); - f = NULL; + if (!frand) return 0; + int err = fclose(frand); + frand = NULL; return err; } @@ -44,7 +40,10 @@ uint32_t random32(void) { uint32_t r; size_t len = sizeof(r); - size_t len_read = fread(&r, 1, len, f); + if (!frand) { + frand = fopen("/dev/urandom", "r"); + } + size_t len_read = fread(&r, 1, len, frand); (void)len_read; assert(len_read == len); return r; @@ -59,7 +58,10 @@ uint32_t random_uniform(uint32_t n) void random_buffer(uint8_t *buf, size_t len) { - size_t len_read = fread(buf, 1, len, f); + if (!frand) { + frand = fopen("/dev/urandom", "r"); + } + size_t len_read = fread(buf, 1, len, frand); (void)len_read; assert(len_read == len); } diff --git a/rand.h b/rand.h index 8d8160887..3c9655999 100644 --- a/rand.h +++ b/rand.h @@ -27,7 +27,6 @@ #include #include -void init_rand(void); int finalize_rand(void); uint32_t random32(void); uint32_t random_uniform(uint32_t n); diff --git a/test-openssl.c b/test-openssl.c index ccef802ce..7103260fe 100644 --- a/test-openssl.c +++ b/test-openssl.c @@ -38,7 +38,6 @@ int main(int argc, char *argv[]) EC_GROUP *ecgroup; int cnt = 0; - init_rand(); ecgroup = EC_GROUP_new_by_curve_name(NID_secp256k1); unsigned long max_iterations = -1; diff --git a/tests.c b/tests.c index 94c9449e6..fc797ee1d 100644 --- a/tests.c +++ b/tests.c @@ -1442,7 +1442,6 @@ Suite *test_suite(void) int main(void) { int number_failed; - init_rand(); // needed for scalar_multiply() Suite *s = test_suite(); SRunner *sr = srunner_create(s); srunner_run_all(sr, CK_VERBOSE);