使用GMP库实现RSA后加密报文的结果为0

问题描述

我正在使用 GMP 库函数来实现 RSA 算法。 这是我的代码:

const char* random_String() {
    srand (time(NULL)); 
    const char * tab[] = {"Alice","Bob","encryption","decryption"};
    std::cout << sizeof(tab)/sizeof(tab[0]) << std::endl;
    int indice = rand() % (sizeof(tab)/sizeof(tab[0]));
    
    return tab[indice];
}


int main()
{
    mpz_init(d);
    mpz_init(e);
    mpz_init(n);
    
    mpz_init(M);
    mpz_init(c);
    
 
    /* This function creates the keys. The basic algorithm is...
     *
     *  1. Generate two large distinct primes p and q randomly
     *  2. Calculate n = pq and x = (p-1)(q-1)
     *  3. Select a random integer e (1<e<x) such that gcd(e,x) = 1
     *  4. Calculate the unique d such that ed = 1(mod x)
     *  5. Public key pair : (e,n),Private key pair : (d,n)
     *
     */
   mpz_t p,q,op;
   mpz_init(p);
   mpz_init(q);
   mpz_init(op);
    
   char p_str[1000];
   char q_str[1000];
    
   mpz_init_set_str(op,"7060",10);
   mpz_nextprime(p,op);
   mpz_get_str(p_str,10,p);
   
   mpz_init_set_str(op,"7874",10);
   mpz_nextprime(q,op);
   mpz_get_str(q_str,q);
   
   std::cout << "Random Prime 'p' = " << p_str <<  std::endl;
   std::cout << "Random Prime 'q' = " << q_str <<  std::endl;

    char n_str[1000];
    mpz_t x;
    mpz_init(x);

    mpz_mul(n,p,q);
    mpz_get_str(n_str,n);
    std::cout << "\t n = " << n_str << std::endl;
    
    mpz_t p_minus_1,q_minus_1;
    mpz_init(p_minus_1);
    mpz_init(q_minus_1);

    mpz_sub_ui(p_minus_1,(unsigned long int)1);
    mpz_sub_ui(q_minus_1,(unsigned long int)1);

    mpz_mul(x,p_minus_1,q_minus_1);
    char phi_str[1000];
    mpz_get_str(phi_str,x);
    std::cout << "\t phi(n) = " << phi_str << std::endl;

    mpz_init_set_str(e,"79",0);
    char e_str[1000];
    mpz_get_str(e_str,e);
    std::cout << "\t e = " << e_str << std::endl;
     
    mpz_invert(d,e,x);
    char d_str[1000];
    mpz_get_str(d_str,d);
    std::cout << "\t d = " << d_str << std::endl << std::endl;


    std::cout << "Public Keys  (e,n): ( " << e_str <<"," << n_str << " )" << std::endl;
    std::cout << "Private Keys (d,n): ( " << d_str <<"," << n_str << " )" << std::endl;
    

    const char* mess = random_String();
    char c_str[1000];

    std::cout << "The message: : " << mess << std::endl;
    mpz_set_str(M,mess,10);
    mpz_powm(c,M,n);
    mpz_get_str(c_str,c);
    std::cout << "The encrypted message: " << c_str << std::endl;
  
}

在代码的最后 5 行中,我使用先前计算的值并遵循 RSA 加密公式对消息进行加密。 加密消息的结果是0,也就是说c_str的结果是0,怎么会是0?

解决方法

此代码

mpz_set_str(M,mess,10);

将随机字符串 mess 转换为整数。为此,字符串必须由十进制数字组成,但这不适用于您的任何随机字符串。所以函数失败,M 不变。

如果您检查 mpz_set_str 的返回值,您会看到它是 -1,表示函数失败。

基本上,您的消息与整数之间的转换只有在消息是十进制数时才有效。要转换任意字符串,您应该使用 mpz_importmpz_export 函数而不是 mpz_set_strmpz_get_str

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...