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

The result of the encrypted message after implementing RSA is 0 using the GMP library

我正在使用 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, 10, 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,10,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,p,(unsigned long int)1);
    mpz_sub_ui(q_minus_1,q,(unsigned long int)1);

    mpz_mul(x,p_minus_1,q_minus_1);
    char phi_str[1000];
    mpz_get_str(phi_str,10,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,10,e);
    std::cout << "\t e = " << e_str << std::endl;
     
    mpz_invert(d, e, x);
    char d_str[1000];
    mpz_get_str(d_str,10,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, e, n);
    mpz_get_str(c_str, 10, 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 的 return 值,您会看到它是 -1,这意味着函数失败。

基本上,只有当消息是十进制数时,您才能将消息转换为整数。要转换任意字符串,您应该使用 mpz_importmpz_export 函数而不是 mpz_set_strmpz_get_str.