【发布时间】:2018-03-27 11:47:13
【问题描述】:
我目前正在尝试为一个学校项目实施 RSA 加密算法。在研究之后,我认为生成我自己的素数也会很有趣。我正在使用 gmp 库来存储数字。
一些消息来源说这通常是通过使用筛分方法然后对数字进行概率测试来完成的,在我的例子中,我从费马测试开始:
a^(potPrime-1) ≡ 1 (mod potPrime)
我遇到的问题是计算“a^(potPrime-1)”,我在 gmp 库中找不到可以计算 mpz_t 幂另一个 mpz_t 的函数,所以我编写了自己的函数,这确实是一段时间一直循环,直到我将数字乘以所需的次数。 这适用于小数字,但是当 potPrime 可以达到 2^2048 时,这个解决方案是不够的。
有谁知道我该如何解决这个问题?这是 Fermat 测试的代码:
int fermatTest(mpz_t potPrime, mpz_t a) //The fermat test is a mathimatical test that will determine if a number is potentialy prime.
{ //a is a random number between ]1;p-1[
int result;
mpz_t potPrimeMin1,aSqPotPrimeMin1,val1; //decalre mpz type value, val1=1
mpz_init(potPrimeMin1); //initialises the mpz type value of the number containing potPrime minus 1
mpz_init(aSqPotPrimeMin1);//value of a^(p-1)
mpz_init(val1); //a mpz type var where val1 is allways 1
mpz_set_ui(val1,1);
mpz_sub_ui(potPrimeMin1,potPrime,1); //subtracts 1 from potPrime and stores it in potPrimeMin1
mympz_pow(aSqPotPrimeMin1,a,potPrimeMin1);//aSqPotPrimeMin1=a^potPrimeMin1
result = mpz_congruent_p(aSqPotPrimeMin1,val1,potPrime); //test checks if a^(potPrime-1) ≡ 1 (mod potPrime) - returns non zero if congruent
//returns non zero if operation is true, 0 if not
mpz_clear(potPrimeMin1);//frees the variables used
mpz_clear(aSqPotPrimeMin1);
mpz_clear(val1);
return result;
}
这是 pow 函数的代码:
int mympz_pow(mpz_t result, mpz_t base, mpz_t power)
{
mpz_t i;
mpz_init(i);
mpz_set_ui(i,1);
mpz_set(result,base);
//mpzPrint("1",result);
while(mpz_cmp(i,power) < 0)
{
mpz_mul(result,result,base);
//mpzPrint("2",result);
mpz_add_ui(i,i,1);
mpzPrint("pow",power);
mpzPrint("i",i);
}
//mpzPrint("3",result);
mpz_clear(i);
return 1;
}
【问题讨论】:
-
如果你必须自己做,你应该使用重复平方而不是重复乘法。
-
计算
pow,注意2^(2k) = 2^k * 2^k。 -
谢谢,我会调查的
-
如果您对更多算法输入感兴趣,请查看en.wikipedia.org/wiki/Exponentiation_by_squaring