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