密碼工程-大素數

20211115fyq發表於2024-06-09

任務詳情

在openEuler(推薦)或Ubuntu或Windows(不推薦)中完成下面任務
利用大整數庫(GMP或者OpenSSL),參考《密碼工程》p113虛擬碼實現 GenerateLargePrime 函式(10‘)
在測試程式碼中產生一個在範圍l = 2^255至u = 2^256-1內的素數。(5‘)
用OpenSSL驗證你產生的素數是不是正確(5’)
提交程式碼和執行結果截圖

測試

image

程式碼

#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;
}

image

執行

image

驗證

image

57896044618658097711785492504343953926634992332820282019728792003956564819968(2^255)
70907801182686810441628914638291098357943705721662653294993757427611873632379(大素數1)
81453251508306472626322650422738268817040832714932998071908453138966836955141(大素數2)
115792089237316195423570985008687907853269984665640564039457584007913129639935(2^256-1)

相關文章