Search code examples
crsagnupglibgcrypt

gcry_mpi_t type definition in libgcrypt-1.8.2


I'm looking for the definition of the gcry_mpi_t type. I'm looking into the code of GnuPG, which uses libgcrypt, which in turn uses the latter as the type responsible for storing the modulus, the prime numbers of the RSA keys, etc. Typically, in /libgcrypt-1.8.2/cipher/rsa.c you can find:

typedef struct
    {
      gcry_mpi_t n;     /* modulus */
      gcry_mpi_t e;     /* exponent */
    } RSA_public_key;


typedef struct
    {
      gcry_mpi_t n;     /* public modulus */
      gcry_mpi_t e;     /* public exponent */
      gcry_mpi_t d;     /* exponent */
      gcry_mpi_t p;     /* prime  p. */
      gcry_mpi_t q;     /* prime  q. */
      gcry_mpi_t u;     /* inverse of p mod q. */
    } RSA_secret_key;

I've found this SO post which mentions the specific type I'm trying to define, but it doesn't tell how it is defined.

My aim is to use the definition in a basic CS class introducing RSA and how it can be implemented. I therefore wish to show how the specific RSA variables have to be handled by specially designed struct for efficient memory management.

However, until now, I couldn't find the proper piece of code defining it in the libgcrypt code. Thanks !


Solution

  • src/gcrypt.h.in (which is used to generate the <gcrypt.h> header:

    /* The data objects used to hold multi precision integers.  */
    struct gcry_mpi;
    typedef struct gcry_mpi *gcry_mpi_t;
    

    So publicly gcry_mpi_t is defined as a pointer to an incomplete struct, allowing the implementation to be kept private. If you're just looking in the installed headers you won't find the complete definition. For internal usage, though, src/mpi.h defines struct gcry_mpi as:

    struct gcry_mpi
    {
       int alloced;         /* Array size (# of allocated limbs). */
       int nlimbs;          /* Number of valid limbs. */
       int sign;            /* Indicates a negative number and is also used
                               for opaque MPIs to store the length.  */
       unsigned int flags; /* Bit 0: Array to be allocated in secure memory space.*/
                           /* Bit 2: The limb is a pointer to some m_alloced data.*/
                           /* Bit 4: Immutable MPI - the MPI may not be modified.  */
                           /* Bit 5: Constant MPI - the MPI will not be freed.  */
       mpi_limb_t *d;      /* Array with the limbs */
    };