int mpl_shr(mpl_int *a, unsigned int nr) { _mpl_int_t *dst, *src; unsigned int nbits, ndigs; int i, n; if (nr == 0 || mpl_iszero(a)) return MPL_OK; if (nr >= mpl_nr_bits(a)) { mpl_zero(a); return MPL_OK; } ndigs = nr / MPL_INT_BITS; nbits = nr % MPL_INT_BITS; n = a->top + 1 - ndigs; dst = a->dig; src = a->dig + ndigs; if (nbits > 0) { _mpl_int_t mask, shift; mask = (~(_mpl_int_t)0 & MPL_INT_MASK) >> (MPL_INT_BITS - nbits); shift = MPL_INT_BITS - nbits; for (i = 1; i < n; i++) { *dst = *src >> nbits; *dst |= (*(src+1) & mask) << shift; ++dst; ++src; } *dst = *src >> nbits; } else {
int mpl_mod_exp(mpl_int *c, const mpl_int *a, const mpl_int *y, const mpl_int *b) { mpl_int w[MPL_MODEXP_STACK]; mpl_int e, s, mu, z; _mpl_int_t *dp, buffer; int i, k, nbits, rc; int do_single; unsigned int mask, x, n, tmp, cnt; if ((rc = mpl_initv(&e, &s, &mu, &z, NULL)) != MPL_OK) return rc; if (mpl_isneg(y)) { if ((rc = mpl_mod_inv(&z, a, b)) != MPL_OK) goto end; } else { if ((rc = mpl_copy(&z, a)) != MPL_OK) goto end; } n = mpl_nr_bits(y); if (n <= 7) k = 2; else if (n <= 36) k = 3; else if (n <= 140) k = 4; else if (n <= 450) k = 5; else if (n <= 1303) k = 6; else if (n <= 3529) k = 7; else k = 8; cnt = 0; for (i = 0; i < 1 << (k-1); i++) { rc = mpl_init(&w[i]); if (rc != MPL_OK) { for (i = 0; i < cnt; i++) mpl_clear(&w[i]); goto end; } ++cnt; } /* reduce Z */ rc = mpl_div(NULL, &z, &z, b); if (rc != MPL_OK) goto err; /* e = a */ rc = mpl_copy(&e, &z); if (rc != MPL_OK) goto err; /* c = 1 */ mpl_set_one(&s); /* prepare reduction constant */ rc = mpl_reduce_barrett_setup(&mu, b); if (rc != MPL_OK) goto err; /* e = a^{2^(k-1)} */ for (i = 0; i < k-1; i++) { rc = mpl_sqr(&e, &e); if (rc != MPL_OK) goto err; rc = mpl_reduce_barrett(&e, &e, b, &mu); if (rc != MPL_OK) goto err; } /* Now fill precomputed table. */ rc = mpl_copy(&w[0], &e); if (rc != MPL_OK) goto err; for (i = 1; i < 1 << (k-1); i++) { /* w[i] = (w[i-1] * a) mod b */ rc = mpl_mul(&w[i], &w[i-1], &z); if (rc != MPL_OK) goto err; rc = mpl_reduce_barrett(&w[i], &w[i], b, &mu); if (rc != MPL_OK) goto err; } buffer = nbits = do_single = cnt = 0; /* Count bits of the topmost MP integer digit. */ dp = y->dig + y->top; tmp = *dp; for (cnt = 0; tmp > 0; cnt++) tmp >>= 1; nbits = cnt; buffer = *dp--; /* Precalculated window mask. */ mask = (1 << k) - 1; while (n > 0) { unsigned int left, xmask; if (nbits == 0) { buffer = *dp--; nbits = MPL_INT_BITS; } /* Check most significant bit of the bit buffer. */ if ((buffer & (1 << (nbits-1))) == 0) { /* c = c^2 mod b */ rc = mpl_sqr(&s, &s); if (rc != MPL_OK) goto err; rc = mpl_reduce_barrett(&s, &s, b, &mu); if (rc != MPL_OK) goto err; --nbits; --n; continue; } if (nbits >= k) { /* We have enough bits in the buffer to fill window. */ x = (buffer & (mask << (nbits-k))) >> (nbits-k); nbits -= k; n -= k; } else {