From: bg Date: Sun, 29 Jun 2014 20:00:17 +0000 (+0200) Subject: first publication of bigint2-dev X-Git-Url: https://git.cryptolib.org/?a=commitdiff_plain;h=cda2e9d578a68a57f3bd95c3ddbc5db78c7e3b36;p=avr-crypto-lib.git first publication of bigint2-dev --- diff --git a/bigint2/bigint2.c b/bigint2/bigint2.c new file mode 100644 index 0000000..449070b --- /dev/null +++ b/bigint2/bigint2.c @@ -0,0 +1,956 @@ +/* + * bigint2.c + * + * Created on: 09.04.2014 + * Author: bg + */ + +#include +#include +#include +#include + +#define CHECKS 1 + +#define E_PARAM -1; +#define E_OOM -2; +#define E_VALUE -3; + + +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +#define MIN(a,b) ((a) < (b) ? (a) : (b)) + +void *(*int_realloc)(void *ptr, size_t size); +void (*int_free)(void *ptr); + +/** + * \brief used to check if bigint is large enough + * Checks if the memory of a is large enough to hold min_size + * words, and if this is not the case tries to increase the allocated memory + * amount (conserving the memory content). + * If the allocated memory insufficient and the buffer could not be enlarged + * E_OOM is returned, otherwise 0 is returned. + */ +static +int check_size(bigint_t *a, bigint_length_t min_size) { + bigint_word_t *tmp; + if (a->allocated_W >= min_size) { + return 0; + } + tmp = int_realloc(a->wordv, min_size * sizeof(bigint_word_t)); + if (!tmp) { + return E_OOM; + } + a->wordv = tmp; + a->allocated_W = min_size; + return 0; +} + +int bigint_copy(bigint_t *dest, const bigint_t *a) { + int r; + if (dest == a) { + return 0; + } + r = check_size(dest, a->length_W); + if (r) { + return r; + } + dest->info = a->info; + dest->length_W = a->length_W; + memcpy(dest->wordv, a->wordv, a->length_W * sizeof(bigint_word_t)); + + return 0; +} + +int bigint_free(bigint_t *a) { + if(a->allocated_W) { + int_free(a->wordv); + } + memset(a, 0, sizeof(bigint_t)); + return 0; +} + +/** + * \brief dest = |a| + |b| + * Adds the bigints a and b and stores the result in dest. + * Signs are ignored. + */ +int bigint_add_u(bigint_t *dest, const bigint_t *a, const bigint_t *b) { + bigint_word_t t, c1, c2, c = 0; + bigint_length_t i, j; + int r; +#if CHECKS + if (!dest || !a || !b) { + return E_PARAM; + } +#endif +#if CHECKS + if ((r = check_size(dest, a->length_W))) { + return r; + } +#endif + j = MIN(a->length_W, b->length_W); + for (i = 0; i < j; ++i) { + t = a->wordv[i] + b->wordv[i]; + c1 = t < a->wordv[i]; + dest->wordv[i] = t + c; + c2 = dest->wordv[i] < t; + c = c1 | c2; + } + for (; i < a->length_W; ++i) { + t = a->wordv[i]; + dest->wordv[i] = t + c; + c = dest->wordv[i] < t; + } + dest->length_W = i; + return 0; +} + +/** UNSAFE!!! + * \brief dest = |a| + |b| + * Adds the bigints a and b and stores the result in dest. + * Signs are ignored. + */ +int bigint_add_auto_u(bigint_t *dest, const bigint_t *a, const bigint_t *b) { + bigint_word_t t, c1, c2, c = 0; + bigint_length_t i, j; + int r; +#if CHECKS + if (!dest || !a || !b) { + return E_PARAM; + } +#endif + if (a->length_W < b->length_W) { + const bigint_t *t; + t = a; + a = b; + b = t; + } +#if CHECKS + if ((r = check_size(dest, a->length_W + 1))) { + return r; + } +#endif + j = MIN(a->length_W, b->length_W); + for (i = 0; i < j; ++i) { + t = a->wordv[i] + b->wordv[i]; + c1 = t < a->wordv[i]; + dest->wordv[i] = t + c; + c2 = dest->wordv[i] < t; + c = c1 | c2; + } + for (; i < a->length_W; ++i) { + t = a->wordv[i]; + dest->wordv[i] = t + c; + c = dest->wordv[i] < t; + } + if (c) { + dest->wordv[i++] = c; + } + dest->length_W = i; + return 0; +} + + +/** + * \brief dest = ~a + */ +int bigint_invert(bigint_t *dest, const bigint_t *a) { + bigint_length_t i; + int r; +#if CHECKS + if ((r = check_size(dest, a->length_W))) { + return r; + } +#endif + i = a->length_W; + while(i--) { + dest->wordv[i] = ~a->wordv[i]; + } + dest->length_W = a->length_W; + return 0; +} + +/** + * \brief dest = a + 1 + */ +int bigint_add_one(bigint_t *dest, const bigint_t *a) { + bigint_t one = { + .wordv = (bigint_word_t*)"\x01", + .length_W = 1, + .allocated_W = 1, + .info = 0 + }; + return bigint_add_u(dest, a, &one); +} + +/** + * \brief dest = -a + */ +int bigint_negate(bigint_t *dest, const bigint_t *a) { + int r = 0; +#if CHECKS + if ((r = check_size(dest, a->length_W))) { + return r; + } +#endif + r |= bigint_invert(dest, a); + r |= bigint_add_one(dest, dest); + return r; +} + +/** + * \brief dest = |a| - |b| + * Subtracts b from a and stores the result in dest. + * Signs are ignored + */ +int bigint_sub_u(bigint_t *dest, const bigint_t *a, const bigint_t *b) { + bigint_length_t i, j; + bigint_word_t t, c1, c2, c = 0; + int r; +#if CHECKS + if (!dest || !a || !b) { + return E_PARAM; + } +#endif +#if CHECKS + if ((r = check_size(dest, MAX(a->length_W, b->length_W)))) { + return r; + } + +#endif + j = MIN(a->length_W, b->length_W); + for (i = 0; i < j; ++i) { + t = a->wordv[i] - b->wordv[i]; + c1 = t > a->wordv[i]; + dest->wordv[i] = t - c; + c2 = dest->wordv[i] > t; + c = c1 | c2; + } + for (; i < a->length_W; ++i) { + t = a->wordv[i]; + dest->wordv[i] = t - c; + c = dest->wordv[i] > t; + } + dest->length_W = a->length_W; + return 0; +} + +/** + * \brief a <<= 1 + */ +int bigint_shiftleft_words(bigint_t *dest, const bigint_t *a, bigint_length_t s) { +#if CHECKS + if (!a) { + return E_PARAM; + } +#endif + if (s == 0) { + bigint_copy(dest, a); + return 0; + } + int r; + if ((r = check_size(dest, a->length_W + s))) { + return r; + } + memmove(&dest->wordv[s], &a->wordv[0], a->length_W * sizeof(bigint_word_t)); + memset(&dest->wordv[0], 0, s * sizeof(bigint_word_t)); + dest->length_W = a->length_W + s; + return 0; +} + + +/** + * \brief a <<= 1 + */ +int bigint_shiftleft_1bit(bigint_t *a) { + uint8_t c1 = 0, c2; + bigint_word_t t; + bigint_length_t i; +#if CHECKS + if (!a) { + return E_PARAM; + } +#endif + + for(i = 0; i < a->length_W; ++i) { + t = a->wordv[i]; + c2 = t >> (BIGINT_WORD_SIZE - 1); + t <<= 1; + t |= c1; + a->wordv[i] = t; + c1 = c2; + } + + return 0; +} + +/** + * \brief a <<= s + */ +static +int bigint_shiftleft_small(bigint_t *dest, const bigint_t *a, uint_fast8_t s) { + bigint_wordplus_t t = 0; + bigint_length_t i, l; +#if CHECKS + if (!a) { + return E_PARAM; + } +#endif + l = bigint_get_first_set_bit(a) + BIGINT_WORD_SIZE; +#if CHECKS + int r; + if ((r = check_size(dest, (l + s ) / BIGINT_WORD_SIZE))) { + return r; + } + +#endif + dest->length_W = (l + s ) / BIGINT_WORD_SIZE; + l /= BIGINT_WORD_SIZE; + for(i = 0; i < l; ++i) { + t |= (bigint_wordplus_t)a->wordv[i] << s; + dest->wordv[i] = t; + t >>= BIGINT_WORD_SIZE; + } + if (t) { + dest->wordv[i] = t; + } + return 0; +} + +/** + * \brief dest = a << s + */ +int bigint_shiftleft(bigint_t *dest, const bigint_t *a, bigint_length_t s) { + int r; + if((r = bigint_shiftleft_small(dest, a, s % BIGINT_WORD_SIZE))) { + return r; + } + if ((r = bigint_shiftleft_words(dest, dest, s / BIGINT_WORD_SIZE))) { + return r; + } + return 0; +} + +/** + * \brief a >>= 1 + */ +int bigint_shiftright_1bit(bigint_t *a) { + uint8_t c1 = 0, c2; + bigint_word_t t; + bigint_length_t i; +#if CHECKS + if (!a) { + return E_PARAM; + } +#endif + + for(i = a->length_W; i != 0; --i) { + t = a->wordv[i - 1]; + c2 = t & 1; + t >>= 1; + t |= c1 << (BIGINT_WORD_SIZE - 1); + a->wordv[i - 1] = t; + c1 = c2; + } + + return 0; +} + +/** + * \brief dest = a ** 2 + */ +int bigint_square(bigint_t *dest, const bigint_t *a) { + bigint_word_t c1, c2; + bigint_wordplus_t uv; + bigint_word_t q; + bigint_length_t i, j; +#if CHECKS + int r; + if (!dest || !a) { + return E_PARAM; + } + if ((r = check_size(dest, a->length_W * 2))) { + return r; + } +#endif + if (dest == a) { + bigint_t t = {NULL, 0, 0, 0}; + bigint_copy(&t, a); + r = bigint_square(dest, &t); + bigint_free(&t); + return r; + } + memset(dest->wordv, 0, 2 * a->length_W * sizeof(bigint_word_t)); + for(i = 0; i < a->length_W; ++i) { + uv = (bigint_wordplus_t)dest->wordv[2 * i] + + (bigint_wordplus_t)a->wordv[i] + * (bigint_wordplus_t)a->wordv[i]; + dest->wordv[2 * i] = uv; + c1 = uv >> BIGINT_WORD_SIZE; + c2 = 0; + for (j = i + 1; j < a->length_W; ++j) { + uv = (bigint_wordplus_t)a->wordv[i] + * (bigint_wordplus_t)a->wordv[j]; + q = uv >> (2 * BIGINT_WORD_SIZE - 1); + uv <<= 1; + uv += dest->wordv[i + j]; + q += (uv < dest->wordv[i + j]); /* this might be dangerous! XXX */ + uv += c1; + q += (uv < c1); /* this might be dangerous! XXX */ + dest->wordv[i + j] = uv; + c1 = c2 + (uv >> BIGINT_WORD_SIZE); + c2 = q + (c1 < c2); /* this might be dangerous! XXX */ + } + dest->wordv[i + a->length_W] += c1; + dest->wordv[i + a->length_W + 1] = c2 + (dest->wordv[i + a->length_W] < c1); /* this might be dangerous! XXX */ + } + dest->length_W = a->length_W * 2; + return 0; +} + + +/** + * \brief dest = |a * b| + * unsigned multiply a bigint (a) by a word (b) + */ +int bigint_mul_word(bigint_t *dest, const bigint_t *a, const bigint_word_t b) { + bigint_wordplus_t c1 = 0; + bigint_length_t i; +#if CHECKS + int r; + if (!dest || !a || !b) { + return E_PARAM; + } + if ((r = check_size(dest, a->length_W + 1))) { + return r; + } +#endif + for(i = 0; i < a->length_W; ++i) { + c1 += (bigint_wordplus_t)b * (bigint_wordplus_t)a->wordv[i]; + dest->wordv[i] = c1; + c1 >>= BIGINT_WORD_SIZE; + } + dest->wordv[i++] = c1; + dest->length_W = i; + BIGINT_SET_POS(dest); + return 0; +} + +/** + * \brief dest = a * b + */ +int bigint_mul_schoolbook(bigint_t *dest, const bigint_t *a, const bigint_t *b) { + bigint_wordplus_t v; + bigint_word_t c; + bigint_length_t i, j; + int r; +#if CHECKS + if (!dest || !a || !b) { + return E_PARAM; + } + if ((r = check_size(dest, a->length_W + b->length_W))) { + return r; + } +#endif + if (dest == a) { + bigint_t t = {NULL, 0, 0, 0}; + bigint_copy(&t, a); + r = bigint_mul_schoolbook(dest, &t, b); + bigint_free(&t); + return r; + } + if (dest == b) { + bigint_t t = {NULL, 0, 0, 0}; + bigint_copy(&t, b); + r = bigint_mul_schoolbook(dest, a, &t); + bigint_free(&t); + return r; + } + memset(dest->wordv, 0, (a->length_W + b->length_W) * sizeof(bigint_word_t)); + for(i = 0; i < b->length_W; ++i) { + c = 0; + for(j = 0; j < a->length_W; ++j) { + v = (bigint_wordplus_t)a->wordv[j] + * (bigint_wordplus_t)b->wordv[i]; + v += (bigint_wordplus_t)dest->wordv[i + j]; + v += (bigint_wordplus_t)c; + dest->wordv[i + j] = v; + c = v >> BIGINT_WORD_SIZE; + } + dest->wordv[i + j] = c; + } + + dest->length_W = a->length_W + b->length_W; + dest->info &= ~BIGINT_SIGN_MASK; + dest->info |= (a->info ^ b->info) & BIGINT_SIGN_MASK; + return 0; +} + +/* + * UNSAFE!!! + */ +int8_t bigint_cmp_u(const bigint_t *a, const bigint_t *b) { + int8_t r = 1; + bigint_length_t i; + if (a->length_W == 0 && b->length_W == 0) { + return 0; + } + if (b->length_W == 0) { + return 1; + } + if (a->length_W == 0) { + return -1; + } + if (a->length_W < b->length_W) { + const bigint_t *t; + t = a; + a = b; + b = t; + r = -1; + } + for (i = a->length_W - 1; i > b->length_W - 1; --i) { + if (a->wordv[i]) { + return r; + } + } + ++i; + do { + --i; + if (a->wordv[i] != b->wordv[i]) { + return a->wordv[i] > b->wordv[i] ? r : -r; + } + } while (i); + return 0; +} + +int8_t bigint_cmp_s(const bigint_t *a, const bigint_t *b) { + if ( bigint_get_first_set_bit(a) == (bigint_length_t)-1 && + bigint_get_first_set_bit(b) == (bigint_length_t)-1 ) { + return 0; + } + if ((a->info & BIGINT_SIGN_MASK) ^ (b->info & BIGINT_SIGN_MASK)) { + return (a->info & BIGINT_SIGN_MASK) ? -1 : 1; + } else { + int r; + r = bigint_cmp_u(a, b); + return (a->info & BIGINT_SIGN_MASK) ? -r : r; + } + return 0; +} + +/* + * UNSAFE!!! + * a <=> b * (B ** s) + */ +int8_t bigint_cmp_scale(const bigint_t *a, const bigint_t *b, bigint_length_t s) { + bigint_length_t i; + if (s == 0) { + return bigint_cmp_u(a, b); + } + if (a->length_W == 0 && b->length_W == 0) { + return 0; + } + if (b->length_W == 0) { + return 1; + } + if (a->length_W == 0) { + return -1; + } + if (s > a->length_W) { + return -1; + } + for (i = a->length_W - 1; i > b->length_W + s - 1; --i) { + if (a->wordv[i]) { + return 1; + } + } + for (; i > s - 1; --i) { + if (a->wordv[i] != b->wordv[i + s]){ + return a->wordv[i] > b->wordv[i + s] ? 1 : -1; + } + } + ++i; + do { + --i; + if (a->wordv[i]) { + return 1; + } + } while (i); + return 0; +} + +/** + * XXXXXXXXXXXX + * \brief dest = |a| - |b| * B ** s + * Subtracts b from a and stores the result in dest. + * Signs are ignored + */ +int bigint_sub_scale(bigint_t *dest, const bigint_t *a, const bigint_t *b, bigint_length_t s) { + bigint_length_t i, j; + bigint_word_t t, c1, c2, c = 0; + int r; +#if CHECKS + if (!dest || !a || !b) { + return E_PARAM; + } +#endif +#if CHECKS + if ((r = check_size(dest, MAX(a->length_W, b->length_W)))) { + return r; + } + +#endif + j = MIN(a->length_W, b->length_W); + for (i = 0; i < j; ++i) { + t = a->wordv[i + s] - b->wordv[i]; + c1 = t > a->wordv[i + s]; + dest->wordv[i + s] = t - c; + c2 = dest->wordv[i + s] > t; + c = c1 | c2; + } + for (; i < a->length_W; ++i) { + t = a->wordv[i + s]; + dest->wordv[i + s] = t - c; + c = dest->wordv[i + s] > t; + } + dest->length_W = a->length_W; + return 0; +} + +/* + * UNSAFE!!! + */ +int bigint_adjust_length(bigint_t *a) { +#if CHECKS + if (!a) { + return E_PARAM; + } +#endif + while (a->length_W) { + if (a->wordv[a->length_W - 1]) { + return 0; + } + a->length_W--; + } + return 0; +} + +bigint_length_t bigint_get_first_set_bit(const bigint_t *a) { + bigint_length_t r; + bigint_word_t t; + if (!a) { + return (bigint_length_t)-1; + } + if (a->length_W == 0) { + return (bigint_length_t)-1; + } + r = a->length_W - 1; + while (r && a->wordv[r] == 0) { + --r; + } + t = a->wordv[r]; + if (!t) { + return (bigint_length_t)-1; + } + r *= BIGINT_WORD_SIZE; + t >>= 1; + while (t) { + t >>= 1; + ++r; + } + return r; +} + +/* + * UNSAFE!!! + * a = q * b + r + */ +int bigint_divide(bigint_t *q, bigint_t *r, const bigint_t *a, const bigint_t *b) { + bigint_t a_ = {NULL, 0, 0, 0}, x_ = {NULL, 0, 0, 0}; + bigint_length_t i, la, lb; + int ret; +#if CHECKS + if (!a || !b || (!q && !r)) { + return E_PARAM; + } +#endif + la = bigint_get_first_set_bit(a); + lb = bigint_get_first_set_bit(b); + if (lb == (bigint_length_t)-1) { + return E_VALUE; + } + if (la == (bigint_length_t)-1) { + if (q) { + q->length_W = 0; + } + if (r) { + r->length_W = 0; + } + return 0; + } + if (la < lb) { + if (q) { + q->length_W = 0; + } + if (r) { + bigint_copy(r, a); + } + return 0; + } + i = la - lb; + if (q) { + if ((ret = check_size(q, (i + BIGINT_WORD_SIZE - 1) / BIGINT_WORD_SIZE))) { + return ret; + } + memset(q->wordv, 0, q->allocated_W * sizeof(bigint_word_t)); + } + if (r) { + if ((ret = check_size(q, (lb + BIGINT_WORD_SIZE - 1) / BIGINT_WORD_SIZE))) { + return ret; + } + } + if ((ret = bigint_copy(&a_, a))) { + return ret; + } + if ((ret = bigint_shiftleft(&x_, b, i))) { + bigint_free(&a_); + return ret; + } +#if 0 + printf("DBG: x' = "); + bigint_print_hex(&x_); + printf("; b = "); + bigint_print_hex(b); + printf("; la = %d; lb = %d; i = %d\n", la, lb, i); +#endif + do { + if (bigint_cmp_u(&a_, &x_) >= 0) { + bigint_sub_u(&a_, &a_, &x_); + if (q) { + q->wordv[i / BIGINT_WORD_SIZE] |= 1 << (i % BIGINT_WORD_SIZE); + } + } + bigint_shiftright_1bit(&x_); + } while (i--); + if (r) { + bigint_copy(r, &a_); + } + bigint_free(&x_); + bigint_free(&a_); + return 0; +} + +/** + * UNSAFE!!! + */ +int bigint_sub_s(bigint_t *dest, const bigint_t *a, const bigint_t *b) { + int8_t s; + int r; + if (a->length_W == 0) { + bigint_copy(dest, b); + dest->info ^= BIGINT_SIGN_MASK; + return 0; + } + if ((a->info ^ b->info) & BIGINT_SIGN_MASK) { + /* different signs */ + if ((r = bigint_add_auto_u(dest, a, b))) { + return r; + } + dest->info = a->info; + } else { + s = bigint_cmp_u(a, b); + if (s >= 0) { + if (( r = bigint_sub_u(dest, a, b))) { + return r; + } + dest->info = a->info; + } else { + if (( r = bigint_sub_u(dest, b, a))) { + return r; + } + dest->info = (~a->info) & BIGINT_SIGN_MASK; + } + } + return 0; +} + +/** + * UNSAFE!!! + */ +int bigint_add_s(bigint_t *dest, const bigint_t *a, const bigint_t *b) { + int8_t s; + int r; + if ((a->info ^ b->info) & BIGINT_SIGN_MASK) { + /* different signs */ + s = bigint_cmp_u(a, b); + if (s >= 0) { + if (( r = bigint_sub_u(dest, a, b))) { + return r; + } + dest->info = a->info; + } else { + if (( r = bigint_sub_u(dest, b, a))) { + return r; + } + dest->info = (~a->info) & BIGINT_SIGN_MASK; + } + } else { + if ((r = bigint_add_auto_u(dest, a, b))) { + return r; + } + dest->info = a->info; + } + return 0; +} + +int8_t bigint_is_even(const bigint_t *a) { + if (!a) { + return E_VALUE; + } + if (a->length_W == 0 || (a->wordv[0] & 1) == 0) { + return 1; + } + return 0; +} + +int8_t bigint_is_odd(const bigint_t *a) { + if (!a) { + return E_VALUE; + } + if (a->length_W > 0 && (a->wordv[0] & 1) == 1) { + return 1; + } + return 0; +} + +/** + * UNSAFE!!! + * (a, b) -> (x, y, v) + * v = gcd(a,b) + * x * a + y * b = v + */ +int bigint_gcdext(bigint_t *gcd, bigint_t *x, bigint_t *y, const bigint_t *a, const bigint_t *b) { + bigint_length_t g = 0; + bigint_t u = {NULL, 0, 0, 0}, v = {NULL, 0, 0, 0}; + bigint_t x_ = {NULL, 0, 0, 0}, y_ = {NULL, 0, 0, 0}; + bigint_t A = {NULL, 0, 0, 0}, B = {NULL, 0, 0, 0}; + bigint_t C = {NULL, 0, 0, 0}, D = {NULL, 0, 0, 0}; + int r; + if ((r = bigint_copy(&x_, a))) { + return r; + } + if ((r = bigint_copy(&y_, b))) { + bigint_free(&x_); + return r; + } + bigint_adjust_length(&x_); + bigint_adjust_length(&y_); + if (x_.length_W == 0 || y_.length_W == 0) { + bigint_free(&y_); + bigint_free(&x_); + return E_VALUE; + } + while (((x_.wordv[0] | y_.wordv[0]) & 1) == 0) { + ++g; + bigint_shiftright_1bit(&x_); + bigint_shiftright_1bit(&y_); + } + if ((r = check_size(&A, 1 + (bigint_get_first_set_bit(&y_) + BIGINT_WORD_SIZE) / BIGINT_WORD_SIZE))) { + bigint_free(&y_); + bigint_free(&x_); + return r; + } + if ((r = check_size(&C, 1 + (bigint_get_first_set_bit(&y_) + BIGINT_WORD_SIZE) / BIGINT_WORD_SIZE))) { + bigint_free(&A); + bigint_free(&y_); + bigint_free(&x_); + return r; + } + if ((r = check_size(&B, 1 + (bigint_get_first_set_bit(&x_) + BIGINT_WORD_SIZE) / BIGINT_WORD_SIZE))) { + bigint_free(&C); + bigint_free(&A); + bigint_free(&y_); + bigint_free(&x_); + return r; + } + if ((r = check_size(&D, 1 + (bigint_get_first_set_bit(&x_) + BIGINT_WORD_SIZE) / BIGINT_WORD_SIZE))) { + bigint_free(&B); + bigint_free(&C); + bigint_free(&A); + bigint_free(&y_); + bigint_free(&x_); + return r; + } + if ((r = bigint_copy(&u, &x_))) { + bigint_free(&D); + bigint_free(&B); + bigint_free(&C); + bigint_free(&A); + bigint_free(&y_); + bigint_free(&x_); + return r; + } + if ((r = bigint_copy(&v, &y_))) { + bigint_free(&u); + bigint_free(&D); + bigint_free(&B); + bigint_free(&C); + bigint_free(&A); + bigint_free(&y_); + bigint_free(&x_); + return r; + } + A.wordv[0] = D.wordv[0] = 1; + A.length_W = D.length_W = 1; + C.length_W = B.length_W = 0; + + do { + while ((u.wordv[0] & 1) == 0) { + bigint_shiftright_1bit(&u); + if (bigint_is_odd(&A) || bigint_is_odd(&B)) { + bigint_add_s(&A, &A, &y_); + bigint_sub_s(&B, &B, &x_); + } + bigint_shiftright_1bit(&A); + bigint_shiftright_1bit(&B); + } + while ((v.wordv[0] & 1) == 0) { + bigint_shiftright_1bit(&v); + if (bigint_is_odd(&C) || bigint_is_odd(&D)) { + bigint_add_s(&C, &C, &y_); + bigint_sub_s(&D, &D, &x_); + } + bigint_shiftright_1bit(&C); + bigint_shiftright_1bit(&D); + } + if (bigint_cmp_s(&u, &v) >= 0) { + bigint_sub_s(&u, &u, &v); + bigint_sub_s(&A, &A, &C); + bigint_sub_s(&B, &B, &D); + } else { + bigint_sub_s(&v, &v, &u); + bigint_sub_s(&C, &C, &A); + bigint_sub_s(&D, &D, &B); + } + bigint_adjust_length(&u); + } while (u.length_W != 0); + if (gcd) { + bigint_shiftleft(gcd, &v, g); + } + if (x) { + bigint_copy(x, &C); + } + if (y) { + bigint_copy(y, &D); + } + bigint_free(&v); + bigint_free(&u); + bigint_free(&D); + bigint_free(&B); + bigint_free(&C); + bigint_free(&A); + bigint_free(&y_); + bigint_free(&x_); + return 0; +} diff --git a/bigint2/bigint2.h b/bigint2/bigint2.h new file mode 100644 index 0000000..4bd9421 --- /dev/null +++ b/bigint2/bigint2.h @@ -0,0 +1,140 @@ +/* bigint2.h */ +/* + This file is part of the AVR-Crypto-Lib. + Copyright (C) 2014 Daniel Otte (daniel.otte@rub.de) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef BIGINT2_H_ +#define BIGINT2_H_ + +#include +#include +#include + +#define BIGINT_WORD_SIZE 8 + +#if BIGINT_WORD_SIZE == 8 +typedef uint8_t bigint_word_t; +typedef uint16_t bigint_wordplus_t; +typedef int16_t bigint_wordplus_signed_t; +#elif BIGINT_WORD_SIZE == 16 +typedef uint16_t bigint_word_t; +typedef uint32_t bigint_wordplus_t; +typedef int32_t bigint_wordplus_signed_t; +#elif BIGINT_WORD_SIZE == 32 +typedef uint32_t bigint_word_t; +typedef uint64_t bigint_wordplus_t; +typedef int64_t bigint_wordplus_signed_t; +#else +#error "INVALID VALUE FOR BIGINT_WORD_SIZE" +#endif + +typedef uint16_t bigint_length_t; +typedef uint8_t bigint_info_t; + +#define BIGINT_SIGN_MASK 0x80 +#define BIGINT_GET_SIGN(x) ((x)->info & BIGINT_SIGN_MASK) +#define BIGINT_SET_POS(x) ((x)->info &= ~BIGINT_SIGN_MASK) +#define BIGINT_SET_NEG(x) ((x)->info |= BIGINT_SIGN_MASK) + + +typedef struct { + bigint_word_t *wordv; + bigint_length_t length_W; + bigint_length_t allocated_W; + bigint_info_t info; +} bigint_t; + +extern void *(*int_realloc)(void *ptr, size_t size); +extern void (*int_free)(void *ptr); + +int bigint_copy(bigint_t *dest, const bigint_t *a); + +int bigint_free(bigint_t *a); + +/** + * \brief dest = |a| + |b| + * Adds the bigints a and b and stores the result in dest. + * Signs are ignored. + */ +int bigint_add_u(bigint_t *dest, const bigint_t *a, const bigint_t *b); + +/** + * \brief dest = |a| - |b| + * Subtracts b from a and stores the result in dest. + * Signs are ignored + */ +int bigint_sub_u(bigint_t *dest, const bigint_t *a, const bigint_t *b); + +/** + * \brief a <<= 1 + */ +int bigint_shiftleft_1bit(bigint_t *a); + +/** + * \brief dest = a << s + */ +int bigint_shiftleft(bigint_t *dest, const bigint_t *a, bigint_length_t s); + +/** + * \brief a >>= 1 + */ +int bigint_shiftright_1bit(bigint_t *a); + +/** + * \brief dest = a ** 2 + */ +int bigint_square(bigint_t *dest, const bigint_t *a); + +/** + * \brief dest = |a * b| + * unsigned multiply a bigint (a) by a word (b) + */ +int bigint_mul_word(bigint_t *dest, const bigint_t *a, const bigint_word_t b); + +/** + * \brief dest = a * b + */ +int bigint_mul_schoolbook(bigint_t *dest, const bigint_t *a, const bigint_t *b); + +/* + * UNSAFE!!! + * a <=> b + */ +int8_t bigint_cmp_u(const bigint_t *a, const bigint_t *b); + +/* + * UNSAFE!!! + * a <=> b * (B ** s) + */ +int8_t bigint_cmp_scale(const bigint_t *a, const bigint_t *b, bigint_length_t s); + +/* + * UNSAFE!!! + */ +int bigint_adjust_length(bigint_t *a); + +bigint_length_t bigint_get_first_set_bit(const bigint_t *a); + +int bigint_divide(bigint_t *q, bigint_t *r, const bigint_t *a, const bigint_t *b); + +int8_t bigint_cmp_s(const bigint_t *a, const bigint_t *b); + +int bigint_gcdext(bigint_t *gcd, bigint_t *x, bigint_t *y, const bigint_t *a, const bigint_t *b); + + + +#endif /* BIGINT2_H_ */ diff --git a/bigint2/bigint2_io.c b/bigint2/bigint2_io.c new file mode 100644 index 0000000..f347688 --- /dev/null +++ b/bigint2/bigint2_io.c @@ -0,0 +1,180 @@ +/* bigint_io.c */ +/* + This file is part of the ARM-Crypto-Lib. + Copyright (C) 2010 Daniel Otte (daniel.otte@rub.de) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#include "cli.h" +#include "hexdigit_tab.h" +#include "bigint2.h" +#include +#include +#include + +void bigint_print_hex(const bigint_t *a) { + if (a->length_W == 0) { + putchar('0'); + return; + } + if (a->info & BIGINT_SIGN_MASK) { + putchar('-'); + } + size_t idx; + uint8_t print_zero = 0; + uint8_t *p, x, y; + p = (uint8_t*)&(a->wordv[a->length_W - 1]) + sizeof(bigint_word_t) - 1; + for (idx = a->length_W * sizeof(bigint_word_t); idx > 0; --idx) { + x = *p >> 4; + y = *p & 0xf; + if (x != 0 || print_zero != 0) { + putchar(pgm_read_byte(&hexdigit_tab_lc_P[x])); + } + if (x) { + print_zero = 1; + } + if (y != 0 || print_zero != 0) { + putchar(pgm_read_byte(&hexdigit_tab_lc_P[y])); + } + if (y) { + print_zero = 1; + } + --p; + } + if (!print_zero) { + putchar(pgm_read_byte(&hexdigit_tab_lc_P[0])); + } +} + +#define BLOCKSIZE 32 + +static uint8_t char2nibble(char c) { + if (c >= '0' && c <= '9') { + return c - '0'; + } + c |= 'A' ^ 'a'; /* to lower case */ + if ( c >= 'a' && c <= 'f') { + return c - 'a' + 10; + } + return 0xff; +} + +static uint16_t read_byte(void) { + uint8_t t1, t2; + char c; + c = cli_getc_cecho(); + if (c == '-') { + return 0x0500; + } + t1 = char2nibble(c); + if (t1 == 0xff) { + return 0x0100; + } + c = cli_getc_cecho(); + t2 = char2nibble(c); + if (t2 == 0xff) { + return 0x0200|t1; + } + return (t1 << 4)|t2; +} + +uint8_t bigint_read_hex_echo(bigint_t *a, bigint_length_t length) { + uint8_t shift4 = 0; + uint16_t t, idx = 0; + uint8_t *buf = NULL; + memset(a, 0, sizeof(*a)); + if (length && a->allocated_W < length) { + uint8_t *p; + p = int_realloc(buf, length * sizeof(bigint_word_t)); + if (p == NULL) { + cli_putstr("\r\nERROR: Out of memory!"); + return 0xff; + } + memset((uint8_t*)p, 0, length * sizeof(bigint_word_t)); + buf = p; + a->allocated_W = length; + } + for (;;) { + if (a->allocated_W - idx < 1) { + uint8_t *p; + if (length) { + if (buf) { + int_realloc(buf, 0); + } + return 0xfe; + } + p = int_realloc(buf, (a->allocated_W += BLOCKSIZE) * sizeof(bigint_word_t)); + if (p == NULL) { + cli_putstr("\r\nERROR: Out of memory!"); + if (buf) { + int_realloc(buf, 0); + } + return 0xff; + } + memset((uint8_t*)p + (a->allocated_W - BLOCKSIZE) * sizeof(bigint_word_t), 0, BLOCKSIZE * sizeof(bigint_word_t)); + buf = p; + } + t = read_byte(); + if (idx == 0) { + if (t & 0x0400) { + /* got minus */ + a->info |= BIGINT_SIGN_MASK; + continue; + } else { + if (t == 0x0100) { + free(a->wordv); + memset(a, 0, sizeof(*a)); + return 1; + } + } + } + if (t <= 0x00ff) { + buf[idx++] = (uint8_t)t; + } else { + if (t & 0x0200) { + shift4 = 1; + buf[idx++] = (uint8_t)((t & 0x0f) << 4); + } + break; + } + } + /* we have to reverse the byte array */ + uint8_t tmp; + uint8_t *p, *q; + a->length_W = (idx + sizeof(bigint_word_t) - 1) / sizeof(bigint_word_t); + p = buf; + q = buf + idx - 1; + while (q > p) { + tmp = *p; + *p = *q; + *q = tmp; + p++; q--; + } + a->wordv = (bigint_word_t*)buf; + if (shift4) { + bigint_shiftright_1bit(a); + bigint_shiftright_1bit(a); + bigint_shiftright_1bit(a); + bigint_shiftright_1bit(a); + } + if(a->length_W == 1 && a->wordv[0] == 0){ + a->length_W = 0; + a->info = 0; + } + if (length) { + a->length_W = length; + } + return 0; +} diff --git a/bigint2/bigint2_io.h b/bigint2/bigint2_io.h new file mode 100644 index 0000000..54f8f2c --- /dev/null +++ b/bigint2/bigint2_io.h @@ -0,0 +1,28 @@ +/* bigint_io.h */ +/* + This file is part of the ARM-Crypto-Lib. + Copyright (C) 2010 Daniel Otte (daniel.otte@rub.de) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ + +#ifndef BIGINT_IO_H_ +#define BIGINT_IO_H_ + +#include "bigint2.h" + +void bigint_print_hex(const bigint_t *a); +uint8_t bigint_read_hex_echo(bigint_t *a, bigint_length_t length); + +#endif /* BIGINT_IO_H_ */ diff --git a/host/bigint2_test.rb b/host/bigint2_test.rb new file mode 100644 index 0000000..df3ca3f --- /dev/null +++ b/host/bigint2_test.rb @@ -0,0 +1,1156 @@ +#!/usr/bin/ruby +# bigint_test.rb +=begin + This file is part of the AVR-Crypto-Lib. + Copyright (C) 2008, 2009 Daniel Otte (daniel.otte@rub.de) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +=end + +$debug = true +$debug = false +require 'rubygems' +require 'serialport' +require 'getopt/std' +require 'fileutils' +require 'date' +$buffer_size = 0 +$conffile_check = Hash.new +$conffile_check.default = 0 + +def max(a, b) + return a > b ? a : b +end + +def min(a, b) + return a < b ? a : b +end + +################################################################################ +# readconfigfile # +################################################################################ + +def readconfigfile(fname, conf) + return conf if $conffile_check[fname]==1 + $conffile_check[fname]=1 + section = "default" + if ! File.exists?(fname) + return conf + end + file = File.open(fname, "r") + until file.eof + line = file.gets() + next if /[\s]*#/.match(line) + if m=/\[[\s]*([^\s]*)[\s]*\]/.match(line) + section=m[1] + conf[m[1]] = Hash.new + next + end + next if ! /=/.match(line) + m=/[\s]*([^\s]*)[\s]*=[\s]*([^\s]*)/.match(line) + if m[1]=="include" + Dir.glob(m[2]){ |fn| conf = readconfigfile(fn, conf) } + else + conf[section][m[1]] = m[2] + end + end + file.close() + return conf +end + +################################################################################ +# expmod # +################################################################################ + +def expmod(base, power, mod) + result = 1 + while power > 0 + result = (result * base) % mod if power & 1 == 1 + base = (base * base) % mod + power >>= 1; + end + return result +end + +################################################################################ +# gcdext # +################################################################################ + +def gcdext(x,y) + return [0, 0, 0] if(x == 0 || y == 0) + g=1 + while(x&1==0 && y&1==0) do + x>>=1 + y>>=1 + g<<=1 + end + u=x; v=y; a=1; b=0; c=0; d=1 + begin + while(u&1==0) do + if(a%2==1 || b%2==1) + a += y + b -= x + end + u>>=1; a>>=1; b>>=1 + end + while(v&1==0) do + if(c%2==1 || d%2==1) + c += y + d -= x + end + v>>=1; c>>=1; d>>=1; + end + if(u>=v) + u -= v; a-=c; b-=d + else + v -= u; c-=a; d-=b + end + end while(u!=0) + return[g*v, c, d] +end + +################################################################################ +# reset_system # +################################################################################ + +def reset_system + $sp.print("exit\r") + sleep 0.1 + $sp.print("exit\r") + sleep 0.1 +end + +################################################################################ +# init_system # +################################################################################ + +def init_system(test_prog) + begin + line = $sp.gets() + end while line!=nil + $sp.print("echo off \r") + print("DBG i: " + "echo off \r"+"\n") if $debug + sleep 0.1 + $sp.print("#{test_prog}\r") + print("DBG i: " + "#{test_prog} \r"+"\n") if $debug + sleep 1 +end + +################################################################################ +# wait_for_prompt # +################################################################################ + +def wait_for_prompt(prompt) + prompt = /[\s]*#{prompt}[\s]*/ if(prompt.class == String) + start_time = Time.now.to_i + acc = '' + begin + line = $sp.gets() + puts("DBG got (#{__LINE__}): "+line) if $debug && line + line = "" if line==nil + if /^(Error:|Crypto-VS).*/.match(line) + puts line + return false + end + if (Time.now.to_i- start_time) > $max_timeout + return false + end + acc += line + end while ! m=prompt.match(acc) + return m +end + +################################################################################ +# screen_progress # +################################################################################ +def screen_progress(v) + if $linepos == 0 + printf("\n%5d [%04d]: ", $testno, $size) + end + putc((v)?('*'):('!')) + $testno += 1 + $linepos = ($linepos+1) % $linewidth +end + +################################################################################ +# add_test # +################################################################################ + +def add_test(a,b) + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter a:[\s]*/.match(line) + $sp.print(a.to_s(16)+" ") + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter b:[\s]*/.match(line) + $sp.print(b.to_s(16)+" ") + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! m=/[\s]*([-]?[0-9a-fA-F]*)[\s]+\+[\s]+([+-]?[0-9a-fA-F]*)[\s]*=[\s]*([+-]?[0-9a-fA-F]*)/.match(line) + a_ = m[1].to_i(16) + b_ = m[2].to_i(16) + c_ = m[3].to_i(16) + line.chomp! + if(a_== a && b_ == b && c_ == (a+b)) + $logfile.printf("[pass (%d)]: %s\n", $testno, line) + return true + else + $logfile.printf("[fail (%s%s%s) (%d)]: %s", + (a == a_) ? "" : "a", + (b == b_) ? "" : "b", + (c_ == a + b) ? "" : "c", $testno, line) + $logfile.printf(" ; should %s + %s = %s\n", a.to_s(16), b.to_s(16), (a+b).to_s(16)) + return false + end + return false +end + +################################################################################ +# sub_test # +################################################################################ + +def sub_test(a, b) + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter a:[\s]*/.match(line) + $sp.print(a.to_s(16)+" ") + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter b:[\s]*/.match(line) + $sp.print(b.to_s(16)+" ") + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! m=/[\s]*([-]?[0-9a-fA-F]*)[\s]+\-[\s]+([+-]?[0-9a-fA-F]*)[\s]*=[\s]*([+-]?[0-9a-fA-F]*)/.match(line) + a_ = m[1].to_i(16) + b_ = m[2].to_i(16) + c_ = m[3].to_i(16) + line.chomp! + if(a_== a && b_ == b && c_ == (a - b)) + $logfile.printf("[pass (%d)]: %s\n", $testno, line) + return true + else + $logfile.printf("[fail (%s%s%s) (%d)]: %s", + (a == a_) ? "" : "a", + (b == b_) ? "" : "b", + (c_ == a - b) ? "" : "c", $testno, line) + $logfile.printf(" ; should %s - %s = %s\n", a.to_s(16), b.to_s(16), (a - b).to_s(16)) + return false + end + return false +end + +################################################################################ +# mul_test # +################################################################################ + +def mul_test(a,b) + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter a:[\s]*/.match(line) + $sp.print(a.to_s(16)+" ") + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter b:[\s]*/.match(line) + $sp.print(b.to_s(16)+" ") + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! m=/[\s]*([+-]?[0-9a-fA-F]*)[\s]+\*[\s]+([+-]?[0-9a-fA-F]*)[\s]*=[\s]*([+-]?[0-9a-fA-F]*)/.match(line) + a_ = m[1].to_i(16) + b_ = m[2].to_i(16) + c_ = m[3].to_i(16) + line.chomp! + if(a_== a && b_ == b && c_ == (a*b)) + $logfile.printf("[pass]: %s\n", line) + return true + else + $logfile.printf("[fail (%s%s%s)]: %s", (a==a_)?"":"a", (b==b_)?"":"b", (c_==a*b)?"":"c",line) + $logfile.printf(" ; should %s * %s = %s\n", a.to_s(16), b.to_s(16), (a*b).to_s(16)) + return false + end + return false +end + +################################################################################ +# add_scale_test # +################################################################################ +def add_scale_test_dummy(a, b, scale) + should = a + (b<<(8*scale)) + printf("[dummy] %s + %s <<8*%04x = %s\n",a.to_s(16), b.to_s(16), scale, should.to_s(16)) +end + +def add_scale_test(a, b, scale) + m = wait_for_prompt("enter a:") + return false if !m + puts("DBG put (#{__LINE__}): "+a.to_s(16)+" ") if $debug + $sp.print(a.to_s(16)+" ") + m = wait_for_prompt("enter b:") + return false if !m + puts("DBG put (#{__LINE__}): "+b.to_s(16)+" ") if $debug + $sp.print(b.to_s(16)+" ") + m = wait_for_prompt("enter scale:") + return false if !m + puts("DBG put (#{__LINE__}): "+scale.to_s(10)+" ") if $debug + $sp.print(scale.to_s(10)+"\r") + should = a + (b<<(8*scale)) + m = wait_for_prompt(/[\s]*([-]?[0-9a-fA-F]+)[\s]+\+[\s]+([+-]?[0-9a-fA-F]+)[\s]*<<8\*[\s]*([+-]?[0-9a-fA-F]+)[\s]*=[\s]*([+-]?[0-9a-fA-F]+)/) + if !m + $logfile.printf("[fail (CRASH)]:") + $logfile.printf(" ; should %s + %s << 8*%s = %s\n", a.to_s(16), b.to_s(16), scale.to_s(16), should.to_s(16)) + return false + end + line = m[0] + a_ = m[1].to_i(16) + b_ = m[2].to_i(16) + s_ = m[3].to_i(16) + c_ = m[4].to_i(16) + line.chomp! + if(a_== a && b_ == b && s_ == scale && c_ == should ) + $logfile.printf("[pass]: %s\n", line) + return true + else + $logfile.printf("[fail (%s%s%s%s)]: %s", (a==a_)?"":"a", (b==b_)?"":"b", (scale==s_)?"":"s",(c_==should)?"":"c",line) + $logfile.printf(" ; should %s + %s << 8*%s = %s\n", a.to_s(16), b.to_s(16), scale.to_s(16), should.to_s(16)) + return false + end + return false +end + +################################################################################ +# square_test # +################################################################################ + +def square_test(a) + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter a:[\s]*/.match(line) + $sp.print(a.to_s(16)+" ") + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! m=/[\s]*([+-]?[0-9a-fA-F]*)[\s]*\*\*2[\s]*=[\s]*([+-]?[0-9a-fA-F]*)/.match(line) + a_ = m[1].to_i(16) + c_ = m[2].to_i(16) + line.chomp! + if(a_== a && c_ == (a**2)) + $logfile.printf("[pass]: %s\n", line) + return true + else + $logfile.printf("[fail (%s%s)]: %s", (a==a_)?"":"a", (c_==a**2)?"":"c",line) + $logfile.printf(" ; should %s **2 = %s\n", a.to_s(16), (a**2).to_s(16)) + return false + end + return false +end + +################################################################################ +# reduce_test # +################################################################################ + +def reduce_test(a,b) + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter a:[\s]*/.match(line) + $sp.print(a.to_s(16)+" ") + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter b:[\s]*/.match(line) + $sp.print(b.to_s(16)+" ") + line='' + begin + line_tmp = $sp.gets() + line_tmp = '' if line_tmp==nil + line += line_tmp + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! m=/[\s]*([+-]?[0-9a-fA-F]*)[\s]+%[\s]+([+-]?[0-9a-fA-F]*)[\s]*=[\s]*([+-]?[0-9a-fA-F]+)/.match(line) + a_ = m[1].to_i(16) + b_ = m[2].to_i(16) + c_ = m[3].to_i(16) + line.strip! + if(a_== a && b_ == b && c_ == (a%b)) + $logfile.printf("[pass (%d)]: %s\n", $testno, line) + return true + else + $logfile.printf("[fail (%s%s%s) (%d)]: %s", + (a == a_) ? "" : "a", + (b == b_) ? "" : "b", + (c_ == a % b) ? "" : "c", $testno, line) + $logfile.printf(" ; should %s %% %s = %s\n", a.to_s(16), b.to_s(16), (a % b).to_s(16)) + return false + end + return false +end + +################################################################################ +# mulmod_test # +################################################################################ + +def mulmod_test(a,b,c) + begin + printf("[testing] mulmod(%#x, %#x, %#x)\n",a,b,c) if $debug + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter a:[\s]*/.match(line) + $sp.print(a.to_s(16)+" ") + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter b:[\s]*/.match(line) + $sp.print(b.to_s(16)+" ") + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter c:[\s]*/.match(line) + $sp.print(c.to_s(16)+" ") + line='' + begin + line_tmp = $sp.gets() + line_tmp = '' if line_tmp==nil + line += line_tmp + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + m = /[\s]*\([\s]*([+-]?[0-9a-fA-F]*)[\s]*\*[\s]*([+-]?[0-9a-fA-F]*)[\s]*\)[\s]+%[\s]+([+-]?[0-9a-fA-F]*)[\s]*=[\s]*([+-]?[0-9a-fA-F]+)/.match(line) + puts("DBG: line did not match pattern (" + line + ")") if !m && $debug + end while ! m + a_ = m[1].to_i(16) + b_ = m[2].to_i(16) + c_ = m[3].to_i(16) + d_ = m[4].to_i(16) + line.chomp! + if(a_== a && b_ == b && c_ == c && d_ == (a * b % c) ) + $logfile.printf("[pass]: %s\n", line) + return true + else + $logfile.printf("[fail (%s%s%s%s)]: %s", (a == a_) ? '' : 'a', (b == b_) ? '' : 'b', (c_ == c) ? '' : 'c', (d_== (a * b % c)) ? '' : 'd',line) + $logfile.printf(" ; should (%s * %s) %% %s = %s\n", a.to_s(16), b.to_s(16), c.to_s(16), (a * b % c).to_s(16)) + return false + end + return false +end + +################################################################################ +# expmod_test # +################################################################################ + +def expmod_test(a,b,c) + begin + printf("[testing] expmod(%#x, %#x, %#x)\n",a,b,c) if $debug + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter a:[\s]*/.match(line) + $sp.print(a.to_s(16)+" ") + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter b:[\s]*/.match(line) + $sp.print(b.to_s(16)+" ") + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter c:[\s]*/.match(line) + $sp.print(c.to_s(16)+" ") + line='' + begin + line_tmp = $sp.gets() + line_tmp = '' if line_tmp == nil + line += line_tmp + puts("DBG got: "+line) if $debug + if /^Error:/.match(line) + puts line + return false + end + end while ! m=/[\s]*([+-]?[0-9a-fA-F]+)\*\*([+-]?[0-9a-fA-F]+)[\s]+%[\s]+([+-]?[0-9a-fA-F]+)[\s]*=[\s]*([+-]?[0-9a-fA-F]+)/.match(line) + a_ = m[1].to_i(16) + b_ = m[2].to_i(16) + c_ = m[3].to_i(16) + d_ = m[4].to_i(16) + line.chomp! + if(a_== a && b_ == b && c_ == c && d_ ==expmod(a,b,c) ) + $logfile.printf("[pass]: %s\n", line) + return true + else + $logfile.printf("[fail (%s%s%s%s)]: %s", (a==a_)?'':'a', (b==b_)?'':'b', (c_==c)?'':'c', (d_==expmod(a,b,c))?'':'d',line) + $logfile.printf(" ; should %s**%s %% %s = %s\n", a.to_s(16), b.to_s(16), c.to_s(16), expmod(a,b,c).to_s(16)) + return false + end + return false +end + +################################################################################ +# gcdext_test # +################################################################################ + +def gcdext_test(a,b) + $logfile.printf("[testing] gcdext(%s, %s)\n", a.to_s(16), b.to_s(16)) + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter a:[\s]*/.match(line) + $sp.print(a.to_s(16)+" ") + begin + line = $sp.gets() + line = "" if line==nil + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! /[\s]*enter b:[\s]*/.match(line) + $sp.print(b.to_s(16)+" ") + line='' + begin + line_tmp = $sp.gets() + line_tmp = '' if line_tmp==nil + line = '' if line.end_with?('\n') + line += line_tmp + puts("DBG got: "+line) if $debug + if /^Error:.*/.match(line) + puts line + return false + end + end while ! m=/gcdext\([\s]*([+-]?[0-9a-fA-F]*)[\s]*,[\s]*([+-]?[0-9a-fA-F]*)[\s]*\)[\s]*=> a = ([+-]?[0-9a-fA-F]+); b = ([+-]?[0-9a-fA-F]+); gcd = ([+-]?[0-9a-fA-F]+)/.match(line) + a_ = m[1].to_i(16) + b_ = m[2].to_i(16) + c_ = m[3].to_i(16) + d_ = m[4].to_i(16) + e_ = m[5].to_i(16) + line.chomp! + line.gsub!("\r",'') + line.gsub!("\n",'') + ref = gcdext(a,b) + if(a_== a && b_ == b && c_ == ref[1] && d_ == ref[2] && e_== ref[0]) + $logfile.printf("[pass (%d)]: %s\n", $testno, line) + return true + else + $logfile.printf("[fail (%s%s%s%s%s) (%d)]: %s", + (a == a_) ? '' : 'a', + (b == b_) ? '' : 'b', + (c_ == ref[1]) ? '' : 'c', + (d_ == ref[2]) ? '' : 'd', + (e_ == ref[0]) ? '' : 'e', $testno, line) + $logfile.printf(" ; should gcdext( %s, %s) => a = %s; b = %s; gcd = %s\n", + a.to_s(16), b.to_s(16), ref[1].to_s(16), ref[2].to_s(16), ref[0].to_s(16)) + return false + end + return false +end + +################################################################################ +# run_test_add # +################################################################################ + +def run_test_add(skip=0) + length_a_B = skip+1 + length_b_B = skip+1 + begin + $size = length_a_B + (0..16).each do |i| + a = rand(256**length_a_B) + b = rand(256**length_a_B) + v = add_test(a, b) + screen_progress(v) + v = add_test(b, a) + screen_progress(v) + end + (0..16).each do |i| + b_size = rand(length_b_B+1) + a = rand(256**length_a_B) + b = rand(256**b_size) + v = add_test(a, b) + screen_progress(v) + v = add_test(b, a) + screen_progress(v) + end + length_a_B += 1 + length_b_B += 1 + end while length_a_B<4096/8 +end + +################################################################################ +# run_test_sub # +################################################################################ + +def run_test_sub(skip = 0) + length_a_B = skip + 1 + length_b_B = skip + 1 + begin + $size = length_a_B + (0..16).each do |i| + a = rand(256 ** length_a_B) + b = rand(a + 1) + v = sub_test(a, b) + screen_progress(v) + end + (0..16).each do |i| + b_size = rand(length_b_B + 1) + a = rand(256 ** length_a_B) + b = rand(min(256 ** b_size, a + 1)) + v = sub_test(a, b) + screen_progress(v) + end + length_a_B += 1 + length_b_B += 1 + end while length_a_B < 4096 / 8 +end + + +################################################################################ +# run_test_add_scale # +################################################################################ + +def run_test_add_scale(skip=0) + length_a_B = skip+1 + length_b_B = skip+1 + begin + $size = length_a_B + (0..4).each do |i| + scales = [0, 300] + 16.times { scales << rand(301) } + scales.sort! + scales.each do |scale| + a = rand(256**length_a_B) + b = rand(256**length_a_B) + v = add_scale_test(a, b, scale) + screen_progress(v) + v = add_scale_test(b, a, scale) + screen_progress(v) + end + end + (0..4).each do |i| + scales = [0, 300] + 16.times { scales << rand(301) } + scales.sort! + scales.each do |scale| + b_size = rand(length_b_B+1)+1 + a = rand(256**length_a_B) + b = rand(256**b_size) + v = add_scale_test(a, b, scale) + screen_progress(v) + v = add_scale_test(b, a, scale) + screen_progress(v) + end + end + length_a_B += 10 + length_b_B += 10 + end while length_a_B<4096/8 +end + +def run_test_add_scale_dummy(skip=0) + length_a_B = skip+1 + length_b_B = skip+1 + begin + $size = length_a_B + (0..4).each do |i| + scales = [0, 300] + 16.times { scales << rand(301) } + scales.sort! + scales.each do |scale| + a = rand(256**length_a_B) + b = rand(256**length_a_B) + v = add_scale_test_dummy(a, b, scale) + v = add_scale_test_dummy(b, a, scale) + end + end + (0..4).each do |i| + scales = [0, 300] + 16.times { scales << rand(301) } + scales.sort! + scales.each do |scale| + b_size = rand(length_b_B+1) + a = rand(256**length_a_B) + b = rand(256**b_size) + v = add_scale_test_dummy(a, b, scale) + v = add_scale_test_dummy(b, a, scale) + end + end + length_a_B += 10 + length_b_B += 10 + end while length_a_B<4096/8 +end + +################################################################################ +# run_test_mul # +################################################################################ + +def run_test_mul(skip=0) + length_a_B = skip+1 + length_b_B = skip+1 + begin + $size = length_a_B + (0..16).each do |i| + s_a = rand(2)*2-1 + s_b = rand(2)*2-1 + a = rand(256**length_a_B) * s_a + b = rand(256**length_a_B) * s_b + v = mul_test(a, b) + screen_progress(v) + v = mul_test(b, a) + screen_progress(v) + end + (0..16).each do |i| + s_a = rand(2)-1 + s_b = rand(2)-1 + b_size = rand(length_b_B+1) + a = rand(256**length_a_B) * s_a + b = rand(256**b_size) * s_b + v = mul_test(a, b) + screen_progress(v) + v = mul_test(b, a) + screen_progress(v) + end + length_a_B += 1 + length_b_B += 1 + end while length_a_B<4096/8 +end + +################################################################################ +# run_test_mul_word # +################################################################################ + +def run_test_mul_word(skip=0) + length_a_B = skip+1 + length_b_B = skip+1 + begin + $size = length_a_B + (0..255).each do |i| + a = rand(256 ** length_a_B) + v = mul_test(a, i) + screen_progress(v) + end + length_a_B += 1 + end while length_a_B < 4096 / 8 +end + +################################################################################ +# run_test_square # +################################################################################ + +def run_test_square(skip=0) + length_a_B = skip+1 + begin + $size = length_a_B + (0..16).each do |i| + a = rand(256**length_a_B) + v = square_test(a) + screen_progress(v) + end + length_a_B += 1 + end while length_a_B<4096/8 +end + +################################################################################ +# run_test_reduce # +################################################################################ + +def run_test_reduce(skip=0) + length_a_B = skip+1 + length_b_B = skip+1 + begin + $size = length_a_B + (0..16).each do |i| + a = rand(256**length_a_B) + b = rand(256**length_a_B)+1 + v = reduce_test(a, b) + screen_progress(v) + end + (0..16).each do |i| + b_size = rand(length_b_B+1) + a = rand(256**length_a_B) + b = rand(256**b_size)+1 + v = reduce_test(a, b) + screen_progress(v) + end + length_a_B += 1 + length_b_B += 1 + end while length_a_B<4096/8 +end + +################################################################################ +# run_test_expmod # +################################################################################ + +def run_test_expmod(skip=0) + length_a_B = skip + 1 + length_b_B = skip + 1 + length_c_B = skip + 1 + begin + $size = length_a_B + (0..16).each do |i| + a = rand(256 ** length_a_B) + b = rand(256 ** length_b_B) + 1 + c = rand(256 ** length_c_B) + 1 + v = expmod_test(a, b, c) + screen_progress(v) + end + (0..16).each do |i| + b_size = rand(length_b_B+1) + a = rand(256 ** length_a_B) + b = rand(256 ** b_size) + 1 + c = rand(256 ** b_size) + 1 + v = expmod_test(a, b, c) + screen_progress(v) + end + length_a_B += 1 + length_b_B += 1 + end while length_a_B<4096/8 +end + +################################################################################ +# run_test_expmodmont # +################################################################################ + +def run_test_expmodmont(skip=0) + length_a_B = skip + 1 + length_b_B = skip + 1 + length_c_B = skip + 1 + begin + $size = length_a_B + (0..16).each do |i| + a = rand(256 ** length_a_B) + b = rand(256 ** length_b_B) + 1 + c = rand(256 ** length_c_B) / 2 * 2 +1 + v = expmod_test(a, b, c) + screen_progress(v) + end + (0..16).each do |i| + b_size = rand(length_b_B + 10) + a = rand(256 ** length_a_B) + b = rand(256 ** b_size) + 1 + c = rand(256 ** b_size) / 2 * 2 +1 + v = expmod_test(a, b, c) + screen_progress(v) + end + length_a_B += 1 + length_b_B += 1 + end while length_a_B<4096/8 +end + +################################################################################ +# run_test_mulmod # +################################################################################ + +def run_test_mulmod(skip=0) + length_a_B = skip+1 + length_b_B = skip+1 + length_c_B = skip+1 + begin + $size = length_a_B + (0..16).each do |i| + a = rand(256**length_a_B) + b = rand(256**length_b_B) + c = (rand(256**length_c_B) / 2 * 2) + 1 + a %= c + b %= c + v = mulmod_test(a, b, c) + screen_progress(v) + end + (0..16).each do |i| + b_size = rand(length_b_B+1) + a = rand(256**length_a_B) + b = rand(256**b_size) + c = (rand(256**length_c_B) / 2 * 2) + 1 + a %= c + b %= c + v = mulmod_test(a, b, c) + screen_progress(v) + end + length_a_B += 1 + length_b_B += 1 + length_c_B += 1 + end while length_a_B<4096/8 +end + +################################################################################ +# run_test_gcdext # +################################################################################ + +def run_test_gcdext(skip=0) + length_a_B = skip+1 + length_b_B = skip+1 + begin + $size = length_a_B + (0..16).each do |i| + a = rand(256**length_a_B) + b = rand(256**length_a_B)+1 + v = gcdext_test(a, b) + $logfile.flush() + screen_progress(v) + end + (0..16).each do |i| + b_size = rand(length_b_B+1) + a = rand(256**length_a_B) + b = rand(256**b_size)+1 + v = gcdext_test(a, b) + $logfile.flush() + screen_progress(v) + end + length_a_B += 1 + length_b_B += 1 + end while length_a_B<4096/8 +end + +def init_serialport(conf) + puts("serial port interface version: " + SerialPort::VERSION); + $linewidth = 64 + $linepos = 0 + $testno = 0 + params = { "baud" => conf["PORT"]["baud"].to_i, + "data_bits" => conf["PORT"]["databits"].to_i, + "stop_bits" => conf["PORT"]["stopbits"].to_i, + "parity" => SerialPort::NONE } + params["paraty"] = SerialPort::ODD if conf["PORT"]["paraty"].downcase == "odd" + params["paraty"] = SerialPort::EVEN if conf["PORT"]["paraty"].downcase == "even" + params["paraty"] = SerialPort::MARK if conf["PORT"]["paraty"].downcase == "mark" + params["paraty"] = SerialPort::SPACE if conf["PORT"]["paraty"].downcase == "space" + + puts("\nPort: "+conf["PORT"]["port"]+"@" + + params["baud"].to_s + + " " + + params["data_bits"].to_s + + conf["PORT"]["paraty"][0,1].upcase + + params["stop_bits"].to_s + + "\n") + + $sp = SerialPort.new(conf["PORT"]["port"], params) + + $sp.read_timeout = 100; # 5 minutes + $sp.flow_control = SerialPort::SOFT + + reset_system() +end + +################################################################################ +# MAIN # +################################################################################ + +opts = Getopt::Std.getopts("r:s:f:i:a:hd") + +conf = Hash.new +conf = readconfigfile("/etc/testport.conf", conf) +conf = readconfigfile("~/.testport.conf", conf) +conf = readconfigfile("testport.conf", conf) +conf = readconfigfile(opts["f"], conf) if opts["f"] + +#puts conf.inspect +init_serialport(conf) + + $max_timeout = 5 * 60 + +if opts['d'] + $debug = true +end + +if opts['r'] + random_seed = opts['r'].to_i(0) +else + random_seed = 0xdeadbeef +end + +logfilename = conf['PORT']['testlogbase']+'bigint.txt' +if File.exists?(logfilename) + i=1 + begin + logfilename = sprintf('%s%04d%s', conf['PORT']['testlogbase']+'bigint_',i,'.txt') + i+=1 + end while(File.exists?(logfilename)) + while(i>2) do + n1 = sprintf('%s%04d%s', conf['PORT']['testlogbase']+'bigint_',i-2,'.txt') + n2 = sprintf('%s%04d%s', conf['PORT']['testlogbase']+'bigint_',i-1,'.txt') + File.rename(n1, n2) +# printf("%s -> %s\n", n1, n2) + i-=1 + end + n1 = sprintf('%s%s', conf['PORT']['testlogbase'],'bigint.txt') + n2 = sprintf('%s%04d%s', conf['PORT']['testlogbase']+'bigint_',1,'.txt') + File.rename(n1, n2) + printf("%s -> %s\n", n1, n2) + logfilename = conf['PORT']['testlogbase']+'bigint.txt' +end +$logfile = File.open(logfilename, 'w') +printf("logfile: %s\n", logfilename) +$logfile.sync = true +$logfile.printf("bigint test from: %s\n", Time.now.to_s) +$logfile.printf("skip = %s\n", opts['s']) if opts['s'] +$logfile.printf("seed = 0x%X\n", random_seed) + +tests = Hash.new +tests['a'] = proc {|x| run_test_add(x) } +tests['b'] = proc {|x| run_test_sub(x) } +tests['m'] = proc {|x| run_test_mul(x) } +tests['M'] = proc {|x| run_test_mulmod(x) } +tests['n'] = proc {|x| run_test_mul_word(x) } +tests['x'] = proc {|x| run_test_add_scale(x) } +tests['s'] = proc {|x| run_test_square(x) } +tests['r'] = proc {|x| run_test_reduce(x) } +tests['e'] = proc {|x| run_test_expmod(x) } +tests['E'] = proc {|x| run_test_expmodmont(x) } +tests['g'] = proc {|x| run_test_gcdext(x) } +init_str = Hash.new +init_str['a'] = 'add-test' +init_str['b'] = 'sub-test' +init_str['x'] = 'add-scale-test' +init_str['m'] = 'mul-test' +init_str['M'] = 'mul-mont-test' +init_str['n'] = 'mul-word-test' +init_str['s'] = 'square-test' +init_str['r'] = 'reduce-test' +init_str['e'] = 'expmod-test' +init_str['E'] = 'expmod-mont-test' +init_str['g'] = 'gcdext-test' + +srand(random_seed) + +if opts['a'] + opts['a'].each_char do |x| + if tests[x] + puts init_str[x] + init_system(init_str[x]) + tests[x].call(opts['s']?opts['s'].to_i():0) + else + puts "no test defined for '#{x}'" + end + end +else + 'amsrMeE'.each_char do |x| + if tests[x] + puts init_str[x] + init_system(init_str[x]) + tests[x].call(opts['s']?opts['s'].to_i():0) + else + puts "no test defined for '#{x}'" + end + end +end +1 + +$logile.close() diff --git a/test_src/main-bigint2-test.c b/test_src/main-bigint2-test.c new file mode 100644 index 0000000..9f3f9de --- /dev/null +++ b/test_src/main-bigint2-test.c @@ -0,0 +1,561 @@ +/* main-bigint-test.c */ +/* + This file is part of the AVR-Crypto-Lib. + Copyright (C) 2008, 2009, 2010 Daniel Otte (daniel.otte@rub.de) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . +*/ +/* + * bigint test-suit + * +*/ + +#include "main-test-common.h" + +#include "noekeon.h" +#include "noekeon_prng.h" +#include "bigint2.h" +#include "bigint2_io.h" + +#include "performance_test.h" + +char *algo_name = "BigInt2"; + +#define MAX(a,b) ((a) > (b) ? (a) : (b)) +#define MIN(a,b) ((a) < (b) ? (a) : (b)) + +/***************************************************************************** + * additional validation-functions * + *****************************************************************************/ +void test_echo_bigint(void) { + bigint_t a; + cli_putstr_P(PSTR("\r\necho test\r\n")); + for (;;) { + cli_putstr_P(PSTR("\r\nenter hex number:")); + if (bigint_read_hex_echo(&a, 0)) { + cli_putstr_P(PSTR("\r\n end echo test")); + return; + } + cli_putstr_P(PSTR("\r\necho: ")); + bigint_print_hex(&a); + cli_putstr_P(PSTR("\r\n")); + free(a.wordv); + } +} + +void test_add_bigint(void){ + bigint_t a, b, c; + printf_P(PSTR("\nadd test\n")); + for (;;) { + printf_P(PSTR("\nenter a:")); + if (bigint_read_hex_echo(&a, 512)) { + printf_P(PSTR("\n end add test")); + return; + } + printf_P(PSTR("\nenter b:")); + if (bigint_read_hex_echo(&b, 512)) { + free(a.wordv); + printf_P(PSTR("\n end add test")); + return; + } + printf_P(PSTR("\n ")); + bigint_print_hex(&a); + printf_P(PSTR(" + ")); + bigint_print_hex(&b); + printf_P(PSTR(" = ")); + memset(&c, 0, sizeof(c)); + bigint_add_u(&c, &a, &b); + bigint_print_hex(&c); + cli_putstr_P(PSTR("\r\n")); + free(a.wordv); + free(b.wordv); + bigint_free(&c); + } +} + +void test_sub_bigint(void){ + bigint_t a, b, c; + printf_P(PSTR("\nadd test\n")); + for (;;) { + printf_P(PSTR("\nenter a:")); + if (bigint_read_hex_echo(&a, 512)) { + printf_P(PSTR("\n end add test")); + return; + } + printf_P(PSTR("\nenter b:")); + if (bigint_read_hex_echo(&b, 512)) { + free(a.wordv); + printf_P(PSTR("\n end add test")); + return; + } + printf_P(PSTR("\n ")); + bigint_print_hex(&a); + printf_P(PSTR(" - ")); + bigint_print_hex(&b); + printf_P(PSTR(" = ")); + memset(&c, 0, sizeof(c)); + bigint_sub_u(&c, &a, &b); + bigint_print_hex(&c); + cli_putstr_P(PSTR("\r\n")); + free(a.wordv); + free(b.wordv); + bigint_free(&c); + } +} + +#if 0 +void test_add_scale_bigint(void){ + bigint_t a, b, c; + uint16_t scale; + cli_putstr_P(PSTR("\r\nadd-scale test\r\n")); + for (;;) { + cli_putstr_P(PSTR("\r\nenter a:")); + if (bigint_read_hex_echo(&a)) { + cli_putstr_P(PSTR("\r\n end add-scale test")); + return; + } + cli_putstr_P(PSTR("\r\nenter b:")); + if (bigint_read_hex_echo(&b)) { + cli_putstr_P(PSTR("\r\n end add-scale test")); + return; + } + cli_putstr_P(PSTR("\r\nenter scale:")); + { + char str[8]; + cli_getsn_cecho(str, 7); + scale = atoi(str); + } + /* + if(bigint_read_hex_echo(&scale)){ + free(scale.wordv); + cli_putstr_P(PSTR("\r\n end add test")); + return; + } + */ + bigint_word_t *c_b; + c_b = malloc((MAX(a.length_W, b.length_W+scale) + 2) * sizeof(bigint_word_t)); + if(c_b==NULL){ + cli_putstr_P(PSTR("\n\rERROR: Out of memory!")); + free(a.wordv); + free(b.wordv); + continue; + } + c.wordv = c_b; + bigint_copy(&c, &a); + bigint_add_scale_u(&c, &b, scale); + cli_putstr_P(PSTR("\r\n ")); + bigint_print_hex(&a); + cli_putstr_P(PSTR(" + ")); + bigint_print_hex(&b); + cli_putstr_P(PSTR("<<8*")); + cli_hexdump_rev(&scale, 2); + cli_putstr_P(PSTR(" = ")); + bigint_print_hex(&c); + cli_putstr_P(PSTR("\r\n")); + free(a.wordv); + free(b.wordv); + free(c_b); + } +} +#endif + + +void test_mul_bigint(void){ + bigint_t a, b, c; + cli_putstr_P(PSTR("\r\nmul test\r\n")); + for (;;) { + cli_putstr_P(PSTR("\r\nenter a:")); + if (bigint_read_hex_echo(&a, 0)) { + cli_putstr_P(PSTR("\r\n end mul test")); + return; + } + cli_putstr_P(PSTR("\r\nenter b:")); + if (bigint_read_hex_echo(&b, 0)) { + free(a.wordv); + cli_putstr_P(PSTR("\r\n end mul test")); + return; + } + cli_putstr_P(PSTR("\r\n ")); + bigint_print_hex(&a); + cli_putstr_P(PSTR(" * ")); + bigint_print_hex(&b); + cli_putstr_P(PSTR(" = ")); + bigint_word_t *c_b; + c_b = malloc((MAX(a.length_W, b.length_W) + 1) * 2 * sizeof(bigint_word_t)); + if (c_b==NULL) { + cli_putstr_P(PSTR("\n\rERROR: Out of memory!")); + free(a.wordv); + free(b.wordv); + continue; + } + c.wordv = c_b; + bigint_mul_schoolbook(&c, &a, &b); + bigint_print_hex(&c); + cli_putstr_P(PSTR("\r\n")); + free(a.wordv); + free(b.wordv); + free(c_b); + } +} + +#if 0 +void test_mul_mont_bigint(void){ + bigint_t a, b, c, a_, b_, m_, res; + bigint_length_t s; + cli_putstr_P(PSTR("\r\nmul-mont test ( (a * b) % c )\r\n")); + for (;;) { + cli_putstr_P(PSTR("\r\nenter a:")); + if (bigint_read_hex_echo(&a)) { + cli_putstr_P(PSTR("\r\n end mul test")); + return; + } + cli_putstr_P(PSTR("\r\nenter b:")); + if (bigint_read_hex_echo(&b)) { + free(a.wordv); + cli_putstr_P(PSTR("\r\n end mul test")); + return; + } + cli_putstr_P(PSTR("\r\nenter c:")); + if (bigint_read_hex_echo(&c)) { + free(a.wordv); + free(b.wordv); + cli_putstr_P(PSTR("\r\n end mul test")); + return; + } + s = c.length_W; + cli_putstr_P(PSTR("\r\n (")); + bigint_print_hex(&a); + cli_putstr_P(PSTR(" * ")); + bigint_print_hex(&b); + cli_putstr_P(PSTR(") % ")); + bigint_print_hex(&c); + cli_putstr_P(PSTR(" = ")); + bigint_word_t res_w[s], a_w_[s], b_w_[s], m_w_[s + 1]; + res.wordv = res_w; + a_.wordv = a_w_; + b_.wordv = b_w_; + m_.wordv = m_w_; + bigint_mont_gen_m_(&m_, &c); + bigint_mont_trans(&a_, &a, &c); + bigint_mont_trans(&b_, &b, &c); + bigint_mont_mul(&res, &a_, &b_, &c, &m_); + bigint_mont_red(&res, &res, &c, &m_); + bigint_print_hex(&res); + putchar('\n'); + free(a.wordv); + free(b.wordv); + free(c.wordv); + } +} +#endif + +void test_mul_word_bigint(void){ + bigint_t a, b; + bigint_word_t *t; + cli_putstr_P(PSTR("\r\nmul test\r\n")); + for (;;) { + cli_putstr_P(PSTR("\r\nenter a:")); + if (bigint_read_hex_echo(&a, 0)) { + cli_putstr_P(PSTR("\r\n end mul test")); + return; + } + cli_putstr_P(PSTR("\r\nenter b:")); + if (bigint_read_hex_echo(&b, 0)) { + free(a.wordv); + cli_putstr_P(PSTR("\r\n end mul test")); + return; + } + cli_putstr_P(PSTR("\r\n ")); + bigint_print_hex(&a); + cli_putstr_P(PSTR(" * ")); + bigint_print_hex(&b); + cli_putstr_P(PSTR(" = ")); + + if (b.length_W > 1) { + free(a.wordv); + free(b.wordv); + cli_putstr_P(PSTR("\r\n end mul test")); + } + + t = realloc(a.wordv, (a.length_W + 3) * sizeof(bigint_word_t)); + if (t == NULL) { + cli_putstr_P(PSTR("\n\rERROR: Out of memory!")); + free(a.wordv); + free(b.wordv); + continue; + } + a.wordv = t; + bigint_mul_word(&a, &a, b.wordv[0]); + bigint_print_hex(&a); + cli_putstr_P(PSTR("\r\n")); + free(a.wordv); + free(b.wordv); + } +} + +void test_square_bigint(void){ + bigint_t a, c; + cli_putstr_P(PSTR("\r\nsquare test\r\n")); + for(;;){ + cli_putstr_P(PSTR("\r\nenter a:")); + if(bigint_read_hex_echo(&a, 0)){ + cli_putstr_P(PSTR("\r\n end square test")); + return; + } + cli_putstr_P(PSTR("\r\n ")); + bigint_print_hex(&a); + cli_putstr_P(PSTR("**2 = ")); + bigint_word_t *c_b; + c_b = malloc(a.length_W * 2 * sizeof(bigint_word_t)); + if(c_b == NULL){ + cli_putstr_P(PSTR("\n\rERROR: Out of memory!")); + free(a.wordv); + continue; + } + c.wordv = c_b; + bigint_square(&c, &a); + bigint_print_hex(&c); + cli_putstr_P(PSTR("\r\n")); + free(a.wordv); + free(c_b); + } +} + +void test_reduce_bigint(void){ + bigint_t a, b, c; + cli_putstr_P(PSTR("\r\nreduce test\r\n")); + for (;;) { + cli_putstr_P(PSTR("\r\nenter a:")); + if (bigint_read_hex_echo(&a, 0)) { + cli_putstr_P(PSTR("\r\n end reduce test")); + return; + } + cli_putstr_P(PSTR("\r\nenter b:")); + if (bigint_read_hex_echo(&b, 0)) { + free(a.wordv); + cli_putstr_P(PSTR("\r\n end reduce test")); + return; + } + cli_putstr_P(PSTR("\r\n ")); + bigint_print_hex(&a); + cli_putstr_P(PSTR(" % ")); + bigint_print_hex(&b); + cli_putstr_P(PSTR(" = ")); + memset(&c, 0, sizeof(c)); + bigint_divide(NULL, &c, &a, &b); + bigint_print_hex(&c); + cli_putstr_P(PSTR("\r\n")); + bigint_free(&c); + bigint_free(&b); + bigint_free(&a); + } +} + +#if 0 +/* d = a**b % c */ +void test_expmod_bigint(void){ + bigint_t a, b, c, d; + bigint_word_t *d_b; + cli_putstr_P(PSTR("\r\nexpnonentiation-modulo test\r\n")); + for (;;) { + cli_putstr_P(PSTR("\r\nenter a:")); + if (bigint_read_hex_echo(&a)) { + cli_putstr_P(PSTR("\r\n end expmod test")); + return; + } + cli_putstr_P(PSTR("\r\nenter b:")); + if (bigint_read_hex_echo(&b)) { + free(a.wordv); + cli_putstr_P(PSTR("\r\n end expmod test")); + return; + } + cli_putstr_P(PSTR("\r\nenter c:")); + if (bigint_read_hex_echo(&c)) { + free(a.wordv); + free(b.wordv); + cli_putstr_P(PSTR("\r\n end expmod test")); + return; + } + d_b = malloc(c.length_W * sizeof(bigint_word_t)); + if(d_b==NULL){ + cli_putstr_P(PSTR("\n\rERROR: Out of memory!")); + free(a.wordv); + free(b.wordv); + free(c.wordv); + continue; + } + d.wordv = d_b; + cli_putstr_P(PSTR("\r\n ")); + bigint_print_hex(&a); + cli_putstr_P(PSTR("**")); + bigint_print_hex(&b); + cli_putstr_P(PSTR(" % ")); + bigint_print_hex(&c); + cli_putstr_P(PSTR(" = ")); + bigint_expmod_u_sam(&d, &a, &b, &c); + bigint_print_hex(&d); + cli_putstr_P(PSTR("\r\n")); + free(a.wordv); + free(b.wordv); + free(c.wordv); + free(d.wordv); + + } +} + +/* d = a**b % c */ +void test_expmod_mont_bigint(void){ + bigint_t a, b, c, d; + bigint_word_t *d_b; + cli_putstr_P(PSTR("\r\nexpnonentiation-modulo-montgomory test\r\n")); + for (;;) { + cli_putstr_P(PSTR("\r\nenter a:")); + if (bigint_read_hex_echo(&a)) { + cli_putstr_P(PSTR("\r\n end expmod test")); + return; + } + cli_putstr_P(PSTR("\r\nenter b:")); + if (bigint_read_hex_echo(&b)) { + free(a.wordv); + cli_putstr_P(PSTR("\r\n end expmod test")); + return; + } + cli_putstr_P(PSTR("\r\nenter c:")); + if (bigint_read_hex_echo(&c)) { + free(a.wordv); + free(b.wordv); + cli_putstr_P(PSTR("\r\n end expmod test")); + return; + } + d_b = malloc(c.length_W * sizeof(bigint_word_t)); + if (d_b == NULL) { + cli_putstr_P(PSTR("\n\rERROR: Out of memory!")); + free(a.wordv); + free(b.wordv); + free(c.wordv); + continue; + } + d.wordv = d_b; + cli_putstr_P(PSTR("\r\n ")); + bigint_print_hex(&a); + cli_putstr_P(PSTR("**")); + bigint_print_hex(&b); + cli_putstr_P(PSTR(" % ")); + bigint_print_hex(&c); + cli_putstr_P(PSTR(" = ")); + bigint_expmod_u_mont_sam(&d, &a, &b, &c); + bigint_print_hex(&d); + cli_putstr_P(PSTR("\r\n")); + free(a.wordv); + free(b.wordv); + free(c.wordv); + free(d.wordv); + + } +} + +#endif + +void test_gcdext_bigint(void){ + bigint_t a, b, c, d, e; + cli_putstr_P(PSTR("\r\ngcdext test\r\n")); + for (;;) { + cli_putstr_P(PSTR("\r\nenter a:")); + if (bigint_read_hex_echo(&a, 0)) { + cli_putstr_P(PSTR("\r\n end gcdext test")); + return; + } + cli_putstr_P(PSTR("\r\nenter b:")); + if (bigint_read_hex_echo(&b, 0)) { + bigint_free(&a); + cli_putstr_P(PSTR("\r\n end gcdext test")); + return; + } + + memset(&c, 0, sizeof(c)); + memset(&d, 0, sizeof(d)); + memset(&e, 0, sizeof(e)); + cli_putstr_P(PSTR("\r\n gcdext( ")); + bigint_print_hex(&a); + cli_putstr_P(PSTR(", ")); + bigint_print_hex(&b); + cli_putstr_P(PSTR(") => ")); + bigint_gcdext(&c, &d, &e, &a, &b); + cli_putstr_P(PSTR("a = ")); + bigint_print_hex(&d); + cli_putstr_P(PSTR("; b = ")); + bigint_print_hex(&e); + cli_putstr_P(PSTR("; gcd = ")); + bigint_print_hex(&c); + + cli_putstr_P(PSTR("\r\n")); + bigint_free(&a); + bigint_free(&b); + bigint_free(&c); + bigint_free(&d); + bigint_free(&e); + } +} + +void testrun_performance_bigint(void){ + +} +/***************************************************************************** + * main * + *****************************************************************************/ + +const char echo_test_str[] PROGMEM = "echo-test"; +const char add_test_str[] PROGMEM = "add-test"; +const char sub_test_str[] PROGMEM = "sub-test"; +const char add_scale_test_str[] PROGMEM = "add-scale-test"; +const char mul_test_str[] PROGMEM = "mul-test"; +const char mul_mont_test_str[] PROGMEM = "mul-mont-test"; +const char mul_word_test_str[] PROGMEM = "mul-word-test"; +const char square_test_str[] PROGMEM = "square-test"; +const char reduce_test_str[] PROGMEM = "reduce-test"; +const char expmod_test_str[] PROGMEM = "expmod-test"; +const char expmod_mont_test_str[] PROGMEM = "expmod-mont-test"; +const char gcdext_test_str[] PROGMEM = "gcdext-test"; +const char quick_test_str[] PROGMEM = "quick-test"; +const char performance_str[] PROGMEM = "performance"; +const char echo_str[] PROGMEM = "echo"; + +const cmdlist_entry_t cmdlist[] PROGMEM = { + { add_test_str, NULL, test_add_bigint }, + { sub_test_str, NULL, test_sub_bigint }, +// { add_scale_test_str, NULL, test_add_scale_bigint }, + { mul_test_str, NULL, test_mul_bigint }, +// { mul_mont_test_str, NULL, test_mul_mont_bigint }, + { mul_word_test_str, NULL, test_mul_word_bigint }, + { square_test_str, NULL, test_square_bigint }, + { reduce_test_str, NULL, test_reduce_bigint }, +// { expmod_test_str, NULL, test_expmod_bigint }, +// { expmod_mont_test_str, NULL, test_expmod_mont_bigint }, + { gcdext_test_str, NULL, test_gcdext_bigint }, +// { quick_test_str, NULL, test_gcdext_simple }, + { echo_test_str, NULL, test_echo_bigint }, + { performance_str, NULL, testrun_performance_bigint }, + { echo_str, (void*)1, (void_fpt)echo_ctrl }, + { NULL, NULL, NULL } +}; + +int main (void){ + main_setup(); + int_realloc = realloc; + int_free = free; + for(;;){ + welcome_msg(algo_name); + cmd_interface(cmdlist); + } +}