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: Working with cipher handles,  Next: General cipher functions,  Prev: Available cipher modes,  Up: Symmetric cryptography

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

   To use a cipher algorithm, you must first allocate an according
handle.  This is to be done using the open function:

 - Function: gcry_error_t gcry_cipher_open (gcry_cipher_hd_t *HD,
     int ALGO, int MODE, unsigned int FLAGS)

     This function creates the context handle required for most of the
     other cipher functions and returns a handle to it in `hd'.  In
     case of an error, an according error code is returned.

     The ID of algorithm to use must be specified via ALGO.  See *Note
     Available ciphers::, for a list of supported ciphers and the
     according constants.

     Besides using the constants directly, the function
     `gcry_cipher_map_name' may be used to convert the textual name of
     an algorithm into the according numeric ID.

     The cipher mode to use must be specified via MODE.  See *Note
     Available cipher modes::, for a list of supported cipher modes and
     the according constants.  Note, that some modes do not work
     together with all algorithms.

     The third argument FLAGS can either be passed as `0' or as the
     bit-wise OR of the following constants.

    `GCRY_CIPHER_SECURE'
          Make sure that all operations are allocated in secure memory.
          This is useful, when the key material is highly confidential.

    `GCRY_CIPHER_ENABLE_SYNC'
          This flag enables the CFB sync mode, which is a special
          feature of Libgcrypt's CFB mode implementation to allow for
          OpenPGP's CFB variant.  See `gcry_cipher_sync'.

    `GCRY_CIPHER_CBC_CTS'
          Enable cipher text stealing (CTS) for the CBC mode.  Cannot
          be used simultaneous as GCRY_CIPHER_CBC_MAC

    `GCRY_CIPHER_CBC_MAC'
          Compute CBC-MAC keyed checksums.  This is the same as CBC
          mode, but only output the last block.  Cannot be used
          simultaneous as GCRY_CIPHER_CBC_CTS.

   Use the following function to release an existing handle:

 - Function: void gcry_cipher_close (gcry_cipher_hd_t H)
     This function releases the context created by `gcry_cipher_open'.

   In order to use a handle for performing cryptographic operations, a
`key' has to be set first:

 - Function: gcry_error_t gcry_cipher_setkey (gcry_cipher_hd_t H, void
          *K, size_t L)
     Set the key K used for encryption or decryption in the context
     denoted by the handle H.  The length L of the key K must match the
     required length of the algorithm set for this context or be in the
     allowed range for algorithms with variable key size.  The function
     checks this and returns an error if there is a problem.  A caller
     should always check for an error.

     Note, this is currently implemented as a macro but may be changed
     to a function in the future.

   Most crypto modes requires an initialization vector (IV), which
usually is a non-secret random string acting as a kind of salt value.
The CTR mode requires a counter, which is also similar to a salt value.
To set the IV or CTR, use these functions:

 - Function: gcry_error_t gcry_cipher_setiv (gcry_cipher_hd_t H, void
          *K, size_t L)
     Set the initialization vector used for encryption or decryption.
     The vector is passed as the buffer K of length L and copied to
     internal data structures.  The function checks that the IV matches
     the requirement of the selected algorithm and mode.  Note, that
     this is implemented as a macro.

 - Function: gcry_error_t gcry_cipher_setctr (gcry_cipher_hd_t H, void
          *C, size_t L)
     Set the counter vector used for encryption or decryption. The
     counter is passed as the buffer C of length L and copied to
     internal data structures.  The function checks that the counter
     matches the requirement of the selected algorithm (i.e., it must be
     the same size as the block size).  Note, that this is implemented
     as a macro.

 - Function: gcry_error_t gcry_cipher_reset (gcry_cipher_hd_t H)
     Set the given handle's context back to the state it had after the
     last call to gcry_cipher_setkey and clear the initialization
     vector.

     Note, that gcry_cipher_reset is implemented as a macro.

   The actual encryption and decryption is done by using one of the
following functions.  They may be used as often as required to process
all the data.

 - Function: gcry_error_t gcry_cipher_encrypt (gcry_cipher_hd_t H,
          unsigned char *out, size_t OUTSIZE, const unsigned char *IN,
          size_t INLEN)
     `gcry_cipher_encrypt' is used to encrypt the data.  This function
     can either work in place or with two buffers.  It uses the cipher
     context already setup and described by the handle H.  There are 2
     ways to use the function: If IN is passed as `NULL' and INLEN is
     `0', in-place encryption of the data in OUT or length OUTSIZE
     takes place.  With IN being not `NULL', INLEN bytes are encrypted
     to the buffer OUT which must have at least a size of INLEN.
     OUTLEN must be set to the allocated size of OUT, so that the
     function can check that there is sufficient space. Note, that
     overlapping buffers are not allowed.

     Depending on the selected algorithms and encryption mode, the
     length of the buffers must be a multiple of the block size.

     The function returns `0' on success or an error code.

 - Function: gcry_error_t gcry_cipher_decrypt (gcry_cipher_hd_t H,
          unsigned char *out, size_t OUTSIZE, const unsigned char *IN,
          size_t INLEN)
     `gcry_cipher_decrypt' is used to decrypt the data.  This function
     can either work in place or with two buffers.  It uses the cipher
     context already setup and described by the handle H.  There are 2
     ways to use the function: If IN is passed as `NULL' and INLEN is
     `0', in-place decryption of the data in OUT or length OUTSIZE
     takes place.  With IN being not `NULL', INLEN bytes are decrypted
     to the buffer OUT which must have at least a size of INLEN.
     OUTLEN must be set to the allocated size of OUT, so that the
     function can check that there is sufficient space. Note, that
     overlapping buffers are not allowed.

     Depending on the selected algorithms and encryption mode, the
     length of the buffers must be a multiple of the block size.

     The function returns `0' on success or an error code.

   OpenPGP (as defined in RFC-2440) requires a special sync operation in
some places, the following function is used for this:

 - Function: gcry_error_t gcry_cipher_sync (gcry_cipher_hd_t H)
     Perform the OpenPGP sync operation on context H. Note, that this
     is a no-op unless the context was created with the flag
     `GCRY_CIPHER_ENABLE_SYNC'

   Some of the described functions are implemented as macros utilizing a
catch-all control function.  This control function is rarely used
directly but there is nothing which would inhibit it:

 - Function: gcry_error_t gcry_cipher_ctl (gcry_cipher_hd_t H, int CMD,
          void *BUFFER, size_t BUFLEN)
     `gcry_cipher_ctl' controls various aspects of the cipher module and
     specific cipher contexts.  Usually some more specialized functions
     or macros are used for this purpose.  The semantics of the
     function and its parameters depends on the the command CMD and the
     passed context handle H.  Please see the comments in the source
     code (`src/global.c') for details.

 - Function: gcry_error_t gcry_cipher_info (gcry_cipher_hd_t H, int
          WHAT, void *BUFFER, size_t *NBYTES)
     `gcry_cipher_info' is used to retrieve various information about a
     cipher context or the cipher module in general.

     Currently no information is available.


File: gcrypt.info,  Node: General cipher functions,  Prev: Working with cipher handles,  Up: Symmetric cryptography

General cipher functions
========================

   To work with the algorithms, several functions are available to map
algorithm names to the internal identifiers, as well as ways to
retrieve information about an algorithm or the current cipher context.

 - Function: gcry_error_t gcry_cipher_algo_info (int ALGO, int WHAT,
          void *BUFFER, size_t *NBYTES)
     This function is used to retrieve information on a specific
     algorithm.  You pass the cipher algorithm ID as ALGO and the type
     of information requested as WHAT. The result is either returned as
     the return code of the function or copied to the provided BUFFER
     whose allocated length must be available in an integer variable
     with the address passed in NBYTES.  This variable will also
     receive the actual used length of the buffer.

     Here is a list of supported codes for WHAT:

    `GCRYCTL_GET_KEYLEN:'
          Return the length of the key. If the algorithm supports
          multiple key lengths, the maximum supported value is
          returned.  The length is returned as number of octets (bytes)
          and not as number of bits in NBYTES; BUFFER must be zero.

    `GCRYCTL_GET_BLKLEN:'
          Return the block length of the algorithm.  The length is
          returned as a number of octets in NBYTES; BUFFER must be zero.

    `GCRYCTL_TEST_ALGO:'
          Returns `0' when the specified algorithm is available for use.
          BUFFER and NBYTES must be zero.


 - Function: const char *gcry_cipher_algo_name (int ALGO)
     `gcry_cipher_algo_name' returns a string with the name of the
     cipher algorithm ALGO.  If the algorithm is not known or another
     error occurred, an empty string is returned.  This function will
     never return `NULL'.

 - Function: int gcry_cipher_map_name (const char *NAME)
     `gcry_cipher_map_name' returns the algorithm identifier for the
     cipher algorithm described by the string NAME.  If this algorithm
     is not available `0' is returned.

 - Function: int gcry_cipher_mode_from_oid (const char *STRING)
     Return the cipher mode associated with an ASN.1 object identifier.
     The object identifier is expected to be in the IETF-style dotted
     decimal notation.  The function returns `0' for an unknown object
     identifier or when no mode is associated with it.


File: gcrypt.info,  Node: Hashing,  Next: Public Key cryptography (I),  Prev: Symmetric cryptography,  Up: Top

Hashing
*******

   Libgcrypt provides an easy and consistent to use interface for
hashing.  Hashing is buffered and several hash algorithms can be
updated at once.  It is possible to calculate a MAC using the same
routines.  The programming model follows an open/process/close paradigm
and is in that similar to other building blocks provided by Libgcrypt.

   For convenience reasons, a few cyclic redudancy check value
operations are also supported.

* Menu:

* Available hash algorithms::   List of hash algorithms supported by the library.
* Hash algorithm modules::      How to work with hash algorithm modules.
* Working with hash algorithms::  List of functions related to hashing.


File: gcrypt.info,  Node: Available hash algorithms,  Next: Hash algorithm modules,  Up: Hashing

Available hash algorithms
=========================

`GCRY_MD_NONE'
     This is not a real algorithm but used by some functions as an error
     return value.  This constant is guaranteed to have the value `0'.

`GCRY_MD_SHA1'
     This is the SHA-1 algorithm which yields a message digest of 20
     bytes.

`GCRY_MD_RMD160'
     This is the 160 bit version of the RIPE message digest
     (RIPE-MD-160).  Like SHA-1 it also yields a digest of 20 bytes.

`GCRY_MD_MD5'
     This is the well known MD5 algorithm, which yields a message
     digest of 16 bytes.

`GCRY_MD_MD4'
     This is the MD4 algorithm, which yields a message digest of 16
     bytes.

`GCRY_MD_MD2'
     This is an reserved identifier for MD-2; there is no
     implementation yet.

`GCRY_MD_TIGER'
     This is the TIGER/192 algorithm which yields a message digest of
     24 bytes.

`GCRY_MD_HAVAL'
     This is an reserved for the HAVAL algorithm with 5 passes and 160
     bit. It yields a message digest of 20 bytes.  Note that there is no
     implementation yet available.

`GCRY_MD_SHA256'
     This is the SHA-256 algorithm which yields a message digest of 32
     bytes.  See FIPS 180-2 for the specification.

`GCRY_MD_SHA384'
     This is reserved for SHA-2 with 384 bits. It yields a message
     digest of 48 bytes.  Note that there is no implementation yet
     available.

`GCRY_MD_SHA512'
     This is reserved for SHA-2 with 512 bits. It yields a message
     digest of 64 bytes.  Note that there is no implementation yet
     available.

`GCRY_MD_CRC32'
     This is the ISO 3309 and ITU-T V.42 cyclic redundancy check.  It
     yields an output of 4 bytes.

`GCRY_MD_CRC32_RFC1510'
     This is the above cyclic redundancy check function, as modified by
     RFC 1510.  It yields an output of 4 bytes.

`GCRY_MD_CRC24_RFC2440'
     This is the OpenPGP cyclic redundancy check function.  It yields an
     output of 3 bytes.


File: gcrypt.info,  Node: Hash algorithm modules,  Next: Working with hash algorithms,  Prev: Available hash algorithms,  Up: Hashing

Hash algorithm modules
======================

   Libgcrypt makes it possible to load additional `message digest
modules'; these cipher can be used just like the message digest
algorithms that are built into the library directly.  For an
introduction into extension modules, see *Note Modules::.

 - Data type: gcry_md_spec_t
     This is the `module specification structure' needed for registering
     message digest modules, which has to be filled in by the user
     before it can be used to register a module.  It contains the
     following members:

    `const char *name'
          The primary name of this algorithm.

    `unsigned char *asnoid'
          Array of bytes that form the ASN OID.

    `int asnlen'
          Length of bytes in `asnoid'.

    `gcry_md_oid_spec_t *oids'
          A list of OIDs that are to be associated with the algorithm.
          The list's last element must have it's `oid' member set to
          NULL.  See below for an explanation of this type.  See below
          for an explanation of this type.

    `int mdlen'
          Length of the message digest algorithm.  See below for an
          explanation of this type.

    `gcry_md_init_t init'
          The function responsible for initializing a handle.  See
          below for an explanation of this type.

    `gcry_md_write_t write'
          The function responsible for writing data into a message
          digest context.  See below for an explanation of this type.

    `gcry_md_final_t final'
          The function responsible for `finalizing' a message digest
          context.  See below for an explanation of this type.

    `gcry_md_read_t read'
          The function reponsible for reading out a message digest
          result.  See below for an explanation of this type.

    `size_t contextsize'
          The size of the algorithm-specific `context', that should be
          allocated for each handle.

 - Data type: gcry_md_oid_spec_t
     This type is used for associating a user-provided algorithm
     implementation with certain OIDs.  It contains the following
     members:

    `const char *oidstring'
          Textual representation of the OID.

 - Data type: gcry_md_init_t
     Type for the `init' function, defined as: void (*gcry_md_init_t)
     (void *c)

 - Data type: gcry_md_write_t
     Type for the `write' function, defined as: void (*gcry_md_write_t)
     (void *c, unsigned char *buf, size_t nbytes)

 - Data type: gcry_md_final_t
     Type for the `final' function, defined as: void (*gcry_md_final_t)
     (void *c)

 - Data type: gcry_md_read_t
     Type for the `read' function, defined as: unsigned char
     *(*gcry_md_read_t) (void *c)

 - Function: gcry_error_t gcry_md_register (gcry_md_spec_t *DIGEST,
          unsigned int *algorithm_id, gcry_module_t *MODULE)
     Register a new digest module whose specification can be found in
     DIGEST.  On success, a new algorithm ID is stored in ALGORITHM_ID
     and a pointer representhing this module is stored in MODULE.

 - Function: void gcry_md_unregister (gcry_module_t MODULE)
     Unregister the digest identified by MODULE, which must have been
     registered with gcry_md_register.

 - Function: gcry_error_t gcry_md_list (int *LIST, int *LIST_LENGTH)
     Get a list consisting of the IDs of the loaded message digest
     modules.  If LIST is zero, write the number of loaded message
     digest modules to LIST_LENGTH and return.  If LIST is non-zero,
     the first *LIST_LENGTH algorithm IDs are stored in LIST, which
     must be of according size.  In case there are less message digests
     modules than *LIST_LENGTH, *LIST_LENGTH is updated to the correct
     number.


File: gcrypt.info,  Node: Working with hash algorithms,  Prev: Hash algorithm modules,  Up: Hashing

Working with hash algorithms
============================

   To use most of these function it is necessary to create a context;
this is done using:

 - Function: gcry_error_t gcry_md_open (gcry_md_hd_t *HD, int ALGO,
          unsigned int FLAGS)
     Create a message digest object for algorithm ALGO.  FLAGS may be
     given as an bitwise OR of constants described below.  ALGO may be
     given as `0' if the algorithms to use are later set using
     `gcry_md_enable'. HD is guaranteed to either receive a valid
     handle or NULL.

     For a list of supported algorithms, see *Note Available hash
     algorithms::.

     The flags allowed for MODE are:

    `GCRY_MD_FLAG_SECURE'
          Allocate all buffers and the resulting digest in "secure
          memory".  Use this is the hashed data is highly confidential.

    `GCRY_MD_FLAG_HMAC'
          Turn the algorithm into a HMAC message authentication
          algorithm.  This does only work if just one algorithm is
          enabled for the handle and SHA-384 and SHA512 is not used.
          Note that the function `gcry_md_setkey' must be used set the
          MAC key.  If you want CBC message authentication codes based
          on a cipher, see *Note Working with cipher handles::.

     You may use the function `gcry_md_is_enabled' to later check
     whether an algorithm has been enabled.


   If you want to calculate several hash algorithms at the same time,
you have to use the following function right after the `gcry_md_open':

 - Function: gcry_error_t gcry_md_enable (gcry_md_hd_t H, int ALGO)
     Add the message digest algorithm ALGO to the digest object
     described by handle H.  Duplicated enabling of algorithms is
     detected and ignored.

   If the flag `GCRY_MD_FLAG_HMAC' was used, the key for the MAC must
be set using the function:

 - Function: gcry_error_t gcry_md_setkey (gcry_md_hd_t H, const void
          *KEY,
     size_t KEYLEN)

     For use with the HMAC feature, set the MAC key to the value of KEY
     of length KEYLEN.

   After you are done with the hash calculation, you should release the
resources by using:

 - Function: void gcry_md_close (gcry_md_hd_t H)
     Release all resources of hash context H.  H should not be used
     after a call to this function.  A `NULL' passed as H is ignored.


   Often you have to do several hash operations using the same
algorithm.  To avoid the overhead of creating and releasing context, a
reset function is provided:

 - Function: void gcry_md_reset (gcry_md_hd_t H)
     Reset the current context to its initial state.  This is
     effectively identical to a close followed by an open and enabling
     all currently active algorithms.

   Often it is necessary to start hashing some data and than continue to
hash different data.  To avoid hashing the same data several times
(which might not even be possible if the data is received from a pipe),
a snapshot of the current hash context can be taken and turned into a
new context:

 - Function: gcry_error_t gcry_md_copy (gcry_md_hd_t *HANDLE_DST,
          gcry_md_hd_t HANDLE_SRC)
     Create a new digest object as an exact copy of the object
     described by handle HANDLE_SRC and store it in HANDLE_DST.  The
     context is not reset and you can continue to hash data using this
     context and independently using the original context.

   Now that we have prepared everything to calculate hashes, its time to
see how it is actually done.  There are 2  ways for this, one to update
the hash with a block of memory and one macro to update the hash by
just one character.  Both may be used intermixed.

 - Function: void gcry_md_write (gcry_md_hd_t H, const void *BUFFER,
          size_t LENGTH)
     Pass LENGTH bytes of the data in BUFFER to the digest object with
     handle H to update the digest values. This function should be used
     for large blocks of data.

 - Function: void gcry_md_putc (gcry_md_hd_t H, int C)
     Pass the byte in C to the digest object with handle H to update
     the digest value.  This is an efficient function, implemented as a
     macro to buffer the data before an actual update.

   The semantics of the hash functions don't allow to read out
intermediate message digests because the calculation must be finalized
fist.  This finalization may for example include the number of bytes
hashed in the message digest.

 - Function: void gcry_md_final (gcry_md_hd_t H)
     Finalize the message digest calculation.  This is not really needed
     because `gcry_md_read' does this implicitly.  After this has been
     done no further updates (by means of `gcry_md_write' or
     `gcry_md_putc' are allowed.  Only the first call to this function
     has an effect. It is implemented as a macro.

   The way to read out the calculated message digest is by using the
function:

 - Function: unsigned char *gcry_md_read (gcry_md_hd_t H, int ALGO)
     `gcry_md_read' returns the message digest after finalizing the
     calculation.  This function may be used as often as required but
     it will always return the same value for one handle.  The returned
     message digest is allocated within the message context and
     therefore valid until the handle is released or reseted (using
     `gcry_md_close' or `gcry_md_reset'.  ALGO may be given as 0 to
     return the only enabled message digest or it may specify one of
     the enabled algorithms.  The function does return `NULL' if the
     requested algorithm has not been enabled.

   Because it is often necessary to get the message digest of one block
of memory, a fast convenience function is available for this task:

 - Function: void gcry_md_hash_buffer (int ALGO, void *DIGEST, const
          cvoid *BUFFER, size_t LENGTH);
     `gcry_md_hash_buffer' is a shortcut function to calculate a message
     digest of a buffer.  This function does not require a context and
     immediately returns the message digest of the LENGTH bytes at
     BUFFER.  DIGEST must be allocated by the caller, large enough to
     hold the message digest yielded by the the specified algorithm
     ALGO.  This required size may be obtained by using the function
     `gcry_md_get_algo_dlen'.

     Note, that this function will abort the process if an unavailable
     algorithm is used.

   Hash algorithms are identified by internal algorithm numbers (see
`gcry_md_open' for a list.  However, in most applications they are used
by names, so 2 functions are available to map between string
representations and hash algorithm identifiers.

 - Function: const char *gcry_md_algo_name (int ALGO)
     Map the digest algorithm id ALGO to a string representation of the
     algorithm name.  For unknown algorithms this functions returns an
     empty string.  This function should not be used to test for the
     availability of an algorithm.

 - Function: int gcry_md_map_name (const char *NAME)
     Map the algorithm with NAME to a digest algorithm identifier.
     Returns 0 if the algorithm name is not known.  Names representing
     ASN.1 object identifiers are recognized if the IETF dotted format
     is used and the OID is prefixed with either "`oid.'" or "`OID.'".
     For a list of supported OIDs, see the source code at
     `cipher/md.c'. This function should not be used to test for the
     availability of an algorithm.

 - Function: gcry_error_t gcry_md_get_asnoid (int ALGO, void *BUFFER,
          size_t *LENGTH)
     Return an DER encoded ASN.1 OID for the algorithm ALGO in the user
     allocated BUFFER. LENGTH must point to variable with the available
     size of BUFFER and receives after return the actual size of the
     returned OID.  The returned error code may be `GPG_ERR_TOO_SHORT'
     if the provided buffer is to short to receive the OID; it is
     possible to call the function with `NULL' for BUFFER to have it
     only return the required size.  The function returns 0 on success.


   To test whether an algorithm is actually available for use, the
following macro should be used:

 - Function: gcry_error_t gcry_md_test_algo (int ALGO)
     The macro returns 0 if the algorithm ALGO is available for use.

   If the length of a message digest is not known, it can be retrieved
using the following function:

 - Function: unsigned int gcry_md_get_algo_dlen (int ALGO)
     Retrieve the length in bytes of the digest yielded by algorithm
     ALGO.  This is often used prior to `gcry_md_read' to allocate
     sufficient memory for the digest.

   In some situations it might be hard to remember the algorithm used
for the ongoing hashing. The following function might be used to get
that information:

 - Function: int gcry_md_get_algo (gcry_md_hd_t H)
     Retrieve the algorithm used with the handle H. Note, that this
     does not work reliable if more than one algorithm is enabled in H.

   The following macro might also be useful:

 - Function: int gcry_md_is_secure (gcry_md_hd_t H)
     This function returns true when the digest object H is allocated
     in "secure memory"; i.e. H was created with the
     `GCRY_MD_FLAG_SECURE'.

 - Function: int gcry_md_is_enabled (gcry_md_hd_t H, int ALGO)
     This function returns true when the algorithm ALGO has been
     enabled for the digest object H.

   Tracking bugs related to hashing is often a cumbersome task which
requires to add a lot of printf statements into the code.  Libgcrypt
provides an easy way to avoid this.  The actual data hashed can be
written to files on request.  The following 2 macros should be used to
implement such a debugging facility:

 - Function: void gcry_md_start_debug (gcry_md_hd_t H, const char
          *SUFFIX)
     Enable debugging for the digest object with handle H.  This
     creates create files named `dbgmd-<n>.<string>' while doing the
     actual hashing.  SUFFIX is the string part in the filename.  The
     number is a counter incremented for each new hashing.  The data in
     the file is the raw data as passed to `gcry_md_write' or
     `gcry_md_putc'.

 - Function: void gcry_md_stop_debug (gcry_md_hd_t H, int RESERVED)
     Stop debugging on handle H.  RESERVED should be specified as 0.
     This function is usually not required because `gcry_md_close' does
     implicitly stop debugging.


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

Public Key cryptography (I)
***************************

   Public key cryptography, also known as asymmetric cryptography, is an
easy way for key management and to provide digital signatures.
Libgcrypt provides two completely different interfaces to public key
cryptography, this chapter explains the one based on S-expressions.

* Menu:

* Available algorithms::        Algorithms supported by the library.
* Used S-expressions::          Introduction into the used S-expression.
* Public key modules::          How to work with public key modules.
* Cryptographic Functions::     Functions for performing the cryptographic actions.
* General public-key related Functions::  General functions, not implementing any cryptography.


File: gcrypt.info,  Node: Available algorithms,  Next: Used S-expressions,  Up: Public Key cryptography (I)

Available 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.


File: gcrypt.info,  Node: Used S-expressions,  Next: Public key modules,  Prev: Available algorithms,  Up: Public Key cryptography (I)

Used S-expressions
==================

   Libgcrypt's API for asymmetric cryptography is based on data
structures called S-expressions (see XXXX) and does not work with
contexts as most of the other building blocks of Libgcrypt do.

   The following information are stored in S-expressions:

keys

plain text data

encrypted data

signatures
To describe how Libgcrypt expect keys, we use some examples. Note that
words in uppercase indicate parameters whereas lowercase words are
literals.

     (private-key
       (dsa
         (p P-MPI)
         (q Q-MPI)
         (g G-MPI)
         (y Y-MPI)
         (x X-MPI)))

This specifies a DSA private key with the following parameters:

P-MPI
     DSA prime p.

Q-MPI
     DSA group order q (which is a prime divisor of p-1).

G-MPI
     DSA group generator g.

Y-MPI
     DSA public key value y = g^x \bmod p.

X-MPI
     DSA secret exponent x.

   All the MPI values are  expected to be in `GCRYMPI_FMT_USG' format.
The public key is similar with "private-key" replaced by "public-key"
and no X-MPI.

   An easy way to create such an S-expressions is by using
`gcry_sexp_build' which allows to pass a string with printf-like
escapes to insert MPI values.

Here is an example for an RSA key:

     (private-key
       (rsa
         (n N-MPI)
         (e E-MPI)
         (d D-MPI)
         (p P-MPI)
         (q Q-MPI)
         (u U-MPI)

with

N-MPI
     RSA public modulus n.

E-MPI
     RSA public exponent e.

D-MPI
     RSA secret exponent d = e^-1 \bmod (p-1)(q-1).

P-MPI
     RSA secret prime p.

Q-MPI
     RSA secret prime q with q > p.

U-MPI
     multiplicative inverse u = p^-1 \bmod q.


File: gcrypt.info,  Node: Public key modules,  Next: Cryptographic Functions,  Prev: Used S-expressions,  Up: Public Key cryptography (I)

Public key modules
==================

   Libgcrypt makes it possible to load additional `public key modules';
these public key algorithms can be used just like the algorithms that
are built into the library directly.  For an introduction into
extension modules, see *Note Modules::.

 - Data type: gcry_pk_spec_t
     This is the `module specification structure' needed for registering
     public key modules, which has to be filled in by the user before it
     can be used to register a module.  It contains the following
     members:

    `const char *name'
          The primary name of this algorithm.

    `char **aliases'
          A list of strings that are `aliases' for the algorithm.  The
          list musdt be terminanted with a NULL element.

    `const char *elements_pkey'
          String containing the one-letter names of the MPI values
          contained in a public key.

    `const char *element_skey'
          String containing the one-letter names of the MPI values
          contained in a secret key.

    `const char *elements_enc'
          String containing the one-letter names of the MPI values that
          are the result of an encryption operation using this
          algorithm.

    `const char *elements_sig'
          String containing the one-letter names of the MPI values that
          are the result of a sign operation using this algorithm.

    `const char *elements_grip'
          String containing the one-letter names of the MPI values that
          are to be included in the `key grip'.

    `int use'
          The bitwise-OR of the following flags, depending on the
          abilities of the algortihm:
         `GCRY_PK_USAGE_SIGN'
               The algorithm supports signing and verifying of data.

         `GCRY_PK_USAGE_ENCR'
               The algorithm supports the encryption and decryption of
               data.

    `gcry_pk_generate_t generate'
          The function responsible for generating a new key pair.  See
          below for a description of this type.

    `gcry_pk_check_secret_key_t check_secret_key'
          The function responsible for checking the sanity of a
          provided secret key.  See below for a description of this
          type.

    `gcry_pk_encrypt_t encrypt'
          The function responsible for encrypting data.  See below for a
          description of this type.

    `gcry_pk_decrypt_t decrypt'
          The function responsible for decrypting data.  See below for a
          description of this type.

    `gcry_pk_sign_t sign'
          The function reponsible for signing data.  See below for a
          description of this type.

    `gcry_pk_verify_t verify'
          The function responsible for verifying that the provided
          signature matches the provided data.  See below for a
          description of this type.

    `gcry_pk_get_nbits_t get_nbits'
          The function reponsible for returning the number of bits of a
          provided key.  See below for a description of this type.

 - Data type: gcry_pk_generate_t
     Type for the `generate' function, defined as: gcry_err_code_t
     (*gcry_pk_generate_t) (int algo, unsigned int nbits, unsigned long
     use_e, gcry_mpi_t *skey, gcry_mpi_t **retfactors)

 - Data type: gcry_pk_check_secret_key_t
     Type for the `check_secret_key' function, defined as:
     gcry_err_code_t (*gcry_pk_check_secret_key_t) (int algo,
     gcry_mpi_t *skey)

 - Data type: gcry_pk_encrypt_t
     Type for the `encrypt' function, defined as: gcry_err_code_t
     (*gcry_pk_encrypt_t) (int algo, gcry_mpi_t *resarr, gcry_mpi_t
     data, gcry_mpi_t *pkey, int flags)

 - Data type: gcry_pk_decrypt_t
     Type for the `decrypt' function, defined as: gcry_err_code_t
     (*gcry_pk_decrypt_t) (int algo, gcry_mpi_t *result, gcry_mpi_t
     *data, gcry_mpi_t *skey, int flags)

 - Data type: gcry_pk_sign_t
     Type for the `sign' function, defined as: gcry_err_code_t
     (*gcry_pk_sign_t) (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
     gcry_mpi_t *skey)

 - Data type: gcry_pk_verify_t
     Type for the `verify' function, defined as: gcry_err_code_t
     (*gcry_pk_verify_t) (int algo, gcry_mpi_t hash, gcry_mpi_t *data,
     gcry_mpi_t *pkey, int (*cmp) (void *, gcry_mpi_t), void *opaquev)

 - Data type: gcry_pk_get_nbits_t
     Type for the `get_nbits' function, defined as: unsigned
     (*gcry_pk_get_nbits_t) (int algo, gcry_mpi_t *pkey)

 - Function: gcry_error_t gcry_pk_register (gcry_pk_spec_t *PUBKEY,
          unsigned int *algorithm_id, gcry_module_t *MODULE)
     Register a new public key module whose specification can be found
     in PUBKEY.  On success, a new algorithm ID is stored in
     ALGORITHM_ID and a pointer representhing this module is stored in
     MODULE.

 - Function: void gcry_pk_unregister (gcry_module_t MODULE)
     Unregister the public key module identified by MODULE, which must
     have been registered with gcry_pk_register.

 - Function: gcry_error_t gcry_pk_list (int *LIST, int *LIST_LENGTH)
     Get a list consisting of the IDs of the loaded pubkey modules.  If
     LIST is zero, write the number of loaded pubkey modules to
     LIST_LENGTH and return.  If LIST is non-zero, the first
     *LIST_LENGTH algorithm IDs are stored in LIST, which must be of
     according size.  In case there are less pubkey modules than
     *LIST_LENGTH, *LIST_LENGTH is updated to the correct number.


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

Cryptographic Functions
=======================

Note, that we will in future allow to use keys without p,q and u
specified and may also support other parameters for performance reasons.

Some functions operating on S-expressions support `flags', that
influence the operation.  These flags have to be listed in a
sub-S-expression named `flags'; the following flags are known:

PKCS1
     Use PKCS#1 block type 2 padding.

NO-BLINDING
     Do not use a technique called `blinding', which is used by default
     in order to prevent leaking of secret information.  Blinding is
     only implemented by RSA, but it might be implemented by other
     algorithms in the future as well, when necessary.

Now that we know the key basics, we can carry on and explain how to
encrypt and decrypt data.  In almost all cases the data is a random
session key which is in turn used for the actual encryption of the real
data.  There are 2 functions to do this:

 - Function: gcry_error_t gcry_pk_encrypt (gcry_sexp_t *R_CIPH,
          gcry_sexp_t DATA, gcry_sexp_t PKEY)
     Obviously a public key must be provided for encryption.  It is
     expected as an appropriate S-expression (see above) in PKEY.  The
     data to be encrypted can either be in the simple old format, which
     is a very simple S-expression consisting only of one MPI, or it
     may be a more complex S-expression which also allows to specify
     flags for operation, like e.g. padding rules.

     If you don't want to let Libgcrypt handle the padding, you must
     pass an appropriate MPI using this expression for DATA:

          (data
            (flags raw)
            (value MPI))

     This has the same semantics as the old style MPI only way.  MPI is
     the actual data, already padded appropriate for your protocol.
     Most systems however use PKCS#1 padding and so you can use this
     S-expression for DATA:

          (data
            (flags pkcs1)
            (value BLOCK))

     Here, the "flags" list has the "pkcs1" flag which let the function
     know that it should provide PKCS#1 block type 2 padding.  The
     actual data to be encrypted is passed as a string of octets in
     BLOCK.  The function checks that this data actually can be used
     with the given key, does the padding and encrypts it.

     If the function could successfully perform the encryption, the
     return value will be 0 and a a new S-expression with the encrypted
     result is allocated and assign to the variable at the address of
     R_CIPH.  The caller is responsible to release this value using
     `gcry_sexp_release'.  In case of an error, an error code is
     returned and R_CIPH will be set to `NULL'.

     The returned S-expression has this format when used with RSA:

          (enc-val
            (rsa
              (a A-MPI)))

     Where A-MPI is an MPI with the result of the RSA operation.  When
     using the ElGamal algorithm, the return value will have this
     format:

          (enc-val
            (elg
              (a A-MPI)
              (b B-MPI)))

     Where A-MPI and B-MPI are MPIs with the result of the ElGamal
     encryption operation.

 - Function: gcry_error_t gcry_pk_decrypt (gcry_sexp_t *R_PLAIN,
          gcry_sexp_t DATA, gcry_sexp_t SKEY)
     Obviously a private key must be provided for decryption.  It is
     expected as an appropriate S-expression (see above) in SKEY.  The
     data to be decrypted must match the format of the result as
     returned by `gcry_pk_encrypt', but should be enlarged with a
     `flags' element:

          (enc-val
            (flags)
            (elg
              (a A-MPI)
              (b B-MPI)))

     Note, that this function currently does not know of any padding
     methods and the caller must do any un-padding on his own.

     The function returns 0 on success or an error code.  The variable
     at the address of R_PLAIN will be set to NULL on error or receive
     the decrypted value on success.  The format of R_PLAIN is a simple
     S-expression part (i.e. not a valid one) with just one MPI if
     there was no `flags' element in DATA; if at least an empty `flags'
     is passed in DATA, the format is:

          (value PLAINTEXT)

   Another operation commonly performed using public key cryptography is
signing data.  In some sense this is even more important than
encryption because digital signatures are an important instrument for
key management.  Libgcrypt supports digital signatures using 2
functions, similar to the encryption functions:

 - Function: gcry_error_t gcry_pk_sign (gcry_sexp_t *R_SIG,
          gcry_sexp_t DATA, gcry_sexp_t SKEY)
     This function creates a digital signature for DATA using the
     private key SKEY and place it into the variable at the address of
     R_SIG.  DATA may either be the simple old style S-expression with
     just one MPI or a modern and more versatile S-expression which
     allows to let Libgcrypt handle padding:

           (data
            (flags pkcs1)
            (hash HASH-ALGO BLOCK))

     This example requests to sign the data in BLOCK after applying
     PKCS#1 block type 1 style padding.  HASH-ALGO is a string with the
     hash algorithm to be encoded into the signature, this may be any
     hash algorithm name as supported by Libgcrypt.  Most likely, this
     will be "sha1", "rmd160" or "md5".  It is obvious that the length
     of BLOCK must match the size of that message digests; the function
     checks that this and other constraints are valid.

     If PKCS#1 padding is not required (because the caller does already
     provide a padded value), either the old format or better the
     following format should be used:

          (data
            (flags raw)
            (value MPI))

     Here, the data to be signed is directly given as an MPI.

     The signature is returned as a newly allocated S-expression in
     R_SIG using this format for RSA:

          (sig-val
            (rsa
              (s S-MPI)))

     Where S-MPI is the result of the RSA sign operation.  For DSA the
     S-expression returned is:

          (sig-val
            (dsa
              (r R-MPI)
              (s S-MPI)))

     Where R-MPI and S-MPI are the result of the DSA sign operation.
     For ElGamal signing (which is slow, yields large numbers and
     probably is not as secure as the other algorithms), the same
     format is used with "elg" replacing "dsa".

The operation most commonly used is definitely the verification of a
signature.  Libgcrypt provides this function:

 - Function: gcry_error_t gcry_pk_verify (gcry_sexp_t SIG,
          gcry_sexp_t DATA, gcry_sexp_t PKEY)
     This is used to check whether the signature SIG matches the DATA.
     The public key PKEY must be provided to perform this verification.
     This function is similar in its parameters to `gcry_pk_sign' with
     the exceptions that the public key is used instead of the private
     key and that no signature is created but a signature, in a format
     as created by `gcry_pk_sign', is passed to the function in SIG.

     The result is 0 for success (i.e. the data matches the signature),
     or an error code where the most relevant code is
     `GCRYERR_BAD_SIGNATURE' to indicate that the signature does not
     match the provided data.


