libtc  20160415
Threshold Cryptography functions library
poly.c
Go to the documentation of this file.
1 #include <assert.h>
2 #include <gmp.h>
3 #include <stdlib.h>
4 
5 #include "mathutils.h"
6 
9 poly_t * create_random_poly(mpz_t d, size_t size, mpz_t m) {
10  assert(mpz_sgn(m) > 0);
11  poly_t * poly = malloc(sizeof(*poly));
12 
13  int bit_len = mpz_sizeinbase(m, 2) - 1;
14 
15  poly->size = size;
16  mpz_t * coeff = malloc(size * sizeof(*coeff));
17 
18  mpz_init_set(coeff[0], d);
19  for (int i = 1; i < size; i++) {
20  mpz_init(coeff[i]);
21  random_dev(coeff[i], bit_len);
22  mpz_mod(coeff[i], coeff[i], m);
23  }
24  poly->coeff = coeff;
25 
26  assert(mpz_cmp(poly->coeff[0], d) == 0);
27  #ifndef NDEBUG
28  for (int i=1; i < size; i++){
29  assert(mpz_cmp(poly->coeff[i], m) < 0);
30  }
31  #endif
32  return poly;
33 }
34 
36  int i;
37  mpz_t * coeff = poly->coeff;
38 
39  for(i=0; i<poly->size; i++) {
40  mpz_clear(coeff[i]);
41  }
42  free(coeff);
43 
44  poly->coeff = NULL; // To force segfaults...
45  free(poly);
46 }
47 
48 /* Horner's method */
49 void poly_eval(mpz_t rop, poly_t * poly, mpz_t x) {
50  assert(poly != NULL);
51  mpz_t * coeff = poly->coeff;
52  int size = poly->size;
53 
54  mpz_t y;
55 
56  /* y = 0 */
57  mpz_init(y);
58  for (int k=size - 1; k >= 0; k--) {
59  /* y = a_k + x*y */
60  mpz_mul(y, y, x);
61  mpz_add(y, y, coeff[k]);
62  }
63 
64  mpz_set(rop, y);
65 
66  mpz_clear(y);
67 
68 }
69 
70 void poly_eval_ui(mpz_t rop, poly_t * poly, unsigned long op) {
71  mpz_t x;
72  mpz_init_set_ui(x, op);
73  poly_eval(rop, poly, x);
74  mpz_clear(x);
75 }
76 
77 
void random_dev(mpz_t rop, int bit_len)
Definition: random.c:8
int size
Definition: mathutils.h:13
mpz_t * coeff
Definition: mathutils.h:12
void poly_eval(mpz_t rop, poly_t *poly, mpz_t x)
Definition: poly.c:49
void clear_poly(poly_t *poly)
Definition: poly.c:35
Definition: mathutils.h:11
poly_t * create_random_poly(mpz_t d, size_t size, mpz_t m)
Definition: poly.c:9
void poly_eval_ui(mpz_t rop, poly_t *poly, unsigned long op)
Definition: poly.c:70