3 Copyright (C) 2013, 2014 Niels Möller
5 This file is part of GNU Nettle.
7 GNU Nettle is free software: you can redistribute it and/or
8 modify it under the terms of either:
10 * the GNU Lesser General Public License as published by the Free
11 Software Foundation; either version 3 of the License, or (at your
12 option) any later version.
16 * the GNU General Public License as published by the Free
17 Software Foundation; either version 2 of the License, or (at your
18 option) any later version.
20 or both in parallel, as here.
22 GNU Nettle is distributed in the hope that it will be useful,
23 but WITHOUT ANY WARRANTY; without even the implied warranty of
24 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
25 General Public License for more details.
27 You should have received copies of the GNU General Public License and
28 the GNU Lesser General Public License along with this program. If
29 not, see http://www.gnu.org/licenses/.
32 /* Development of Nettle's ECC support was funded by the .SE Internet Fund. */
40 #include "ecc-internal.h"
43 cnd_neg (int cnd, mp_limb_t *rp, const mp_limb_t *ap, mp_size_t n)
45 mp_limb_t cy = (cnd != 0);
49 for (i = 0; i < n; i++)
51 mp_limb_t r = (ap[i] ^ mask) + cy;
57 /* Compute a^{-1} mod m, with running time depending only on the size.
58 Returns zero if a == 0 (mod m), to be consistent with a^{phi(m)-1}.
59 Also needs (m+1)/2, and m must be odd.
61 Needs 2n limbs available at rp, and 2n additional scratch limbs.
64 /* FIXME: Could use mpn_sec_invert (in GMP-6), but with a bit more
65 scratch need since it doesn't precompute (m+1)/2. */
67 ecc_mod_inv (const struct ecc_modulo *m,
68 mp_limb_t *vp, const mp_limb_t *in_ap,
72 #define bp (scratch + n)
75 mp_size_t n = m->size;
76 /* Avoid the mp_bitcnt_t type for compatibility with older GMP
82 a = u * orig_a (mod m)
83 b = v * orig_a (mod m)
85 and b odd at all times. Initially,
94 mpn_zero (up+1, n - 1);
95 mpn_copyi (bp, m->m, n);
97 mpn_copyi (ap, in_ap, n);
99 for (i = m->bit_size + GMP_NUMB_BITS * n; i-- > 0; )
101 mp_limb_t odd, swap, cy;
103 /* Always maintain b odd. The logic of the iteration is as
108 if (underflow from a-b)
110 b += a, assigns old a
118 if (underflow from a - b)
121 if (underflow from u - v)
125 if (a one bit was shifted out)
128 As long as a > 0, the quantity
130 (bitsize of a) + (bitsize of b)
132 is reduced by at least one bit per iteration, hence after
133 (bit_size of orig_a) + (bit_size of m) - 1 iterations we
134 surely have a = 0. Then b = gcd(orig_a, m) and if b = 1 then
135 also v = orig_a^{-1} (mod m)
141 swap = cnd_sub_n (odd, ap, bp, n);
142 cnd_add_n (swap, bp, ap, n);
143 cnd_neg (swap, ap, ap, n);
145 cnd_swap (swap, up, vp, n);
146 cy = cnd_sub_n (odd, up, vp, n);
147 cy -= cnd_add_n (cy, up, m->m, n);
149 cy = mpn_rshift (ap, ap, n, 1);
151 cy = mpn_rshift (up, up, n, 1);
152 cy = cnd_add_n (cy, up, m->mp1h, n);
155 assert ( (ap[0] | ap[n-1]) == 0);