This is gcrypt.info, produced by makeinfo version 4.2 from
/usr/obj/ports/libgcrypt-1.2.0/libgcrypt-1.2.0/doc/gcrypt.texi.

INFO-DIR-SECTION GNU Libraries
START-INFO-DIR-ENTRY
* libgcrypt: (gcrypt) Cryptographic function library.
END-INFO-DIR-ENTRY

   This file documents the `Libgcrypt' library.

   This is Edition 1.2.0, last updated 12 March 2004, of `The
`Libgcrypt' Reference Manual', for Version 1.2.0.

   Copyright (C) 2000, 2002, 2003 Free Software Foundation, Inc.

   Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version. The text of the license can be found in the
section entitled "Copying".


File: gcrypt.info,  Node: General public-key related Functions,  Prev: Cryptographic Functions,  Up: Public Key cryptography (I)

General public-key related Functions
====================================

A couple of utility functions are available to retrieve the length of
the key, map algorithm identifiers and perform sanity checks:

 - Function: const char * gcry_pk_algo_name (int ALGO)
     Map the public key algorithm id ALGO to a string representation of
     the algorithm name.  For unknown algorithms this functions returns
     an empty string.

 - Function: int gcry_pk_map_name (const char *NAME)
     Map the algorithm NAME to a public key algorithm Id.  Returns 0 if
     the algorithm name is not known.

 - Function: int gcry_pk_test_algo (int ALGO)
     Return 0 if the public key algorithm ALGO is available for use.
     Note, that this is implemented as a macro.

 - Function: unsigned int gcry_pk_get_nbits (gcry_sexp_t KEY)
     Return what is commonly referred as the key length for the given
     public or private in KEY.

 - Function: unsigned char * gcry_pk_get_keygrip (gcry_sexp_t KEY,
          unsigned char *ARRAY)
     Return the so called "keygrip" which is the SHA-1 hash of the
     public key parameters expressed in a way depended on the
     algorithm.  ARRAY must either provide space for 20 bytes or
     `NULL;'. In the latter case a newly allocated array of that size
     is returned.  On success a pointer to the newly allocated space or
     to ARRAY is returned.  `NULL' is returned to indicate an error
     which is most likely an unknown algorithm or one where a "keygrip"
     has not yet been defined.  The function accepts public or secret
     keys in KEY.

 - Function: gcry_error_t gcry_pk_testkey (gcry_sexp_t KEY)
     Return zero if the private key KEY is `sane', an error code
     otherwise.  Note, that it is not possible to chek the `saneness'
     of a public key.


 - Function: int gcry_pk_algo_info (int ALGO, int WHAT, void *BUFFER,
          size_t *NBYTES)
     Depending on the value of WHAT return various information about
     the public key algorithm with the id ALGO.  Note, that the
     function returns `-1' on error and the actual error code must be
     retrieved using the function `gcry_errno'.  The currently defined
     values for WHAT are:

    `GCRYCTL_TEST_ALGO:'
          Return 0 when the specified algorithm is available for use.
          BUFFER must be `NULL', NBYTES may be passed as `NULL' or
          point to a variable with the required usage of the algorithm.
          This may be 0 for "don't care" or the bit-wise OR of these
          flags:

         `GCRY_PK_USAGE_SIGN'
               Algorithm is usable for signing.

         `GCRY_PK_USAGE_ENCR'
               Algorithm is usable for encryption.

    `GCRYCTL_GET_ALGO_USAGE:'
          Return the usage flags for the given algorithm.  An invalid
          algorithm return 0.  Disabled algorithms are ignored here
          because we want to know whether the algorithm is at all
          capable of a certain usage.

    `GCRYCTL_GET_ALGO_NPKEY'
          Return the number of elements the public key for algorithm
          ALGO consist of.  Return 0 for an unknown algorithm.

    `GCRYCTL_GET_ALGO_NSKEY'
          Return the number of elements the private key for algorithm
          ALGO consist of.  Note that this value is always larger than
          that of the public key.  Return 0 for an unknown algorithm.

    `GCRYCTL_GET_ALGO_NSIGN'
          Return the number of elements a signature created with the
          algorithm ALGO consists of.  Return 0 for an unknown
          algorithm or for an algorithm not capable of creating
          signatures.

    `GCRYCTL_GET_ALGO_NENC'
          Return the number of elements a encrypted message created
          with the algorithm ALGO consists of.  Return 0 for an unknown
          algorithm or for an algorithm not capable of encryption.

     Please note that parameters not required should be passed as
     `NULL'.

 - Function: gcry_error_t gcry_pk_ctl (int CMD, void *BUFFER,
          size_t BUFLEN)
     This is a general purpose function to perform certain control
     operations.  CMD controls what is to be done. The return value is
     0 for success or an error code.  Currently supported values for
     CMD are:

    `GCRYCTL_DISABLE_ALGO'
          Disable the algorithm given as an algorithm id in BUFFER.
          BUFFER must point to an `int' variable with the algorithm id
          and BUFLEN must have the value `sizeof (int)'.


Libgcrypt also provides a function for generating public key pairs:

 - Function: gcry_error_t gcry_pk_genkey (gcry_sexp_t *R_KEY,
          gcry_sexp_t PARMS)
     This function create a new public key pair using information given
     in the S-expression PARMS and stores the private and the public key
     in one new S-expression at the address given by R_KEY.  In case of
     an error, R_KEY is set to `NULL'.  The return code is 0 for
     success or an error code otherwise.

     Here is an example for PARMS for creating a 1024 bit RSA key:

          (genkey
            (rsa
              (nbits 4:1024)))

     To create an ElGamal key, substitute "elg" for "rsa" and to create
     a DSA key use "dsa".  Valid ranges for the key length depend on the
     algorithms; all commonly used key lengths are supported.  Currently
     supported parameters are:

    `nbits'
          This is always required to specify the length of the key.
          The argument is a string with a number in C-notation.

    `rsa-use-e'
          This is only used with RSA to give a hint for the public
          exponent. The value will be used as a base to test for a
          usable exponent. Some values are special:

         `0'
               Use a secure and fast value.  This is currently the
               number 41.

         `1'
               Use a secure value as required by some specification.
               This is currently the number 65537.

         `2'
               Reserved

          If this parameter is not used, Libgcrypt uses for historic
          reasons 65537.

     The key pair is returned in a format depending on the algorithm.
     Both private and public keys are returned in one container and may
     be accompanied by some miscellaneous information.

     As an example, here is what the ElGamal key generation returns:

          (key-data
            (public-key
              (elg
                (p P-MPI)
                (g G-MPI)
                (y Y-MPI)))
            (private-key
              (elg
                (p P-MPI)
                (g G-MPI)
                (y Y-MPI)
                (x X-MPI)))
            (misc-key-info
              (pm1-factors N1 N2 ... NN)))

     As you can see, some of the information is duplicated, but this
     provides an easy way to extract either the public or the private
     key.  Note that the order of the elements is not defined, e.g. the
     private key may be stored before the public key. N1 N2 ... NN is a
     list of prime numbers used to composite P-MPI; this is in general
     not a very useful information.


File: gcrypt.info,  Node: Public Key cryptography (II),  Next: Random Numbers,  Prev: Public Key cryptography (I),  Up: Top

Public Key cryptography (II)
****************************

   This chapter documents the alternative interface to asymmetric
cryptography (ac) that is not based on S-expressions, but on native C
data structures.  As opposed to the pk interface described in the
former chapter, this one follows an open/use/close paradigm like other
building blocks of the library.

* Menu:

* Available asymmetric algorithms::  List of algorithms supported by the library.
* Working with sets of data::   How to work with sets of data.
* Working with handles::        How to use handles.
* Working with keys::           How to work with keys.
* Using cryptographic functions::  How to perform cryptographic operations.
* Handle-independent functions::  General functions independent of handles.


File: gcrypt.info,  Node: Available asymmetric algorithms,  Next: Working with sets of data,  Up: Public Key cryptography (II)

Available asymmetric algorithms
===============================

   Libgcrypt supports the RSA (Rivest-Shamir-Adleman) algorithms as
well as DSA (Digital Signature Algorithm) and ElGamal.  The versatile
interface allows to add more algorithms in the future.

 - Data type: gcry_ac_id_t
     The following constants are defined for this type:

    `GCRY_AC_RSA'
          Riven-Shamir-Adleman

    `GCRY_AC_DSA'
          Digital Signature Algorithm

    `GCRY_AC_ELG'
          ElGamal

    `GCRY_AC_ELG_E'
          ElGamal, encryption only.


File: gcrypt.info,  Node: Working with sets of data,  Next: Working with handles,  Prev: Available asymmetric algorithms,  Up: Public Key cryptography (II)

Working with sets of data
=========================

   In the context of this interface the term `data set' refers to a list
of `named MPI values' that is used by functions performing
cryptographic operations.

   Such data sets are used for representing keys, since keys simply
consist of a variable amount of numbers.  Furthermore some functions
return data sets to the caller that are to be provided to other
functions.

   This section documents the data types, symbols and functions that are
relevant for working with such data sets.

 - Data type: gcry_ac_data_t
     A data set, that is simply a list of named MPI values.

   The following flags are supported:

`GCRY_AC_FLAG_DEALLOC'
     Used for storing data in a data set.  If given, the data will be
     released by the library.

`GCRY_AC_FLAG_COPY'
     Used for storing/retrieving data in/from a data set.  If given, the
     library will create copies of the provided/contained data, which
     will then be given to the user/associated with the data set.

 - Function: gcry_error_t gcry_ac_data_new (gcry_ac_data_t *DATA)
     Creates a new, empty data set and stores it in DATA.

 - Function: void gcry_ac_data_destroy (gcry_ac_data_t DATA)
     Destroys the data set DATA.

 - Function: gcry_error_t gcry_ac_data_set (gcry_ac_data_t DATA,
     unsigned int FLAGS, char *NAME, gcry_mpi_t MPI) Add the value MPI
     to DATA with the label NAME.  If FLAGS contains
     GCRY_AC_FLAG_DATA_COPY, the data set will contain copies of NAME
     and MPI.  If FLAGS contains GCRY_AC_FLAG_DATA_DEALLOC or
     GCRY_AC_FLAG_DATA_COPY, the values contained in the data set will
     be deallocated when they are to be removed from the data set.

 - Function: gcry_error_t gcry_ac_data_copy (gcry_ac_data_t *DATA_CP,
          gcry_ac_data_t DATA)
     Create a copy of the data set DATA and store it in DATA_CP.

 - Function: unsigned int gcry_ac_data_length (gcry_ac_data_t DATA)
     Returns the number of named MPI values inside of the data set DATA.

 - Function: gcry_error_t gcry_ac_data_get_name (gcry_ac_data_t DATA,
     unsigned int FLAGS, char *NAME, gcry_mpi_t *MPI) Store the value
     labelled with NAME found in DATA in MPI.  If FLAGS contains
     GCRY_AC_FLAG_COPY, store a copy of the MPI value contained in the
     data set.  MPI may be NULL.

 - Function: gcry_error_t gcry_ac_data_get_index (gcry_ac_data_t DATA,
     unsigned int flags, unsigned int INDEX, const char **NAME,
     gcry_mpi_t *MPI) Stores in NAME and MPI the named MPI value
     contained in the data set DATA with the index IDX.  If FLAGS
     contains GCRY_AC_FLAG_COPY, store copies of the values contained in
     the data set. NAME or MPI may be NULL.

 - Function: void gcry_ac_data_clear (gcry_ac_data_t DATA)
     Destroys any values contained in the data set DATA.


File: gcrypt.info,  Node: Working with handles,  Next: Working with keys,  Prev: Working with sets of data,  Up: Public Key cryptography (II)

Working with handles
====================

   In order to use an algorithm, an according handle must be created.
This is done using the following function:

 - Function: gcry_error_t gcry_ac_open (gcry_ac_handle_t *HANDLE,
     int ALGORITHM, int FLAGS)

     Creates a new handle for the algorithm ALGORITHM and stores it in
     HANDLE.  FLAGS is not used yet.

     ALGORITHM must be a valid algorithm ID, see *Note Available
     algorithms::, for a list of supported algorithms and the according
     constants.  Besides using the listed constants directly, the
     functions `gcry_ac_name_to_id' may be used to convert the textual
     name of an algorithm into the according numeric ID.

 - Function: void gcry_ac_close (gcry_ac_handle_t HANDLE)
     Destroys the handle HANDLE.


File: gcrypt.info,  Node: Working with keys,  Next: Using cryptographic functions,  Prev: Working with handles,  Up: Public Key cryptography (II)

Working with keys
=================

 - Data type: gcry_ac_key_id_t
     Defined constants:

    `GCRY_AC_KEY_TYPE_SECRET'
          Specifies a secret key.

    `GCRY_AC_KEY_TYPE_PUBLIC'
          Specifies a public key.

 - Data type: gcry_ac_key_t
     This type represents a single `key', either a secret one or a
     public one.

 - Data type: gcry_ac_key_pair_t
     This type represents a `key pair' containing a secret and a public
     key.

   Key data structures can be created in two different ways; a new key
pair can be generated, resulting in ready-to-use key.  Alternatively a
key can be initialized from a given data set.

 - Function: gcry_error_t gcry_ac_key_init (gcry_ac_key_t *KEY,
          gcry_ac_handle_t HANDLE, gcry_ac_key_type_t TYPE,
          gcry_ac_data_t DATA)
     Creates a new key of type TYPE, consisting of the MPI values
     contained in the data set DATA and stores it in KEY.

 - Function: gcry_error_t gcry_ac_key_pair_generate (gcry_ac_handle_t
          HANDLE,
     unsigned int NBITS, void *KEY_SPEC, gcry_ac_key_pair_t *KEY_PAIR,
     gcry_mpi_t **MISC_DATA)

     Generates a new key pair via the handle HANDLE of NBITS bits and
     stores it in KEY_PAIR.

     In case non-standard settings are wanted, a pointer to a structure
     of type `gcry_ac_key_spec_<algorithm>_t', matching the selected
     algorithm, can be given as KEY_SPEC.  MISC_DATA is not used yet.
     Such a structure does only exist for RSA.  A descriptions of the
     members of the supported structures follows.

    `gcry_ac_key_spec_rsa_t'

         `gcry_mpi_t e'
               Generate the key pair using a special `e'.  The value of
               `e' has the following meanings:
              `= 0'
                    Let Libgcrypt device what exponent should be used.

              `= 1'
                    Request the use of a "secure" exponent; this is
                    required by some specification to be 65537.

              `> 2'
                    Try starting at this value until a working exponent
                    is found.  Note, that the current implementation
                    leaks some information about the private key
                    because the incrementation used is not randomized.
                    Thus, this function will be changed in the future
                    to return a random exponent of the given size.

     Example code:
          {
            gcry_ac_key_pair_t key_pair;
            gcry_ac_key_spec_rsa  rsa_spec;
          
            rsa_spec.e = gcry_mpi_new (0);
            gcry_mpi_set_ui (rsa_spec.e, 1)
          
            err = gcry_ac_open  (&handle, GCRY_AC_RSA, 0);
            assert (! err);
          
            err = gcry_ac_key_pair_generate (handle, &key_pair, 1024, (void *) &rsa_spec);
            assert (! err);
          }

 - Function: gcry_ac_key_t gcry_ac_key_pair_extract (gcry_ac_key_pair_t
          KEY_PAIR, gcry_ac_key_type_t WHICH)
     Returns the key of type WHICH out of the key pair KEY_PAIR.

 - Function: void gcry_ac_key_destroy (gcry_ac_key_t KEY)
     Destroys the key KEY.

 - Function: void gcry_ac_key_pair_destroy (gcry_ac_key_pair_t KEY_PAIR)
     Destroys the key pair KEY_PAIR.

 - Function: gcry_ac_data_t gcry_ac_key_data_get (gcry_ac_key_t KEY)
     Returns the data set contained in the key KEY.

 - Function: gcry_error_t gcry_ac_key_test (gcry_ac_handle_t HANDLE,
          gcry_ac_key_t KEY)
     Verifies that the private key KEY is sane via HANDLE.

 - Function: gcry_error_t gcry_ac_key_get_nbits (gcry_ac_handle_t
          HANDLE,
     gcry_ac_key_t KEY, unsigned int *NBITS) Stores the number of bits
     of the key KEY in NBITS via HANDLE.

 - Function: gcry_error_t gcry_ac_key_get_grip (gcry_ac_handle_t HANDLE,
     gcry_ac_key_t KEY, unsigned char *KEY_GRIP) Writes the 20 byte
     long key grip of the key KEY to KEY_GRIP via HANDLE.


File: gcrypt.info,  Node: Using cryptographic functions,  Next: Handle-independent functions,  Prev: Working with keys,  Up: Public Key cryptography (II)

Using cryptographic functions
=============================

   The following flags might be relevant:

`GCRY_AC_FLAG_NO_BLINDING'
     Disable any blinding, which might be supported by the chosen
     algorithm; blinding is the default.

 - Function: gcry_error_t gcry_ac_data_encrypt (gcry_ac_handle_t
          HANDLE, unsigned int FLAGS, gcry_ac_key_t KEY, gcry_mpi_t
          DATA_PLAIN, gcry_ac_data_t **DATA_ENCRYPTED)
     Encrypts the plain text MPI value DATA_PLAIN with the key public
     KEY under the control of the flags FLAGS and stores the resulting
     data set into DATA_ENCRYPTED.

 - Function: gcry_error_t gcry_ac_data_decrypt (gcry_ac_handle_t
          HANDLE, unsigned int FLAGS, gcry_ac_key_t KEY, gcry_mpi_t
          *DATA_PLAIN, gcry_ac_data_t DATA_ENCRYPTED)
     Decrypts the encrypted data contained in the data set
     DATA_ENCRYPTED with the secret key KEY under the control of the
     flags FLAGS and stores the resulting plain text MPI value in
     DATA_PLAIN.

 - Function: gcry_error_t gcry_ac_data_sign (gcry_ac_handle_t HANDLE,
          gcry_ac_key_t KEY, gcry_mpi_t DATA, gcry_ac_data_t
          *DATA_SIGNATURE)
     Signs the data contained in DATA with the secret key KEY and
     stores the resulting signature in the data set DATA_SIGNATURE.

 - Function: gcry_error_t gcry_ac_data_verify (gcry_ac_handle_t HANDLE,
          gcry_ac_key_t KEY, gcry_mpi_t DATA, gcry_ac_data_t
          DATA_SIGNATURE)
     Verifies that the signature contained in the data set
     DATA_SIGNATURE is indeed the result of signing the data contained
     in DATA with the secret key belonging to the public key KEY.


File: gcrypt.info,  Node: Handle-independent functions,  Prev: Using cryptographic functions,  Up: Public Key cryptography (II)

Handle-independent functions
============================

 - Function: gcry_error_t gcry_ac_id_to_name (gcry_ac_id_t ALGORITHM,
          const char **NAME)
     Stores the textual representation of the algorithm whose id is
     given in ALGORITHM in NAME.

 - Function: gcry_error_t gcry_ac_name_to_id (const char *NAME,
          gcry_ac_id_t *ALGORITHM)
     Stores the numeric ID of the algorithm whose textual
     representation is contained in NAME in ALGORITHM.


File: gcrypt.info,  Node: Random Numbers,  Next: S-expressions,  Prev: Public Key cryptography (II),  Up: Top

Random Numbers
**************

* Menu:

* Quality of random numbers::   Libgcrypt uses different quality levels.
* Retrieving random numbers::   How to retrieve random numbers.


File: gcrypt.info,  Node: Quality of random numbers,  Next: Retrieving random numbers,  Up: Random Numbers

Quality of random numbers
=========================

   Libgcypt offers random numbers of different quality levels:

 - Data type: enum gcry_random_level
     The constants for the random quality levels are of this type.

`GCRY_WEAK_RANDOM'
     This should not anymore be used.  It has recently been changed to
     an alias of GCRY_STRONG_RANDOM.  Use `gcry_create_nonce' instead.

`GCRY_STRONG_RANDOM'
     Use this level for e.g. session keys and similar purposes.

`GCRY_VERY_STRONG_RANDOM'
     Use this level for e.g. key material.


File: gcrypt.info,  Node: Retrieving random numbers,  Prev: Quality of random numbers,  Up: Random Numbers

Retrieving random numbers
=========================

 - Function: void gcry_randomize (unsigned char *BUFFER, size_t LENGTH,
          enum gcry_random_level LEVEL)
     Fill BUFFER with LENGTH random bytes using a random quality as
     defined by LEVEL.

 - Function: void * gcry_random_bytes (size_t NBYTES, enum
          gcry_random_level LEVEL)
     Allocate a memory block consisting of NBYTES fresh random bytes
     using a random quality as defined by LEVEL.

 - Function: void * gcry_random_bytes_secure (size_t NBYTES, enum
          gcry_random_level LEVEL)
     Allocate a memory block consisting of NBYTES fresh random bytes
     using a random quality as defined by LEVEL.  This function differs
     from `gcry_random_bytes' in that the returned buffer is allocated
     in a "secure" area of the memory.

 - Function: void gcry_create_nonce (unsigned char *BUFFER, size_t
          LENGTH)
     Fill BUFFER with LENGTH unpredictable bytes.  This is commonly
     called a nonce and may also be used for initialization vectors and
     padding.  This is an extra function nearly independent of the
     other random function for 3 reasons: It better protects the
     regular random generator's internal state, provides better
     performance and does not drain the precious entropy pool.



File: gcrypt.info,  Node: S-expressions,  Next: MPI library,  Prev: Random Numbers,  Up: Top

S-expressions
*************

   S-expressions are used by the public key functions to pass complex
data structures around.  These LISP like objects are used by some
cryptographic protocols (cf. RFC-2692) and Libgcrypt provides functions
to parse and construct them.  For detailed information, see `Ron
Rivest, code and description of S-expressions,
`http://theory.lcs.mit.edu/~rivest/sexp.html''.

* Menu:

* Data types for S-expressions::  Data types related with S-expressions.
* Working with S-expressions::  How to work with S-expressions.


File: gcrypt.info,  Node: Data types for S-expressions,  Next: Working with S-expressions,  Up: S-expressions

Data types for S-expressions
============================

 - Data type: gcry_sexp_t
     The `gcry_sexp_t' type describes an object with the Libgcrypt
     internal representation of an S-expression.


File: gcrypt.info,  Node: Working with S-expressions,  Prev: Data types for S-expressions,  Up: S-expressions

Working with S-expressions
==========================

There are several functions to create an Libgcrypt S-expression object
from its external representation or from a string template.  There is
also a function to convert the internal representation back into one of
the external formats:

 - Function: gcry_error_t gcry_sexp_new (gcry_sexp_t *R_SEXP,
          const void *BUFFER, size_t LENGTH, int AUTODETECT)
     This is the generic function to create an new S-expression object
     from its external representation in BUFFER of LENGTH bytes.  On
     success the result is stored at the address given by R_SEXP.  With
     AUTODETECT set to 0, the data in BUFFER is expected to be in
     canonized format, with AUTODETECT set to 1 the parses any of the
     defined external formats.  If BUFFER does not hold a valid
     S-expression an error code is returned and R_SEXP set to `NULL'.
     Note, that the caller is responsible for releasing the newly
     allocated S-expression using `gcry_sexp_release'.

 - Function: gcry_error_t gcry_sexp_create (gcry_sexp_t *R_SEXP,
          void *BUFFER, size_t LENGTH, int AUTODETECT,
          void (*FREEFNC)(void*))
     This function is identical to `gcry_sexp_new' but has an extra
     argument FREEFNC, which, when not set to `NULL', is expected to be
     a function to release the BUFFER; most likely the standard `free'
     function is used for this argument.  This has the effect of
     transferring the ownership of BUFFER to the created object in
     R_SEXP.  The advantage of using this function is that Libgcrypt
     might decide to directly use the provided buffer and thus avoid
     extra copying.

 - Function: gcry_error_t gcry_sexp_sscan (gcry_sexp_t *R_SEXP,
          size_t *ERROFF, const char *BUFFER, size_t LENGTH)
     This is another variant of the above functions.  It behaves nearly
     identical but provides an ERROFF argument which will receive the
     offset into the buffer where the parsing stopped on error.

 - Function: gcry_error_t gcry_sexp_build (gcry_sexp_t *R_SEXP,
          size_t *ERROFF, const char *FORMAT, ...)
     This function creates an internal S-expression from the string
     template FORMAT and stores it at the address of R_SEXP. If there
     is a parsing error, the function returns an appropriate error code
     and stores the offset into FORMAT where the parsing stopped in
     ERROFF.  The function supports a couple of printf-like formatting
     characters and expects arguments for some of these escape
     sequences right after FORMAT.  The following format characters are
     defined:

    `%m'
          The next argument is expected to be of type `gcry_mpi_t' and
          a copy of its value is inserted into the resulting
          S-expression.

    `%s'
          The next argument is expected to be of type `char *' and that
          string is inserted into the resulting S-expression.

    `%d'
          The next argument is expected to be of type `int' and its
          value ist inserted into the resulting S-expression.

    `%b'
          The next argument is expected to be of type `int' directly
          followed by an argument of type `char *'.  This represents a
          buffer of given length to be inserted into the resulting
          regular expression.

     No other format characters are defined and would return an error.
     Note, that the format character `%%' does not exists, because a
     percent sign is not a valid character in an S-expression.

 - Function: void gcry_sexp_release (gcry_sexp_t SEXP)
     Release the S-expression object SEXP.

The next 2 functions are used to convert the internal representation
back into a regular external S-expression format and to show the
structure for debugging.

 - Function: size_t gcry_sexp_sprint (gcry_sexp_t SEXP, int MODE,
          char *BUFFER, size_t MAXLENGTH)
     Copies the S-expression object SEXP into BUFFER using the format
     specified in MODE.  MAXLENGTH must be set to the allocated length
     of BUFFER.  The function returns the actual length of valid bytes
     put into BUFFER or 0 if the provided buffer is too short.  Passing
     `NULL' for BUFFER returns the required length for BUFFER.  For
     convenience reasons an extra byte with value 0 is appended to the
     buffer.

     The following formats are supported:

    `GCRYSEXP_FMT_DEFAULT'
          Returns a convenient external S-expression representation.

    `GCRYSEXP_FMT_CANON'
          Return the S-expression in canonical format.

    `GCRYSEXP_FMT_BASE64'
          Not currently supported.

    `GCRYSEXP_FMT_ADVANCED'
          Returns the S-expression in advanced format.

 - Function: void gcry_sexp_dump (gcry_sexp_t SEXP)
     Dumps SEXP in a format suitable for debugging to Libgcrypt's
     logging stream.

Often canonical encoding is used in the external representation.  The
following function can be used to check for valid encoding and to learn
the length of the S-expression"

 - Function: size_t gcry_sexp_canon_len (const unsigned char *BUFFER,
          size_t LENGTH, size_t *ERROFF, int *ERRCODE)
     Scan the canonical encoded BUFFER with implicit length values and
     return the actual length this S-expression uses.  For a valid
     S-expression it should never return 0.  If LENGTH is not 0, the
     maximum length to scan is given; this can be used for syntax
     checks of data passed from outside.  ERRCODE and ERROFF may both be
     passed as `NULL'.


There are a couple of functions to parse S-expressions and retrieve
elements:

 - Function: gcry_sexp_t gcry_sexp_find_token (const gcry_sexp_t LIST,
          const char *TOKEN, size_t TOKLEN)
     Scan the S-expression for a sublist with a type (the car of the
     list) matching the string TOKEN.  If TOKLEN is not 0, the token is
     assumed to be raw memory of this length.  The function returns a
     newly allocated S-expression consisting of the found sublist or
     `NULL' when not found.

 - Function: int gcry_sexp_length (const gcry_sexp_t LIST)
     Return the length of the LIST.  For a valid S-expression this
     should be at least 1.

 - Function: gcry_sexp_t gcry_sexp_nth (const gcry_sexp_t LIST,
          int NUMBER)
     Create and return a new S-expression from the element with index
     NUMBER in LIST.  Note that the first element has the index 0.  If
     there is no such element, `NULL' is returned.

 - Function: gcry_sexp_t gcry_sexp_car (const gcry_sexp_t LIST)
     Create and return a new S-expression from the first element in
     LIST; this called the "type" and should always exist and be a
     string. `NULL' is returned in case of a problem.

 - Function: gcry_sexp_t gcry_sexp_cdr (const gcry_sexp_t LIST)
     Create and return a new list form all elements except for the
     first one.  Note, that this function may return an invalid
     S-expression because it is not guaranteed, that the type exists
     and is a string.  However, for parsing a complex S-expression it
     might be useful for intermediate lists.  Returns `NULL' on error.

 - Function: const char * gcry_sexp_nth_data (const gcry_sexp_t LIST,
          int NUMBER, size_t *DATALEN)
     This function is used to get data from a LIST.  A pointer to the
     actual data with index NUMBER is returned and the length of this
     data will be stored to DATALEN.  If there is no data at the given
     index or the index represents another list, `NULL' is returned.
     *Note:* The returned pointer is valid as long as LIST is not
     modified or released.

     Here is an example on how to extract and print the surname (Meier)
     from the S-expression `(Name Otto Meier (address Burgplatz 3))':

          size_t len;
          const char *name;
          
          name = gcry_sexp_nth_data (list, 2, &len);
          printf ("my name is %.*s\n", (int)len, name);

 - Function: gcry_mpi_t gcry_sexp_nth_mpi (gcry_sexp_t LIST,
          int NUMBER, int MPIFMT)
     This function is used to get and convert data from a LIST. This
     data is assumed to be an MPI stored in the format described by
     MPIFMT and returned as a standard Libgcrypt MPI.  The caller must
     release this returned value using `gcry_mpi_release'.  If there is
     no data at the given index, the index represents a list or the
     value can't be converted to an MPI, `NULL' is returned.


File: gcrypt.info,  Node: MPI library,  Next: Utilities,  Prev: S-expressions,  Up: Top

MPI library
***********

* Menu:

* Data types::                  MPI related data types.
* Basic functions::             First steps with MPI numbers.
* MPI formats::                 External representation of MPIs.
* Calculations::                Performing MPI calculations.
* Comparisons::                 How to compare MPI values.
* Bit manipulations::           How to access single bits of MPI values.
* Misc::                        Misc, fixme.

   Public key cryptography is based on mathematics with large numbers.
To implement the public key functions, a library for handling these
large numbers is required.  Because of the general usefulness of such a
library, its interface is exposed by Libgcrypt.  The implementation is
based on an old release of GNU Multi-Precision Library (GMP) but in the
meantime heavily modified and stripped down to what is required for
cryptography. For a lot of CPUs, high performance assembler
implementations of some very low level functions are used to gain much
better performance than with the standard C implementation.

In the context of Libgcrypt and in most other applications, these large
numbers are called MPIs (multi-precision-integers).


File: gcrypt.info,  Node: Data types,  Next: Basic functions,  Up: MPI library

Data types
==========

 - Data type: gcry_mpi_t
     The `gcry_mpi_t' type represents an object to hold an MPI.


File: gcrypt.info,  Node: Basic functions,  Next: MPI formats,  Prev: Data types,  Up: MPI library

Basic functions
===============

To work with MPIs, storage must be allocated and released for the
numbers.  This can be done with one of these functions:

 - Function: gcry_mpi_t gcry_mpi_new (unsigned int NBITS)
     Allocate a new MPI object, initialize it to 0 and initially
     allocate enough memory for a number of at least NBITS.  This
     pre-allocation is only a small performance issue and not actually
     necessary because Libgcrypt automatically re-allocates the
     required memory.

 - Function: gcry_mpi_t gcry_mpi_snew (unsigned int NBITS)
     This is identical to `gcry_mpi_new' but allocates the MPI in the so
     called "secure memory" which in turn will take care that all
     derived values will also be stored in this "secure memory".  Use
     this for highly confidential data like private key parameters.

 - Function: gcry_mpi_t gcry_mpi_copy (const gcry_mpi_t A)
     Create a new MPI as the exact copy of A.

 - Function: void gcry_mpi_release (gcry_mpi_t A)
     Release the MPI A and free all associated resources.  Passing
     `NULL' is allowed and ignored.  When a MPI stored in the "secure
     memory" is released, that memory gets wiped out immediately.

The simplest operations are used to assign a new value to an MPI:

 - Function: gcry_mpi_t gcry_mpi_set (gcry_mpi_t W, const gcry_mpi_t U)
     Assign the value of U to W and return W.  If `NULL' is passed for
     W, a new MPI is allocated, set to the value of U and returned.

 - Function: gcry_mpi_t gcry_mpi_set_ui (gcry_mpi_t W, unsigned long U)
     Assign the value of U to W and return W.  If `NULL' is passed for
     W, a new MPI is allocated, set to the value of U and returned.
     This function takes an `unsigned int' as type for U and thus it is
     only possible to set W to small values (usually up to the word
     size of the CPU).

 - Function: void gcry_mpi_swap (gcry_mpi_t A, gcry_mpi_t B)
     Swap the values of A and B.


File: gcrypt.info,  Node: MPI formats,  Next: Calculations,  Prev: Basic functions,  Up: MPI library

MPI formats
===========

The following functions are used to convert between an external
representation of an MPI and the internal one of Libgcrypt.

 - Function: int gcry_mpi_scan (gcry_mpi_t *R_MPI,
          enum gcry_mpi_format FORMAT, const unsigned char *BUFFER,
          size_t BUFLEN, size_t *NSCANNED)
     Convert the external representation of an integer stored in BUFFER
     with a length of BUFLEN into a newly created MPI returned which
     will be stored at the address of R_MPI.  For certain formats the
     length argument is not required and may be passed as `0'.  After a
     successful operation the variable NSCANNED receives the number of
     bytes actually scanned unless NSCANNED was given as `NULL'. FORMAT
     describes the format of the MPI as stored in BUFFER:

    `GCRYMPI_FMT_STD'
          2-complement stored without a length header.

    `GCRYMPI_FMT_PGP'
          As used by OpenPGP (only defined as unsigned). This is
          basically `GCRYMPI_FMT_STD' with a 2 byte big endian length
          header.

    `GCRYMPI_FMT_SSH'
          As used in the Secure Shell protocol.  This is
          `GCRYMPI_FMT_STD' with a 4 byte big endian header.

    `GCRYMPI_FMT_HEX'
          Stored as a C style string with each byte of the MPI encoded
          as 2 hex digits.

    `GCRYMPI_FMT_USG'
          Simple unsigned integer.

     Note, that all of the above formats store the integer in big-endian
     format (MSB first).

 - Function: int gcry_mpi_print (enum gcry_mpi_format FORMAT,
          unsigned char *BUFFER, size_t BUFLEN, size_t *NWRITTEN,
          const gcry_mpi_t A)
     Convert the MPI A into an external representation described by
     FORMAT (see above) and store it in the provided BUFFER which which
     has a usable length of at least the BUFLEN bytes. If NWRITTEN is
     not NULL, it wilol receive the number of bytes actually stored in
     BUFFER after a successful operation.

 - Function: int gcry_mpi_aprint (enum gcry_mpi_format FORMAT,
          unsigned char **BUFFER, size_t *NBYTES, const gcry_mpi_t A)
     Convert the MPI A into an external representation described by
     FORMAT (see above) and store it in a newly allocated buffer which
     address will be stored in the variable BUFFER points to.  The
     number of bytes stored in this buffer will be stored in the
     variable NBYTES points to, unless NBYTES is `NULL'.

 - Function: void gcry_mpi_dump (const gcry_mpi_t A)
     Dump the value of A in a format suitable for debugging to
     Libgcrypt's logging stream.  Note that one leading space but no
     trailing space or linefeed will be printed.  It is okay to pass
     `NULL' for A.


File: gcrypt.info,  Node: Calculations,  Next: Comparisons,  Prev: MPI formats,  Up: MPI library

Calculations
============

Basic arithmetic operations:

 - Function: void gcry_mpi_add (gcry_mpi_t W, gcry_mpi_t U,
          gcry_mpi_t V)
     W = U + V.

 - Function: void gcry_mpi_add_ui (gcry_mpi_t W, gcry_mpi_t U,
          unsigned long V)
     W = U + V.  Note, that V is an unsigned integer.

 - Function: void gcry_mpi_addm (gcry_mpi_t W, gcry_mpi_t U,
          gcry_mpi_t V, gcry_mpi_t M)
     W = U + V \bmod M.

 - Function: void gcry_mpi_sub (gcry_mpi_t W, gcry_mpi_t U,
          gcry_mpi_t V)
     W = U - V.

 - Function: void gcry_mpi_sub_ui (gcry_mpi_t W, gcry_mpi_t U,
          unsigned long V)
     W = U - V.  V is an unsigned integer.

 - Function: void gcry_mpi_subm (gcry_mpi_t W, gcry_mpi_t U,
          gcry_mpi_t V, gcry_mpi_t M)
     W = U - V \bmod M.

 - Function: void gcry_mpi_mul (gcry_mpi_t W, gcry_mpi_t U,
          gcry_mpi_t V)
     W = U * V.

 - Function: void gcry_mpi_mul_ui (gcry_mpi_t W, gcry_mpi_t U,
          unsigned long V)
     W = U * V.  V is an unsigned integer.

 - Function: void gcry_mpi_mulm (gcry_mpi_t W, gcry_mpi_t U,
          gcry_mpi_t V, gcry_mpi_t M)
     W = U * V \bmod M.

 - Function: void gcry_mpi_mul_2exp (gcry_mpi_t W, gcry_mpi_t U,
          unsigned long E)
     W = U * 2^e.

 - Function: void gcry_mpi_div (gcry_mpi_t Q, gcry_mpi_t R,
          gcry_mpi_t DIVIDEND, gcry_mpi_t DIVISOR, int ROUND)
     Q = DIVIDEND / DIVISOR, R = DIVIDEND \bmod DIVISOR.  Q and R may
     be passed as `NULL'.  ROUND should be negative or 0.

 - Function: void gcry_mpi_mod (gcry_mpi_t R, gcry_mpi_t DIVIDEND,
          gcry_mpi_t DIVISOR)
     R = DIVIDEND \bmod DIVISOR.

 - Function: void gcry_mpi_powm (gcry_mpi_t W, const gcry_mpi_t B,
          const gcry_mpi_t E, const gcry_mpi_t M)
     W = B^e \bmod M.

 - Function: int gcry_mpi_gcd (gcry_mpi_t G, gcry_mpi_t A, gcry_mpi_t B)
     Set G to the greatest common divisor of A and B.  Return true if
     the G is 1.

 - Function: int gcry_mpi_invm (gcry_mpi_t X, gcry_mpi_t A,
          gcry_mpi_t M)
     Set X to the multiplicative inverse of A \bmod M.  Return true if
     the inverse exists.


File: gcrypt.info,  Node: Comparisons,  Next: Bit manipulations,  Prev: Calculations,  Up: MPI library

Comparisons
===========

The next 2 functions are used to compare MPIs:

 - Function: int gcry_mpi_cmp (const gcry_mpi_t U, const gcry_mpi_t V)
     Compare the big integer number U and V returning 0 for equality, a
     positive value for U > V and a negative for U < V.

 - Function: int gcry_mpi_cmp_ui (const gcry_mpi_t U, unsigned long V)
     Compare the big integer number U with the unsigned integer V
     returning 0 for equality, a positive value for U > V and a
     negative for U < V.


File: gcrypt.info,  Node: Bit manipulations,  Next: Misc,  Prev: Comparisons,  Up: MPI library

Bit manipulations
=================

There are a couple of functions to get information on arbitrary bits in
an MPI and to set or clear them:

 - Function: unsigned int gcry_mpi_get_nbits (gcry_mpi_t A)
     Return the number of bits required to represent A.

 - Function: int gcry_mpi_test_bit (gcry_mpi_t A, unsigned int N)
     Return true if bit number N (counting from 0) is set in A.

 - Function: void gcry_mpi_set_bit (gcry_mpi_t A, unsigned int N)
     Set bit number N in A.

 - Function: void gcry_mpi_clear_bit (gcry_mpi_t A, unsigned int N)
     Clear bit number N in A.

 - Function: void gcry_mpi_set_highbit (gcry_mpi_t A, unsigned int N)
     Set bit number N in A and clear all bits greater than N.

 - Function: void gcry_mpi_clear_highbit (gcry_mpi_t A, unsigned int N)
     Clear bit number N in A and all bits greater than N.

 - Function: void gcry_mpi_rshift (gcry_mpi_t X, gcry_mpi_t A,
          unsigned int N)
     Shift the value of A by N bits to the right and store the result
     in X.


File: gcrypt.info,  Node: Misc,  Prev: Bit manipulations,  Up: MPI library

Misc
====

The remaining MPI functions take care of very special properties of the
implementation:

 - Function: gcry_mpi_t gcry_mpi_set_opaque (gcry_mpi_t A, void *P,
          unsigned int NBITS)
     Store NBITS of the value P points to in A and mark A as an opaque
     value (i.e. an value that can't be used for any math calculation
     and is only used to store an arbitrary bit pattern in A.

     WARNING: Never use an opaque MPI for actual math operations.  The
     only valid functions are gcry_mpi_get_opaque and gcry_mpi_release.
     Use gcry_mpi_scan to convert a string of arbitrary bytes into an
     MPI.


 - Function: void * gcry_mpi_get_opaque (gcry_mpi_t A,
          unsigned int *NBITS)
     Return a pointer to an opaque value stored in A and return its
     size in NBITS.  Note, that the returned pointer is still owned by
     A and that the function should never be used for an non-opaque MPI.

 - Function: void gcry_mpi_set_flag (gcry_mpi_t A,
          enum gcry_mpi_flag FLAG)
     Set the FLAG for the MPI A.  Currently only the flag
     `GCRYMPI_FLAG_SECURE' is allowed to convert A into an MPI stored
     in "secure memory".

 - Function: void gcry_mpi_clear_flag (gcry_mpi_t A,
          enum gcry_mpi_flag FLAG)
     Clear FLAG for the big integer A.  Note, that this function is
     currently useless as no flags are allowed.

 - Function: int gcry_mpi_get_flag (gcry_mpi_t A,
          enum gcry_mpi_flag FLAG)
     Return true when the FLAG is set for A.


File: gcrypt.info,  Node: Utilities,  Next: Library Copying,  Prev: MPI library,  Up: Top

Utilities
*********

* Menu:

* Memory allocation::           Functions related with memory allocation.


File: gcrypt.info,  Node: Memory allocation,  Up: Utilities

Memory allocation
=================

 - Function: void *gcry_malloc (size_t N)
     This function tries to allocate N bytes of memory.  On success it
     returns a pointer to the memory area, in an out-of-core condition,
     it returns NULL.

 - Function: void *gcry_malloc_secure (size_t N)
     Like `gcry_malloc', but uses secure memory.

 - Function: void *gcry_calloc (size_t N)
     This function tries to allocate N bytes of cleared memory (i.e.
     memory that is initialized with zero bytes).  On success it
     returns a pointer to the memory area, in an out-of-core condition,
     it returns NULL.

 - Function: void *gcry_calloc_secure (size_t N)
     Like `gcry_calloc', but uses secure memory.

 - Function: void *gcry_realloc (void *P, size_t N)
     This function tries to resize the memory area pointed to by P to N
     bytes.  On success it returns a pointer to the new memory area, in
     an out-of-core condition, it returns NULL.  Depending on wether
     the memory pointed to by P is secure memory or not, gcry_realloc
     tries to use secure memory as well.

 - Function: void gcry_free (void *P)
     Release the memory area pointed to by P.

