Example #1
0
static int addi(void *a, unsigned long b, void *c)
{
	LTC_ARGCHK(a != NULL);
	LTC_ARGCHK(c != NULL);
	if (b > (unsigned long) UINT32_MAX) {
		return CRYPT_INVALID_ARG;
	}
	mpa_add_word((mpanum) c, (const mpanum) a, b, external_mem_pool);
	return CRYPT_OK;
}
Example #2
0
/*------------------------------------------------------------
 *
 *  primality_test_miller_rabin
 *
 */
static int primality_test_miller_rabin(mpanum n, int conf_level,
				      mpa_scratch_mem pool)
{
	int result;
	bool proof_version;
	static const int32_t proof_a[7] = { 2, 3, 5, 7, 11, 13, 17 };
	int cnt;
	int idx;
	int t;
	int e = 0;
	int cmp_one;
	mpanum a;
	mpanum q;
	mpanum n_minus_1;
	mpanum b;
	mpanum r_modn;
	mpanum r2_modn;
	mpa_word_t n_inv;

	mpa_alloc_static_temp_var(&r_modn, pool);
	mpa_alloc_static_temp_var(&r2_modn, pool);

	if (mpa_compute_fmm_context(n, r_modn, r2_modn, &n_inv, pool) == -1) {
		result = DEF_COMPOSITE;
		goto cleanup_short;
	}

	mpa_alloc_static_temp_var(&a, pool);
	mpa_alloc_static_temp_var(&q, pool);
	mpa_alloc_static_temp_var(&n_minus_1, pool);
	mpa_alloc_static_temp_var(&b, pool);

	proof_version =
	    (mpa_cmp(n, (mpanum) &const_miller_rabin_proof_limit) < 0);

	if (proof_version)
		cnt = 7;
	else	/* MR has 1/4 chance in failing a composite */
		cnt = (conf_level + 1) / 2;

	mpa_sub_word(n_minus_1, n, 1, pool);
	mpa_set(q, n_minus_1);
	t = 0;
	/* calculate q such that n - 1 = 2^t * q where q is odd */
	while (mpa_is_even(q)) {
		mpa_shift_right(q, q, 1);
		t++;
	}

	result = PROB_PRIME;
	for (idx = 0; idx < cnt && result == PROB_PRIME; idx++) {
		if (proof_version) {
			mpa_set_S32(a, proof_a[idx]);
			if (mpa_cmp(n, a) == 0) {
				result = DEF_PRIME;
				continue;
			}
		} else {
			/*
			 * Get random a, 1 < a < N by
			 * asking for a random in range 0 <= x < N - 2
			 * and then add 2 to it.
			 */
			mpa_sub_word(n_minus_1, n_minus_1, 1, pool);
			/* n_minus_1 is now N - 2 ! */
			mpa_get_random(a, n_minus_1);
			mpa_add_word(n_minus_1, n_minus_1, 1, pool);
			/* and a is now 2 <= a < N */
			mpa_add_word(a, a, 2, pool);
		}

		mpa_exp_mod(b, a, q, n, r_modn, r2_modn, n_inv, pool);
		e = 0;

inner_loop:
		cmp_one = mpa_cmp_short(b, 1);
		if ((cmp_one == 0) && (e > 0)) {
			result = DEF_COMPOSITE;
			continue;
		}

		if ((mpa_cmp(b, n_minus_1) == 0) ||
		    ((cmp_one == 0) && (e == 0))) {
			/* probably prime, try another a */
			continue;
		}

		e++;
		if (e < t) {
			mpa_exp_mod(b, b, (mpanum) &const_two, n, r_modn,
				    r2_modn, n_inv, pool);
			goto inner_loop;
		}
		result = DEF_COMPOSITE;
	}

	if (result == PROB_PRIME && proof_version)
		result = DEF_PRIME;

	mpa_free_static_temp_var(&a, pool);
	mpa_free_static_temp_var(&q, pool);
	mpa_free_static_temp_var(&n_minus_1, pool);
	mpa_free_static_temp_var(&b, pool);
cleanup_short:
	mpa_free_static_temp_var(&r_modn, pool);
	mpa_free_static_temp_var(&r2_modn, pool);

	return result;
}