andre@0: /* This Source Code Form is subject to the terms of the Mozilla Public andre@0: * License, v. 2.0. If a copy of the MPL was not distributed with this andre@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ andre@0: andre@0: #include "ecl-priv.h" andre@0: andre@0: /* Returns 2^e as an integer. This is meant to be used for small powers of andre@0: * two. */ andre@0: int andre@0: ec_twoTo(int e) andre@0: { andre@0: int a = 1; andre@0: int i; andre@0: andre@0: for (i = 0; i < e; i++) { andre@0: a *= 2; andre@0: } andre@0: return a; andre@0: } andre@0: andre@0: /* Computes the windowed non-adjacent-form (NAF) of a scalar. Out should andre@0: * be an array of signed char's to output to, bitsize should be the number andre@0: * of bits of out, in is the original scalar, and w is the window size. andre@0: * NAF is discussed in the paper: D. Hankerson, J. Hernandez and A. andre@0: * Menezes, "Software implementation of elliptic curve cryptography over andre@0: * binary fields", Proc. CHES 2000. */ andre@0: mp_err andre@0: ec_compute_wNAF(signed char *out, int bitsize, const mp_int *in, int w) andre@0: { andre@0: mp_int k; andre@0: mp_err res = MP_OKAY; andre@0: int i, twowm1, mask; andre@0: andre@0: twowm1 = ec_twoTo(w - 1); andre@0: mask = 2 * twowm1 - 1; andre@0: andre@0: MP_DIGITS(&k) = 0; andre@0: MP_CHECKOK(mp_init_copy(&k, in)); andre@0: andre@0: i = 0; andre@0: /* Compute wNAF form */ andre@0: while (mp_cmp_z(&k) > 0) { andre@0: if (mp_isodd(&k)) { andre@0: out[i] = MP_DIGIT(&k, 0) & mask; andre@0: if (out[i] >= twowm1) andre@0: out[i] -= 2 * twowm1; andre@0: andre@0: /* Subtract off out[i]. Note mp_sub_d only works with andre@0: * unsigned digits */ andre@0: if (out[i] >= 0) { andre@0: mp_sub_d(&k, out[i], &k); andre@0: } else { andre@0: mp_add_d(&k, -(out[i]), &k); andre@0: } andre@0: } else { andre@0: out[i] = 0; andre@0: } andre@0: mp_div_2(&k, &k); andre@0: i++; andre@0: } andre@0: /* Zero out the remaining elements of the out array. */ andre@0: for (; i < bitsize + 1; i++) { andre@0: out[i] = 0; andre@0: } andre@0: CLEANUP: andre@0: mp_clear(&k); andre@0: return res; andre@0: andre@0: }