3 Copyright (C) 2013 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"
42 /* Computes r mod m, input 2*m->size, output m->size. */
44 ecc_mod (const struct ecc_modulo *m, mp_limb_t *rp)
47 mp_size_t mn = m->size;
48 mp_size_t bn = m->B_size;
49 mp_size_t sn = mn - bn;
56 /* FIXME: Could use mpn_addmul_2. */
57 /* Eliminate sn limbs at a time */
58 if (m->B[bn-1] < ((mp_limb_t) 1 << (GMP_NUMB_BITS - 1)))
60 /* Multiply sn + 1 limbs at a time, so we get a mn+1 limb
61 product. Then we can absorb the carry in the high limb */
62 while (rn > 2 * mn - bn)
66 for (i = 0; i <= sn; i++)
67 rp[rn+i-1] = mpn_addmul_1 (rp + rn - mn - 1 + i, m->B, bn, rp[rn+i-1]);
68 rp[rn-1] = rp[rn+sn-1]
69 + mpn_add_n (rp + rn - sn - 1, rp + rn - sn - 1, rp + rn - 1, sn);
75 while (rn >= 2 * mn - bn)
79 for (i = 0; i < sn; i++)
80 rp[rn+i] = mpn_addmul_1 (rp + rn - mn + i, m->B, bn, rp[rn+i]);
82 hi = mpn_add_n (rp + rn - sn, rp + rn - sn, rp + rn, sn);
83 hi = cnd_add_n (hi, rp + rn - mn, m->B, mn);
93 for (i = 0; i < sn; i++)
94 rp[mn+i] = mpn_addmul_1 (rp + i, m->B, bn, rp[mn+i]);
96 hi = mpn_add_n (rp + bn, rp + bn, rp + mn, sn);
97 hi = sec_add_1 (rp + bn + sn, rp + bn + sn, mn - bn - sn, hi);
100 shift = m->size * GMP_NUMB_BITS - m->bit_size;
103 /* Combine hi with top bits, add in */
104 hi = (hi << shift) | (rp[mn-1] >> (GMP_NUMB_BITS - shift));
105 rp[mn-1] = (rp[mn-1] & (((mp_limb_t) 1 << (GMP_NUMB_BITS - shift)) - 1))
106 + mpn_addmul_1 (rp, m->B_shifted, mn-1, hi);
110 hi = cnd_add_n (hi, rp, m->B_shifted, mn);