问题
I am using a libgcrypt function gcry_prime_check
to test if the number 3
is a prime number. It turns out 3 is not a prime number according to my the function. What am i doing wrong?
Here is my code
#include <gcrypt.h>
#include <stdio.h>
int main(void)
{
gcry_mpi_t cript_prime;
gcry_error_t err;
char buffer[8] = {0};
char number[8] = {0};
printf("%s\n", gcry_check_version ( NULL ) );
gcry_control( GCRYCTL_INIT_SECMEM, 16384, 0 );
cript_prime = gcry_mpi_new(16);
strcpy(number,"3");
gcry_mpi_scan(&cript_prime,GCRYMPI_FMT_USG,number,sizeof(number),NULL);
gcry_mpi_print(GCRYMPI_FMT_USG,buffer,sizeof(buffer),NULL,cript_prime);
printf("The number tested is: %s\n",buffer);
err = gcry_prime_check(cript_prime,4);
if(err)
{
printf("%s\n",gcry_strerror(err));
}
gcry_mpi_release(cript_prime);
return 0;
}
Here is the output
1.4.4
The number tested is: 3
Number is not prime
Also, a link for a good tutorial on using libgcrypt would be a big bonus. Thanks
EDIT:
Alright, I managed to generate a prime number using gcry_prime_generate
and copied the value into number
. Turns out it failed the prime check. But when you directly the pass the mpi output from prime generate to the prime check function ... it passes!!
回答1:
It's a bug. Like most prime tests, it tests for divisibility by small prime values before moving onto more expensive tests. Unfortunately, if your prime is one of these values, it is reported as being divisible (by itself) - and therefore composite.
Since the focus of libgcrypt is cryptographic applications, such a small prime has no utility. It's sloppy though, and wouldn't take much to rectify.
回答2:
This is the function prototype, it takes a gcry_mpi_t
structure and an Integer.
gcry_error_t gcry_prime_check (gcry_mpi_t p, unsigned int flags)
gcry_mpi_t
: This type represents an object to hold an MPI.
gcry_mpi_t
structures can be allocated using the gcry_mpi_new
function
And can be set using the gcry_mpi_set
function.
来源:https://stackoverflow.com/questions/11464425/c-libgcrypt-unable-to-check-if-number-is-prime-using-libgcrypt