diff --git a/src/poly.c b/src/poly.c index 18ca829..d6efb4c 100644 --- a/src/poly.c +++ b/src/poly.c @@ -19,8 +19,10 @@ * MA 02110-1301 USA */ +#include "context.h" #include "err.h" +#include #include #include #include @@ -75,6 +77,55 @@ void init_polynom_size(pb_poly *new_poly, mp_int *chara, size_t size) } } +/** + * Initializes and builds a polynomial with the + * coefficient values of c[] of size len within NTRU + * context ctx and returns a newly allocated polynomial + * pointer. + * + * @param c array of polynomial coefficients, can be NULL + * @param len size of the coefficient array, can be 0 + * @param ctx NTRU context + * @return newly allocated polynomial pointer, must be freed + * with delete_polynom() + */ +pb_poly *build_polynom(int const * const c, + const size_t len, + ntru_context *ctx) +{ + pb_poly *new_poly; + mp_int chara; + + new_poly = malloc(sizeof(*new_poly)); + init_integer(&chara); + init_polynom_size(new_poly, &chara, len); + mp_clear(&chara); + + /* fill the polynom if c is not NULL */ + if (c) { + for (unsigned int i = 0; i < len; i++) { + bool sign = false; + unsigned long unsigned_c; + + if (c[i] < 0) { + unsigned_c = 0 - c[i]; + sign = true; + } else { + unsigned_c = c[i]; + } + + mp_set_int(&(new_poly->terms[i]), unsigned_c); + + if (sign == true) + new_poly->terms[i].sign = 1; + } + new_poly->used = len; + pb_clamp(new_poly); + } + + return new_poly; +} + /** * This deletes the internal structure of a polynomial, * and frees the pointer. Don't call this on stack variables, diff --git a/src/poly.h b/src/poly.h index 7b534ba..37cf639 100644 --- a/src/poly.h +++ b/src/poly.h @@ -23,6 +23,8 @@ #ifndef NTRU_POLY_H #define NTRU_POLY_H +#include "context.h" + #include #include @@ -33,6 +35,10 @@ void init_polynom(pb_poly *new_poly, mp_int *chara); void init_polynom_size(pb_poly *new_poly, mp_int *chara, size_t size); +pb_poly *build_polynom(int const * const c, + const size_t len, + ntru_context *ctx); + void delete_polynom(pb_poly *new_poly); void draw_polynom(pb_poly * const poly);