+/******************************************************************************/
+
+void bigint_changeendianess(bigint_t *a){
+ uint8_t t, *p, *q;
+ p = (uint8_t*)a->wordv;
+ q = p + a->length_W * sizeof(bigint_word_t) - 1;
+ while(p < q){
+ t = *p;
+ *p = *q;
+ *q = t;
+ ++p; --q;
+ }
+}
+
+/******************************************************************************/
+
+void bigint_mul_word_u(bigint_t *a, bigint_word_t b){
+ bigint_wordplus_t c0 = 0, c1 = 0;
+ bigint_length_t i;
+
+ if(b == 0){
+ bigint_set_zero(a);
+ return;
+ }
+
+ for(i = 0; i < a->length_W; ++i){
+ c1 = ((bigint_wordplus_t)(a->wordv[i])) * ((bigint_wordplus_t)b);
+ c1 += c0;
+ a->wordv[i] = (bigint_word_t)c1;
+ c0 = c1 >> BIGINT_WORD_SIZE;
+ }
+ if(c0){
+ a->wordv[a->length_W] = (bigint_word_t)c0;
+ a->length_W += 1;
+ }
+ bigint_adjust(a);
+}
+
+/******************************************************************************/
+#if 1
+
+void bigint_clip(bigint_t *dest, bigint_length_t length_W){
+ if(dest->length_W > length_W){
+ dest->length_W = length_W;
+ }
+ bigint_adjust(dest);
+}
+/******************************************************************************/
+
+/*
+ * m_ = m * m'[0]
+ * dest = (a * b) % m (?)
+ */
+
+void bigint_mont_mul(bigint_t *dest, const bigint_t *a, const bigint_t *b, const bigint_t *m, const bigint_t *m_){
+ const bigint_length_t s = MAX(MAX(a->length_W, b->length_W), m->length_W);
+ bigint_t u, t;
+
+ bigint_length_t i;
+
+ if (a->length_W == 0 || b->length_W == 0) {
+ bigint_set_zero(dest);
+ return;
+ }
+ ALLOC_BIGINT_WORDS(u_w, s + 2);
+ ALLOC_BIGINT_WORDS(t_w, s + 2);
+ u.wordv = u_w;
+ u.info = 0;
+ u.length_W = 0;
+ t.wordv = t_w;
+ for (i = 0; i < a->length_W; ++i) {
+ bigint_copy(&t, b);
+ bigint_mul_word_u(&t, a->wordv[i]);
+ bigint_add_u(&u, &u, &t);
+ bigint_copy(&t, m_);
+ if (u.length_W != 0) {
+ bigint_mul_word_u(&t, u.wordv[0]);
+ bigint_add_u(&u, &u, &t);
+ }
+ bigint_shiftright_1word(&u);
+ }
+ for (; i < s; ++i) {
+ bigint_copy(&t, m_);
+ if (u.length_W != 0) {
+ bigint_mul_word_u(&t, u.wordv[0]);
+ bigint_add_u(&u, &u, &t);
+ }
+ bigint_shiftright_1word(&u);
+ }
+ bigint_reduce(&u, m);
+ bigint_copy(dest, &u);
+ FREE(t_w);
+ FREE(u_w);
+}
+
+/******************************************************************************/