libtc  20160415
Threshold Cryptography functions library
random.c
Go to the documentation of this file.
1 #include <assert.h>
2 #include <gmp.h>
3 #include <stdio.h>
4 #include <stdlib.h>
5 
6 #include "mathutils.h"
7 
8 void random_dev(mpz_t rop, int bit_len) {
9  assert(bit_len > 0);
10  int byte_size = bit_len / 8;
11  void * buffer = malloc(byte_size);
12 
13  FILE * dev = fopen("/dev/urandom", "r");
14  int read = fread(buffer, 1, byte_size, dev);
15  while(read < byte_size) {
16  read += fread(buffer + read, 1, byte_size - read, dev);
17  }
18  fclose(dev);
19 
20  mpz_import(rop, byte_size, 1, 1, 0, 0, buffer);
21  free(buffer);
22 
23  assert(mpz_sizeinbase(rop, 2) <= bit_len);
24 }
25 
26 void random_prime(mpz_t rop, int bit_len, random_fn random) {
27  assert(bit_len > 0 && random != NULL);
28  mpz_t r;
29  mpz_init(r);
30 
31  int size;
32  do {
33  random(r, bit_len);
34  mpz_nextprime(rop, r);
35  size = mpz_sizeinbase(rop, 2);
36  } while (size > bit_len);
37 
38  mpz_clear(r);
39  assert(mpz_sizeinbase(rop, 2) <= bit_len && mpz_probab_prime_p(rop, 25));
40 }
void random_prime(mpz_t rop, int bit_len, random_fn random)
Definition: random.c:26
void random_dev(mpz_t rop, int bit_len)
Definition: random.c:8
void(* random_fn)(mpz_t rop, int bit_len)
Definition: mathutils.h:6