Blame nss/lib/freebl/ecl/ec_naf.c

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