Data type conversions

Werner Koch wk at gnupg.org
Fri Jan 8 14:12:59 CET 2010


On Fri, 8 Jan 2010 11:52:46 +0100, Sergi Blanch i Torné wrote:
> means, from the point of view of the data, that I have to transform
> 'gcry_mpi_t' data form/to 'byte*'. In the libgcrypt documentation I
> didn't find a method for this conversion.

That is easy: Use gcry_mpi_print with a suitable format specifier.
Have a look at this code in gnupg/g10/build-packet.c:

/*
 * Write the mpi A to OUT.
 */
static int
mpi_write (iobuf_t out, gcry_mpi_t a)
{
  char buffer[(MAX_EXTERN_MPI_BITS+7)/8+2]; /* 2 is for the mpi length. */
  size_t nbytes;
  int rc;

  nbytes = DIM(buffer);
  rc = gcry_mpi_print (GCRYMPI_FMT_PGP, buffer, nbytes, &nbytes, a );
  if( !rc )
    rc = iobuf_write( out, buffer, nbytes );
  else if (gpg_err_code(rc) == GPG_ERR_TOO_SHORT )
    {
      log_info ("mpi too large (%u bits)\n", gcry_mpi_get_nbits (a));
      /* The buffer was too small. We better tell the user about the MPI. */
      rc = gpg_error (GPG_ERR_TOO_LARGE);
    }

  return rc;
}

If you don't want to put an upper limit on the size of the MPI or you
want to store int in secure memory you need to allocate the buffer.
gcry_mpi_aprint does this for you and automagically decides whether to
allocate from the standard or the secure memory pool.  See the gcrypt
manual.


Salam-Shalom,

   Werner

-- 
Die Gedanken sind frei.  Ausnahmen regelt ein Bundesgesetz.




More information about the Gcrypt-devel mailing list