简体   繁体   English

C Libgcrypt:无法使用libgcrypt检查数字是否为素数

[英]C Libgcrypt: Unable to check if number is prime using libgcrypt

I am using a libgcrypt function gcry_prime_check to test if the number 3 is a prime number. 我正在使用libgcrypt函数gcry_prime_check来测试数字3是否为质数。 It turns out 3 is not a prime number according to my the function. 事实证明,根据我的功能3不是素数。 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. 此外,有关使用libgcrypt的良好教程的链接将是一个很大的收获。 Thanks 谢谢

EDIT: 编辑:

Alright, I managed to generate a prime number using gcry_prime_generate and copied the value into number . 好了,我设法使用gcry_prime_generate生成素数,并将该值复制到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!! 但是,当您直接将prime生成的mpi输出传递给prime检查函数时,它就会通过!

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. 由于libgcrypt的重点是密码应用程序,所以这么小的素数没有任何用处。 It's sloppy though, and wouldn't take much to rectify. 它虽然草率,并且不需要花费很多时间进行纠正。

This is the function prototype, it takes a gcry_mpi_t structure and an Integer. 这是函数原型,它带有gcry_mpi_t结构和一个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 :此类型表示一个持有MPI的对象。

gcry_mpi_t structures can be allocated using the gcry_mpi_new function 可以使用gcry_mpi_new函数分配gcry_mpi_t结构

And can be set using the gcry_mpi_set function. 可以使用gcry_mpi_set函数进行设置。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM