任务详情
0.在openEuler(推荐)或Ubuntu或Windows(不推荐)中完成下面任务
1.利用大整数库(GMP或者OpenSSL),参考《密码工程》p113伪代码实现 2.GenerateLargePrime 函数(10‘)
3.在测试代码中产生一个在范围l = 2^255至u = 2^256-1内的素数。(5‘)
4.用OpenSSL验证你产生的素数是不是正确(5’)
提交代码和运行结果截图
测试
echo "2^255" | bc
57896044618658097711785492504343953926634992332820282019728792003956\
564819968
echo "2^256-1" | bc
11579208923731619542357098500868790785326998466564056403945758400791\
3129639935
代码
#include <gmp.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Generate a random large prime number between lower and upper bounds
void GenerateLargePrime(mpz_t p, mpz_t l, mpz_t u) {
mpz_t temp;
mpz_init(temp);
gmp_randstate_t state;
gmp_randinit_default(state);
gmp_randseed_ui(state, time(NULL));
do {
mpz_urandomm(temp, state, u); // Generate a random number between 0 and u
mpz_add(temp, temp, l); // Add l to the random number to get a number between l and u
mpz_nextprime(p, temp); // Find the next prime number after temp
} while (mpz_cmp(p, u) > 0); // Repeat until the prime number is within the range [l, u]
mpz_clear(temp);
gmp_randclear(state);
}
int main() {
mpz_t l, u, p;
mpz_init(l);
mpz_init(u);
mpz_init(p);
mpz_set_str(l, "57896044618658097711785492504343953926634992332820282019728792003956564819968", 10); // Set lower bound 2^255
mpz_set_str(u, "115792089237316195423570985008687907853269984665640564039457584007913129639935", 10); // Set upper bound 2^256-1
GenerateLargePrime(p, l, u);
gmp_printf("Large prime: %Zd\n", p);
mpz_clear(l);
mpz_clear(u);
mpz_clear(p);
return 0;
}
运行
sudo apt-get update
sudo apt-get install libgmp-dev
rjx@rjx-VirtualBox:~/test/2024.6.7$ ./test
Large prime: 102245892909274590127127437346763990236079888116777219746583252655183600606079
rjx@rjx-VirtualBox:~/test/2024.6.7$ ./test
Large prime: 85599317078990932562422224999979696330958333053715948349991704892713360607561
验证
- 57896044618658097711785492504343953926634992332820282019728792003956564819968(2^255)
- 102245892909274590127127437346763990236079888116777219746583252655183600606079(大素数1)
- 85599317078990932562422224999979696330958333053715948349991704892713360607561(大素数2)
- 115792089237316195423570985008687907853269984665640564039457584007913129639935(2^256-1)