1 \input texinfo @c -*- Texinfo -*-
3 @setfilename gcrypt.info
5 @settitle The Libgcrypt Reference Manual
6 @c Unify some of the indices.
11 This manual is for Libgcrypt
12 (version @value{VERSION}, @value{UPDATED}),
13 which is GNU's library of cryptographic building blocks.
15 Copyright @copyright{} 2000, 2002, 2003, 2004, 2006, 2007 Free Software Foundation, Inc.
18 Permission is granted to copy, distribute and/or modify this document
19 under the terms of the GNU General Public License as published by the
20 Free Software Foundation; either version 2 of the License, or (at your
21 option) any later version. The text of the license can be found in the
22 section entitled ``Copying''.
26 @dircategory GNU Libraries
28 * libgcrypt: (gcrypt). Cryptographic function library.
36 @setchapternewpage odd
38 @title The Libgcrypt Reference Manual
39 @subtitle Version @value{VERSION}
40 @subtitle @value{UPDATED}
41 @author Werner Koch (@email{wk@@gnupg.org})
42 @author Moritz Schulte (@email{mo@@g10code.com})
45 @vskip 0pt plus 1filll
58 @top The Libgcrypt Library
64 * Introduction:: What is Libgcrypt.
65 * Preparation:: What you should do before using the library.
66 * Generalities:: General library functions and data types.
67 * Handler Functions:: Working with handler functions.
68 * Symmetric cryptography:: How to use symmetric cryptography.
69 * Hashing:: How to use hashing.
70 * Public Key cryptography (I):: How to use public key cryptography.
71 * Public Key cryptography (II):: How to use public key cryptography, alternatively.
72 * Random Numbers:: How to work with random numbers.
73 * S-expressions:: How to manage S-expressions.
74 * MPI library:: How to work with multi-precision-integers.
75 * Prime numbers:: How to use the Prime number related functions.
76 * Utilities:: Utility functions.
80 * Library Copying:: The GNU Lesser General Public License
81 says how you can copy and share Libgcrypt.
82 * Copying:: The GNU General Public License says how you
83 can copy and share some parts of Libgcrypt.
87 * Concept Index:: Index of concepts and programs.
88 * Function and Data Index:: Index of functions, variables and data types.
91 --- The Detailed Node Listing ---
94 * Getting Started:: How to use this manual.
95 * Features:: A glance at Libgcrypt's features.
96 * Overview:: Overview about the library.
99 * Header:: What header file you need to include.
100 * Building sources:: How to build sources using the library.
101 * Building sources using Automake:: How to build sources with the help of Automake.
102 * Initializing the library:: How to initialize the library.
103 * Multi-Threading:: How Libgcrypt can be used in a MT environment.
106 * Controlling the library:: Controlling Libgcrypt's behavior.
107 * Modules:: Description of extension modules.
108 * Error Handling:: Error codes and such.
111 * Progress handler:: Using a progress handler function.
112 * Allocation handler:: Using special memory allocation functions.
113 * Error handler:: Using error handler functions.
114 * Logging handler:: Using a special logging function.
116 Symmetric cryptography
117 * Available ciphers:: List of ciphers supported by the library.
118 * Cipher modules:: How to work with cipher modules.
119 * Available cipher modes:: List of cipher modes supported by the library.
120 * Working with cipher handles:: How to perform operations related to cipher handles.
121 * General cipher functions:: General cipher functions independent of cipher handles.
124 * Available hash algorithms:: List of hash algorithms supported by the library.
125 * Hash algorithm modules:: How to work with hash algorithm modules.
126 * Working with hash algorithms:: List of functions related to hashing.
128 Public Key cryptography (I)
129 * Used S-expressions:: Introduction into the used S-expression.
130 * Available algorithms:: Algorithms supported by the library.
131 * Public key modules:: How to work with public key modules.
132 * Cryptographic Functions:: Functions for performing the cryptographic actions.
133 * General public-key related Functions:: General functions, not implementing any cryptography.
135 Public Key cryptography (II)
136 * Available asymmetric algorithms:: List of algorithms supported by the library.
137 * Working with sets of data:: How to work with sets of data.
138 * Working with handles:: How to use handles.
139 * Working with keys:: How to work with keys.
140 * Using cryptographic functions:: How to perform cryptographic operations.
141 * Handle-independent functions:: General functions independent of handles.
144 * Quality of random numbers:: Libgcrypt uses different quality levels.
145 * Retrieving random numbers:: How to retrieve random numbers.
148 * Data types for S-expressions:: Data types related with S-expressions.
149 * Working with S-expressions:: How to work with S-expressions.
152 * Data types:: MPI related data types.
153 * Basic functions:: First steps with MPI numbers.
154 * MPI formats:: External representation of MPIs.
155 * Calculations:: Performing MPI calculations.
156 * Comparisons:: How to compare MPI values.
157 * Bit manipulations:: How to access single bits of MPI values.
158 * Miscellaneous:: Miscellaneous MPI functions.
161 * Generation:: Generation of new prime numbers.
162 * Checking:: Checking if a given number is prime.
165 * Memory allocation:: Functions related with memory allocation.
179 @c **********************************************************
180 @c ******************* Introduction ***********************
181 @c **********************************************************
183 @chapter Introduction
184 Libgcrypt is a library providing cryptographic building blocks.
187 * Getting Started:: How to use this manual.
188 * Features:: A glance at Libgcrypt's features.
189 * Overview:: Overview about the library.
192 @node Getting Started
193 @section Getting Started
195 This manual documents the Libgcrypt library application programming
196 interface (API). All functions and data types provided by the library
200 The reader is assumed to possess basic knowledge about applied
203 This manual can be used in several ways. If read from the beginning
204 to the end, it gives a good introduction into the library and how it
205 can be used in an application. Forward references are included where
206 necessary. Later on, the manual can be used as a reference manual to
207 get just the information needed about any particular interface of the
208 library. Experienced programmers might want to start looking at the
209 examples at the end of the manual, and then only read up those parts
210 of the interface which are unclear.
216 Libgcrypt might have a couple of advantages over other libraries doing
220 @item It's Free Software
221 Anybody can use, modify, and redistribute it under the terms of the GNU
222 Lesser General Public License (@pxref{Library Copying}). Note, that
223 some parts (which are not needed on a GNU or GNU/Linux system) are
224 subject to the terms of the GNU General Public License
225 (@pxref{Copying}); please see the README file of the distribution for of
228 @item It encapsulates the low level cryptography
229 Libgcrypt provides a high level interface to cryptographic
230 building blocks using an extensible and flexible API.
238 The Libgcrypt library is fully thread-safe, where it makes
239 sense to be thread-safe. Not thread-safe are some cryptographic
240 functions that modify a certain context stored in handles. If the
241 user really intents to use such functions from different threads on
242 the same handle, he has to take care of the serialization of such
243 functions himself. If not described otherwise, every function is
246 Libgcrypt depends on the library `libgpg-error', which
247 contains common error handling related code for GnuPG components.
249 @c **********************************************************
250 @c ******************* Preparation ************************
251 @c **********************************************************
255 To use Libgcrypt, you have to perform some changes to your
256 sources and the build system. The necessary changes are small and
257 explained in the following sections. At the end of this chapter, it
258 is described how the library is initialized, and how the requirements
259 of the library are verified.
262 * Header:: What header file you need to include.
263 * Building sources:: How to build sources using the library.
264 * Building sources using Automake:: How to build sources with the help of Automake.
265 * Initializing the library:: How to initialize the library.
266 * Multi-Threading:: How Libgcrypt can be used in a MT environment.
273 All interfaces (data types and functions) of the library are defined
274 in the header file `gcrypt.h'. You must include this in all source
275 files using the library, either directly or through some other header
282 The name space of Libgcrypt is @code{gcry_*} for function
283 and type names and @code{GCRY*} for other symbols. In addition the
284 same name prefixes with one prepended underscore are reserved for
285 internal use and should never be used by an application. Note that
286 Libgcrypt uses libgpg-error, which uses @code{gpg_*} as
287 name space for function and type names and @code{GPG_*} for other
288 symbols, including all the error codes.
291 @node Building sources
292 @section Building sources
294 If you want to compile a source file including the `gcrypt.h' header
295 file, you must make sure that the compiler can find it in the
296 directory hierarchy. This is accomplished by adding the path to the
297 directory in which the header file is located to the compilers include
298 file search path (via the @option{-I} option).
300 However, the path to the include file is determined at the time the
301 source is configured. To solve this problem, Libgcrypt ships with a small
302 helper program @command{libgcrypt-config} that knows the path to the
303 include file and other configuration options. The options that need
304 to be added to the compiler invocation at compile time are output by
305 the @option{--cflags} option to @command{libgcrypt-config}. The following
306 example shows how it can be used at the command line:
309 gcc -c foo.c `libgcrypt-config --cflags`
312 Adding the output of @samp{libgcrypt-config --cflags} to the compilers
313 command line will ensure that the compiler can find the Libgcrypt header
316 A similar problem occurs when linking the program with the library.
317 Again, the compiler has to find the library files. For this to work,
318 the path to the library files has to be added to the library search path
319 (via the @option{-L} option). For this, the option @option{--libs} to
320 @command{libgcrypt-config} can be used. For convenience, this option
321 also outputs all other options that are required to link the program
322 with the Libgcrypt libraries (in particular, the @samp{-lgcrypt}
323 option). The example shows how to link @file{foo.o} with the Libgcrypt
324 library to a program @command{foo}.
327 gcc -o foo foo.o `libgcrypt-config --libs`
330 Of course you can also combine both examples to a single command by
331 specifying both options to @command{libgcrypt-config}:
334 gcc -o foo foo.c `libgcrypt-config --cflags --libs`
337 @node Building sources using Automake
338 @section Building sources using Automake
340 It is much easier if you use GNU Automake instead of writing your own
341 Makefiles. If you do that, you do not have to worry about finding and
342 invoking the @command{libgcrypt-config} script at all.
343 Libgcrypt provides an extension to Automake that does all
346 @c A simple macro for optional variables.
348 @r{[}@var{\varname\}@r{]}
350 @defmac AM_PATH_LIBGCRYPT (@ovar{minimum-version}, @ovar{action-if-found}, @ovar{action-if-not-found})
351 Check whether Libgcrypt (at least version
352 @var{minimum-version}, if given) exists on the host system. If it is
353 found, execute @var{action-if-found}, otherwise do
354 @var{action-if-not-found}, if given.
356 Additionally, the function defines @code{LIBGCRYPT_CFLAGS} to the
357 flags needed for compilation of the program to find the
358 @file{gcrypt.h} header file, and @code{LIBGCRYPT_LIBS} to the linker
359 flags needed to link the program to the Libgcrypt library.
362 You can use the defined Autoconf variables like this in your
366 AM_CPPFLAGS = $(LIBGCRYPT_CFLAGS)
367 LDADD = $(LIBGCRYPT_LIBS)
370 @node Initializing the library
371 @section Initializing the library
373 Before the library can be used, it must initialize itself. This is
374 achieved by invoking the function @code{gcry_check_version} described
377 Also, it is often desirable to check that the version of
378 Libgcrypt used is indeed one which fits all requirements.
379 Even with binary compatibility, new features may have been introduced,
380 but due to problem with the dynamic linker an old version may actually
381 be used. So you may want to check that the version is okay right
382 after program startup.
384 @deftypefun const char *gcry_check_version (const char *@var{req_version})
386 The function @code{gcry_check_version} initializes the sub-systems
387 used by Libgcrypt and must be invoked before any other function in the
388 library, with the exception of the @code{GCRYCTL_SET_THREAD_CBS}
389 command (called via the @code{gcry_control} function), see
390 @xref{Multi-Threading}.
392 Furthermore, this function returns the version number of the library.
393 It can also verify that the version number is higher than a certain
394 required version number @var{req_version}, if this value is not a null
399 @node Multi-Threading
400 @section Multi-Threading
402 As mentioned earlier, the Libgcrypt library is
403 thread-safe if you adhere to the following requirements:
407 If your application is multi-threaded, you must set the thread support
408 callbacks with the @code{GCRYCTL_SET_THREAD_CBS} command
409 @strong{before} any other function in the library.
411 This is easy enough if you are indeed writing an application using
412 Libgcrypt. It is rather problematic if you are writing a library
413 instead. Here are some tips what to do if you are writing a library:
415 If your library requires a certain thread package, just initialize
416 Libgcrypt to use this thread package. If your library supports multiple
417 thread packages, but needs to be configured, you will have to
418 implement a way to determine which thread package the application
419 wants to use with your library anyway. Then configure Libgcrypt to use
422 If your library is fully reentrant without any special support by a
423 thread package, then you are lucky indeed. Unfortunately, this does
424 not relieve you from doing either of the two above, or use a third
425 option. The third option is to let the application initialize Libgcrypt
426 for you. Then you are not using Libgcrypt transparently, though.
428 As if this was not difficult enough, a conflict may arise if two
429 libraries try to initialize Libgcrypt independently of each others, and
430 both such libraries are then linked into the same application. To
431 make it a bit simpler for you, this will probably work, but only if
432 both libraries have the same requirement for the thread package. This
433 is currently only supported for the non-threaded case, GNU Pth and
434 pthread. Support for more thread packages is easy to add, so contact
435 us if you require it.
438 The function @code{gcry_check_version} must be called before any other
439 function in the library, except the @code{GCRYCTL_SET_THREAD_CBS}
440 command (called via the @code{gcry_control} function), because it
441 initializes the thread support subsystem in Libgcrypt. To
442 achieve this in multi-threaded programs, you must synchronize the
443 memory with respect to other threads that also want to use
444 Libgcrypt. For this, it is sufficient to call
445 @code{gcry_check_version} before creating the other threads using
446 Libgcrypt@footnote{At least this is true for POSIX threads,
447 as @code{pthread_create} is a function that synchronizes memory with
448 respects to other threads. There are many functions which have this
449 property, a complete list can be found in POSIX, IEEE Std 1003.1-2003,
450 Base Definitions, Issue 6, in the definition of the term ``Memory
451 Synchronization''. For other thread packages, more relaxed or more
452 strict rules may apply.}.
456 Just like the function @code{gpg_strerror}, the function
457 @code{gcry_strerror} is not thread safe. You have to use
458 @code{gpg_strerror_r} instead.
462 Libgcrypt contains convenient macros, which define the
463 necessary thread callbacks for PThread and for GNU Pth:
466 @item GCRY_THREAD_OPTION_PTH_IMPL
468 This macro defines the following (static) symbols: gcry_pth_init,
469 gcry_pth_mutex_init, gcry_pth_mutex_destroy, gcry_pth_mutex_lock,
470 gcry_pth_mutex_unlock, gcry_pth_read, gcry_pth_write, gcry_pth_select,
471 gcry_pth_waitpid, gcry_pth_accept, gcry_pth_connect, gcry_threads_pth.
473 After including this macro, gcry_control() shall be used with a
474 command of GCRYCTL_SET_THREAD_CBS in order to register the thread
475 callback structure named ``gcry_threads_pth''.
477 @item GCRY_THREAD_OPTION_PTHREAD_IMPL
479 This macro defines the following (static) symbols:
480 gcry_pthread_mutex_init, gcry_pthread_mutex_destroy, gcry_mutex_lock,
481 gcry_mutex_unlock, gcry_threads_pthread.
483 After including this macro, gcry_control() shall be used with a
484 command of GCRYCTL_SET_THREAD_CBS in order to register the thread
485 callback structure named ``gcry_threads_pthread''.
488 Note that these macros need to be terminated with a semicolon. Keep
489 in mind that these are convenient macros for C programmers; C++
490 programmers might have to wrap these macros in an ``extern C'' body.
492 @c **********************************************************
493 @c ******************* General ****************************
494 @c **********************************************************
496 @chapter Generalities
499 * Controlling the library:: Controlling Libgcrypt's behavior.
500 * Modules:: Description of extension modules.
501 * Error Handling:: Error codes and such.
504 @node Controlling the library
505 @section Controlling the library
507 @deftypefun gcry_error_t gcry_control (enum gcry_ctl_cmds @var{cmd}, ...)
509 This function can be used to influence the general behavior of
510 Libgcrypt in several ways. Depending on @var{cmd}, more
511 arguments can or have to be provided.
514 @item GCRYCTL_ENABLE_M_GUARD; Arguments: none
515 This command enables the built-in memory guard. It must not be used to
516 activate the memory guard after the memory management has already been
517 used; therefore it can ONLY be used at initialization time. Note that
518 the memory guard is NOT used when the user of the library has set his
519 own memory management callbacks.
521 @item GCRYCTL_ENABLE_QUICK_RANDOM; Arguments: none
522 This command activates the use of a highly-insecure, but fast PRNG. It
523 can only be used at initialization time. The only useful applications
524 for this are certain regression tests.
526 @item GCRYCTL_DUMP_RANDOM_STATS
527 This command dumps PRNG related statistics to the librarys logging
530 @item GCRYCTL_DUMP_MEMORY_STATS
531 This command dumps memory manamgent related statistics to the librarys
534 @item GCRYCTL_DUMP_SECMEM_STATS
535 This command dumps secure memory manamgent related statistics to the
536 librarys logging stream.
538 @item GCRYCTL_DROP_PRIVS
539 This command disables the use of secure memory and drops the priviliges
540 of the current process. FIXME.
542 @item GCRYCTL_DISABLE_SECMEM
543 This command disables the use of secure memory. FIXME.
545 @item GCRYCTL_INIT_SECMEM
546 @item GCRYCTL_TERM_SECMEM
547 @item GCRYCTL_DISABLE_SECMEM_WARN
548 @item GCRYCTL_SUSPEND_SECMEM_WARN
549 @item GCRYCTL_RESUME_SECMEM_WARN
551 @item GCRYCTL_USE_SECURE_RNDPOOL; Arguments: none
553 This command tells the PRNG to store random numbers in secure memory.
554 FIXME: what about initialization time?
556 @item GCRYCTL_SET_RANDOM_SEED_FILE; Arguments: const char *filename
558 This command specifies the file, which is to be used as seed file for
559 the PRNG. If the seed file is registered prior to initialization of the
560 PRNG, the seed file's content (if it exists and seems to be valid) is
561 feed into the PRNG pool. After the seed file has been registered, the
562 PRNG can be signalled to write out the PRNG pool's content into the seed
563 file with the following command.
565 @item GCRYCTL_UPDATE_RANDOM_SEED_FILE; Arguments: none
567 Write out the PRNG pool's content into the registered seed file.
569 @item GCRYCTL_SET_VERBOSITY
572 @item GCRYCTL_SET_DEBUG_FLAGS
573 @item GCRYCTL_CLEAR_DEBUG_FLAGS
574 @item GCRYCTL_DISABLE_INTERNAL_LOCKING
575 @item GCRYCTL_ANY_INITIALIZATION_P
576 @item GCRYCTL_INITIALIZATION_FINISHED_P
577 @item GCRYCTL_INITIALIZATION_FINISHED
579 @item GCRYCTL_SET_THREAD_CBS; Arguments: struct ath_ops *ath_ops
581 This command registers a thread-callback structure. See section ``multi
582 threading'' for more information on this command.
584 @item GCRYCTL_FAST_POOL
592 Libgcrypt supports the use of `extension modules', which
593 implement algorithms in addition to those already built into the library
596 @deftp {Data type} gcry_module_t
597 This data type represents a `module'.
600 Functions registering modules provided by the user take a `module
601 specification structure' as input and return a value of
602 @code{gcry_module_t} and an ID that is unique in the modules'
603 category. This ID can be used to reference the newly registered
604 module. After registering a module successfully, the new functionality
605 should be able to be used through the normal functions provided by
606 Libgcrypt until it is unregistered again.
608 @c **********************************************************
609 @c ******************* Errors ****************************
610 @c **********************************************************
612 @section Error Handling
614 Many functions in Libgcrypt can return an error if they
615 fail. For this reason, the application should always catch the error
616 condition and take appropriate measures, for example by releasing the
617 resources and passing the error up to the caller, or by displaying a
618 descriptive message to the user and cancelling the operation.
620 Some error values do not indicate a system error or an error in the
621 operation, but the result of an operation that failed properly. For
622 example, if you try to decrypt a tempered message, the decryption will
623 fail. Another error value actually means that the end of a data
624 buffer or list has been reached. The following descriptions explain
625 for many error codes what they mean usually. Some error values have
626 specific meanings if returned by a certain functions. Such cases are
627 described in the documentation of those functions.
629 Libgcrypt uses the @code{libgpg-error} library. This allows to share
630 the error codes with other components of the GnuPG system, and to pass
631 error values transparently from the crypto engine, or some helper
632 application of the crypto engine, to the user. This way no
633 information is lost. As a consequence, Libgcrypt does not use its own
634 identifiers for error codes, but uses those provided by
635 @code{libgpg-error}. They usually start with @code{GPG_ERR_}.
637 However, Libgcrypt does provide aliases for the functions
638 defined in libgpg-error, which might be preferred for name space
642 Most functions in Libgcrypt return an error code in the case
643 of failure. For this reason, the application should always catch the
644 error condition and take appropriate measures, for example by
645 releasing the resources and passing the error up to the caller, or by
646 displaying a descriptive message to the user and canceling the
649 Some error values do not indicate a system error or an error in the
650 operation, but the result of an operation that failed properly.
652 GnuPG components, including Libgcrypt, use an extra library named
653 libgpg-error to provide a common error handling scheme. For more
654 information on libgpg-error, see the according manual.
657 * Error Values:: The error value and what it means.
658 * Error Sources:: A list of important error sources.
659 * Error Codes:: A list of important error codes.
660 * Error Strings:: How to get a descriptive string from a value.
665 @subsection Error Values
668 @cindex error sources
670 @deftp {Data type} {gcry_err_code_t}
671 The @code{gcry_err_code_t} type is an alias for the
672 @code{libgpg-error} type @code{gpg_err_code_t}. The error code
673 indicates the type of an error, or the reason why an operation failed.
675 A list of important error codes can be found in the next section.
678 @deftp {Data type} {gcry_err_source_t}
679 The @code{gcry_err_source_t} type is an alias for the
680 @code{libgpg-error} type @code{gpg_err_source_t}. The error source
681 has not a precisely defined meaning. Sometimes it is the place where
682 the error happened, sometimes it is the place where an error was
683 encoded into an error value. Usually the error source will give an
684 indication to where to look for the problem. This is not always true,
685 but it is attempted to achieve this goal.
687 A list of important error sources can be found in the next section.
690 @deftp {Data type} {gcry_error_t}
691 The @code{gcry_error_t} type is an alias for the @code{libgpg-error}
692 type @code{gpg_error_t}. An error value like this has always two
693 components, an error code and an error source. Both together form the
696 Thus, the error value can not be directly compared against an error
697 code, but the accessor functions described below must be used.
698 However, it is guaranteed that only 0 is used to indicate success
699 (@code{GPG_ERR_NO_ERROR}), and that in this case all other parts of
700 the error value are set to 0, too.
702 Note that in Libgcrypt, the error source is used purely for
703 diagnostic purposes. Only the error code should be checked to test
704 for a certain outcome of a function. The manual only documents the
705 error code part of an error value. The error source is left
706 unspecified and might be anything.
709 @deftypefun {gcry_err_code_t} gcry_err_code (@w{gcry_error_t @var{err}})
710 The static inline function @code{gcry_err_code} returns the
711 @code{gcry_err_code_t} component of the error value @var{err}. This
712 function must be used to extract the error code from an error value in
713 order to compare it with the @code{GPG_ERR_*} error code macros.
716 @deftypefun {gcry_err_source_t} gcry_err_source (@w{gcry_error_t @var{err}})
717 The static inline function @code{gcry_err_source} returns the
718 @code{gcry_err_source_t} component of the error value @var{err}. This
719 function must be used to extract the error source from an error value in
720 order to compare it with the @code{GPG_ERR_SOURCE_*} error source macros.
723 @deftypefun {gcry_error_t} gcry_err_make (@w{gcry_err_source_t @var{source}}, @w{gcry_err_code_t @var{code}})
724 The static inline function @code{gcry_err_make} returns the error
725 value consisting of the error source @var{source} and the error code
728 This function can be used in callback functions to construct an error
729 value to return it to the library.
732 @deftypefun {gcry_error_t} gcry_error (@w{gcry_err_code_t @var{code}})
733 The static inline function @code{gcry_error} returns the error value
734 consisting of the default error source and the error code @var{code}.
736 For @acronym{GCRY} applications, the default error source is
737 @code{GPG_ERR_SOURCE_USER_1}. You can define
738 @code{GCRY_ERR_SOURCE_DEFAULT} before including @file{gcrypt.h} to
741 This function can be used in callback functions to construct an error
742 value to return it to the library.
745 The @code{libgpg-error} library provides error codes for all system
746 error numbers it knows about. If @var{err} is an unknown error
747 number, the error code @code{GPG_ERR_UNKNOWN_ERRNO} is used. The
748 following functions can be used to construct error values from system
751 @deftypefun {gcry_error_t} gcry_err_make_from_errno (@w{gcry_err_source_t @var{source}}, @w{int @var{err}})
752 The function @code{gcry_err_make_from_errno} is like
753 @code{gcry_err_make}, but it takes a system error like @code{errno}
754 instead of a @code{gcry_err_code_t} error code.
757 @deftypefun {gcry_error_t} gcry_error_from_errno (@w{int @var{err}})
758 The function @code{gcry_error_from_errno} is like @code{gcry_error},
759 but it takes a system error like @code{errno} instead of a
760 @code{gcry_err_code_t} error code.
763 Sometimes you might want to map system error numbers to error codes
764 directly, or map an error code representing a system error back to the
765 system error number. The following functions can be used to do that.
767 @deftypefun {gcry_err_code_t} gcry_err_code_from_errno (@w{int @var{err}})
768 The function @code{gcry_err_code_from_errno} returns the error code
769 for the system error @var{err}. If @var{err} is not a known system
770 error, the function returns @code{GPG_ERR_UNKNOWN_ERRNO}.
773 @deftypefun {int} gcry_err_code_to_errno (@w{gcry_err_code_t @var{err}})
774 The function @code{gcry_err_code_to_errno} returns the system error
775 for the error code @var{err}. If @var{err} is not an error code
776 representing a system error, or if this system error is not defined on
777 this system, the function returns @code{0}.
782 @subsection Error Sources
783 @cindex error codes, list of
785 The library @code{libgpg-error} defines an error source for every
786 component of the GnuPG system. The error source part of an error
787 value is not well defined. As such it is mainly useful to improve the
788 diagnostic error message for the user.
790 If the error code part of an error value is @code{0}, the whole error
791 value will be @code{0}. In this case the error source part is of
792 course @code{GPG_ERR_SOURCE_UNKNOWN}.
794 The list of error sources that might occur in applications using
795 @acronym{Libgctypt} is:
798 @item GPG_ERR_SOURCE_UNKNOWN
799 The error source is not known. The value of this error source is
802 @item GPG_ERR_SOURCE_GPGME
803 The error source is @acronym{GPGME} itself.
805 @item GPG_ERR_SOURCE_GPG
806 The error source is GnuPG, which is the crypto engine used for the
809 @item GPG_ERR_SOURCE_GPGSM
810 The error source is GPGSM, which is the crypto engine used for the
813 @item GPG_ERR_SOURCE_GCRYPT
814 The error source is @code{libgcrypt}, which is used by crypto engines
815 to perform cryptographic operations.
817 @item GPG_ERR_SOURCE_GPGAGENT
818 The error source is @command{gpg-agent}, which is used by crypto
819 engines to perform operations with the secret key.
821 @item GPG_ERR_SOURCE_PINENTRY
822 The error source is @command{pinentry}, which is used by
823 @command{gpg-agent} to query the passphrase to unlock a secret key.
825 @item GPG_ERR_SOURCE_SCD
826 The error source is the SmartCard Daemon, which is used by
827 @command{gpg-agent} to delegate operations with the secret key to a
830 @item GPG_ERR_SOURCE_KEYBOX
831 The error source is @code{libkbx}, a library used by the crypto
832 engines to manage local keyrings.
834 @item GPG_ERR_SOURCE_USER_1
835 @item GPG_ERR_SOURCE_USER_2
836 @item GPG_ERR_SOURCE_USER_3
837 @item GPG_ERR_SOURCE_USER_4
838 These error sources are not used by any GnuPG component and can be
839 used by other software. For example, applications using
840 Libgcrypt can use them to mark error values coming from callback
841 handlers. Thus @code{GPG_ERR_SOURCE_USER_1} is the default for errors
842 created with @code{gcry_error} and @code{gcry_error_from_errno},
843 unless you define @code{GCRY_ERR_SOURCE_DEFAULT} before including
849 @subsection Error Codes
850 @cindex error codes, list of
852 The library @code{libgpg-error} defines many error values. The
853 following list includes the most important error codes.
857 This value indicates the end of a list, buffer or file.
859 @item GPG_ERR_NO_ERROR
860 This value indicates success. The value of this error code is
861 @code{0}. Also, it is guaranteed that an error value made from the
862 error code @code{0} will be @code{0} itself (as a whole). This means
863 that the error source information is lost for this error code,
864 however, as this error code indicates that no error occurred, this is
865 generally not a problem.
867 @item GPG_ERR_GENERAL
868 This value means that something went wrong, but either there is not
869 enough information about the problem to return a more useful error
870 value, or there is no separate error value for this type of problem.
873 This value means that an out-of-memory condition occurred.
876 System errors are mapped to GPG_ERR_EFOO where FOO is the symbol for
879 @item GPG_ERR_INV_VALUE
880 This value means that some user provided data was out of range.
882 @item GPG_ERR_UNUSABLE_PUBKEY
883 This value means that some recipients for a message were invalid.
885 @item GPG_ERR_UNUSABLE_SECKEY
886 This value means that some signers were invalid.
888 @item GPG_ERR_NO_DATA
889 This value means that data was expected where no data was found.
891 @item GPG_ERR_CONFLICT
892 This value means that a conflict of some sort occurred.
894 @item GPG_ERR_NOT_IMPLEMENTED
895 This value indicates that the specific function (or operation) is not
896 implemented. This error should never happen. It can only occur if
897 you use certain values or configuration options which do not work,
898 but for which we think that they should work at some later time.
900 @item GPG_ERR_DECRYPT_FAILED
901 This value indicates that a decryption operation was unsuccessful.
903 @item GPG_ERR_WRONG_KEY_USAGE
904 This value indicates that a key is not used appropriately.
906 @item GPG_ERR_NO_SECKEY
907 This value indicates that no secret key for the user ID is available.
909 @item GPG_ERR_UNSUPPORTED_ALGORITHM
910 This value means a verification failed because the cryptographic
911 algorithm is not supported by the crypto backend.
913 @item GPG_ERR_BAD_SIGNATURE
914 This value means a verification failed because the signature is bad.
916 @item GPG_ERR_NO_PUBKEY
917 This value means a verification failed because the public key is not
923 @item GPG_ERR_USER_16
924 These error codes are not used by any GnuPG component and can be
925 freely used by other software. Applications using Libgcrypt
926 might use them to mark specific errors returned by callback handlers
927 if no suitable error codes (including the system errors) for these
928 errors exist already.
933 @subsection Error Strings
934 @cindex error values, printing of
935 @cindex error codes, printing of
936 @cindex error sources, printing of
937 @cindex error strings
939 @deftypefun {const char *} gcry_strerror (@w{gcry_error_t @var{err}})
940 The function @code{gcry_strerror} returns a pointer to a statically
941 allocated string containing a description of the error code contained
942 in the error value @var{err}. This string can be used to output a
943 diagnostic message to the user.
947 @deftypefun {const char *} gcry_strsource (@w{gcry_error_t @var{err}})
948 The function @code{gcry_strerror} returns a pointer to a statically
949 allocated string containing a description of the error source
950 contained in the error value @var{err}. This string can be used to
951 output a diagnostic message to the user.
954 The following example illustrates the use of the functions described
959 gcry_cipher_hd_t handle;
960 gcry_error_t err = 0;
962 err = gcry_cipher_open (&handle, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, 0);
965 fprintf (stderr, "Failure: %s/%s\n",
966 gcry_strsource (err),
967 gcry_strerror (err));
972 @c **********************************************************
973 @c ******************* General ****************************
974 @c **********************************************************
975 @node Handler Functions
976 @chapter Handler Functions
978 Libgcrypt makes it possible to install so called `handler functions',
979 which get called by Libgcrypt in case of certain events.
982 * Progress handler:: Using a progress handler function.
983 * Allocation handler:: Using special memory allocation functions.
984 * Error handler:: Using error handler functions.
985 * Logging handler:: Using a special logging function.
988 @node Progress handler
989 @section Progress handler
991 It is often useful to retrieve some feedback while long running
992 operations are performed.
994 @deftp {Data type} gcry_handler_progress_t
995 Progress handler functions have to be of the type
996 @code{gcry_handler_progress_t}, which is defined as:
998 @code{void (*gcry_handler_progress_t) (void *, const char *, int, int, int)}
1001 The following function may be used to register a handler function for
1004 @deftypefun void gcry_set_progress_handler (gcry_handler_progress_t @var{cb}, void *@var{cb_data})
1006 This function installs @var{cb} as the `Progress handler' function.
1007 @var{cb} must be defined as follows:
1011 my_progress_handler (void *@var{cb_data}, const char *@var{what},
1012 int @var{printchar}, int @var{current}, int @var{total})
1018 A description of the arguments of the progress handler function follows.
1022 The argument provided in the call to @code{gcry_set_progress_handler}.
1024 A string identifying the type of the progress output. The following
1025 values for @var{what} are defined:
1029 Not enough entropy is available. @var{total} holds the number of
1033 Values for @var{printchar}:
1038 Need to refresh the pool of prime numbers.
1040 Number of bits adjusted.
1042 Searching for a generator.
1044 Fermat test on 10 candidates failed.
1046 Restart with a new random value.
1048 Rabin Miller test passed.
1056 @node Allocation handler
1057 @section Allocation handler
1059 It is possible to make Libgcrypt use special memory
1060 allocation functions instead of the built-in ones.
1062 Memory allocation functions are of the following types:
1063 @deftp {Data type} gcry_handler_alloc_t
1064 This type is defined as: @code{void *(*gcry_handler_alloc_t) (size_t n)}.
1066 @deftp {Data type} gcry_handler_secure_check_t
1067 This type is defined as: @code{int *(*gcry_handler_secure_check_t) (const void *)}.
1069 @deftp {Data type} gcry_handler_realloc_t
1070 This type is defined as: @code{void *(*gcry_handler_realloc_t) (void *p, size_t n)}.
1072 @deftp {Data type} gcry_handler_free_t
1073 This type is defined as: @code{void *(*gcry_handler_free_t) (void *)}.
1076 Special memory allocation functions can be installed with the
1079 @deftypefun void gcry_set_allocation_handler (gcry_handler_alloc_t @var{func_alloc}, gcry_handler_alloc_t @var{func_alloc_secure}, gcry_handler_secure_check_t @var{func_secure_check}, gcry_handler_realloc_t @var{func_realloc}, gcry_handler_free_t @var{func_free})
1080 Install the provided functions and use them instead of the built-in
1081 functions for doing memory allocation.
1085 @section Error handler
1087 The following functions may be used to register handler functions that
1088 are called by Libgcrypt in case certain error conditions
1091 @deftp {Data type} gcry_handler_no_mem_t
1092 This type is defined as: @code{void (*gcry_handler_no_mem_t) (void *, size_t, unsigned int)}
1094 @deftypefun void gcry_set_outofcore_handler (gcry_handler_no_mem_t @var{func_no_mem}, void *@var{cb_data})
1095 This function registers @var{func_no_mem} as `out-of-core handler',
1096 which means that it will be called in the case of not having enough
1100 @deftp {Data type} gcry_handler_error_t
1101 This type is defined as: @code{void (*gcry_handler_error_t) (void *, int, const char *)}
1104 @deftypefun void gcry_set_fatalerror_handler (gcry_handler_error_t @var{func_error}, void *@var{cb_data})
1105 This function registers @var{func_error} as `error handler',
1106 which means that it will be called in error conditions.
1109 @node Logging handler
1110 @section Logging handler
1112 @deftp {Data type} gcry_handler_log_t
1113 This type is defined as: @code{void (*gcry_handler_log_t) (void *, int, const char *, va_list)}
1116 @deftypefun void gcry_set_log_handler (gcry_handler_log_t @var{func_log}, void *@var{cb_data})
1117 This function registers @var{func_log} as `logging handler', which
1118 means that it will be called in case Libgcrypt wants to log
1122 @c **********************************************************
1123 @c ******************* Ciphers ****************************
1124 @c **********************************************************
1125 @c @include cipher-ref.texi
1126 @node Symmetric cryptography
1127 @chapter Symmetric cryptography
1129 The cipher functions are used for symmetrical cryptography,
1130 i.e. cryptography using a shared key. The programming model follows
1131 an open/process/close paradigm and is in that similar to other
1132 building blocks provided by Libgcrypt.
1135 * Available ciphers:: List of ciphers supported by the library.
1136 * Cipher modules:: How to work with cipher modules.
1137 * Available cipher modes:: List of cipher modes supported by the library.
1138 * Working with cipher handles:: How to perform operations related to cipher handles.
1139 * General cipher functions:: General cipher functions independent of cipher handles.
1142 @node Available ciphers
1143 @section Available ciphers
1146 @item GCRY_CIPHER_NONE
1147 This is not a real algorithm but used by some functions as error return.
1148 The value always evaluates to false.
1150 @item GCRY_CIPHER_IDEA
1151 This is the IDEA algorithm. The constant is provided but there is
1152 currently no implementation for it because the algorithm is patented.
1154 @item GCRY_CIPHER_3DES
1155 Triple-DES with 3 Keys as EDE. The key size of this algorithm is 168 but
1156 you have to pass 192 bits because the most significant bits of each byte
1159 @item GCRY_CIPHER_CAST5
1160 CAST128-5 block cipher algorithm. The key size is 128 bits.
1162 @item GCRY_CIPHER_BLOWFISH
1163 The blowfish algorithm. The current implementation allows only for a key
1166 @item GCRY_CIPHER_SAFER_SK128
1167 Reserved and not currently implemented.
1169 @item GCRY_CIPHER_DES_SK
1170 Reserved and not currently implemented.
1172 @item GCRY_CIPHER_AES
1173 @itemx GCRY_CIPHER_AES128
1174 @itemx GCRY_CIPHER_RIJNDAEL
1175 @itemx GCRY_CIPHER_RIJNDAEL128
1176 AES (Rijndael) with a 128 bit key.
1178 @item GCRY_CIPHER_AES192
1179 @itemx GCRY_CIPHER_RIJNDAEL192
1180 AES (Rijndael) with a 192 bit key.
1182 @item GCRY_CIPHER_AES256
1183 @itemx GCRY_CIPHER_RIJNDAEL256
1184 AES (Rijndael) with a 256 bit key.
1186 @item GCRY_CIPHER_TWOFISH
1187 The Twofish algorithm with a 256 bit key.
1189 @item GCRY_CIPHER_TWOFISH128
1190 The Twofish algorithm with a 128 bit key.
1192 @item GCRY_CIPHER_ARCFOUR
1193 An algorithm which is 100% compatible with RSA Inc.'s RC4 algorithm.
1194 Note that this is a stream cipher and must be used very carefully to
1195 avoid a couple of weaknesses.
1197 @item GCRY_CIPHER_DES
1198 Standard DES with a 56 bit key. You need to pass 64 bit but the high
1199 bits of each byte are ignored. Note, that this is a weak algorithm
1200 which can be broken in reasonable time using a brute force approach.
1202 @item GCRY_CIPHER_SERPENT128
1203 @itemx GCRY_CIPHER_SERPENT192
1204 @itemx GCRY_CIPHER_SERPENT256
1205 The Serpent cipher from the AES contest.
1207 @item GCRY_CIPHER_RFC2268_40
1208 @itemx GCRY_CIPHER_RFC2268_128
1209 Ron's Cipher 2 in the 40 and 128 bit variants. Note, that we currently
1210 only support the 40 bit variant. The identifier for 128 is reserved for
1213 @item GCRY_CIPHER_SEED
1214 A 128 bit cipher as described by RFC4269.
1218 @node Cipher modules
1219 @section Cipher modules
1221 Libgcrypt makes it possible to load additional `cipher modules'; these
1222 ciphers can be used just like the cipher algorithms that are built
1223 into the library directly. For an introduction into extension
1224 modules, see @xref{Modules}.
1226 @deftp {Data type} gcry_cipher_spec_t
1227 This is the `module specification structure' needed for registering
1228 cipher modules, which has to be filled in by the user before it can be
1229 used to register a module. It contains the following members:
1232 @item const char *name
1233 The primary name of the algorithm.
1234 @item const char **aliases
1235 A list of strings that are `aliases' for the algorithm. The list must
1236 be terminated with a NULL element.
1237 @item gcry_cipher_oid_spec_t *oids
1238 A list of OIDs that are to be associated with the algorithm. The
1239 list's last element must have it's `oid' member set to NULL. See
1240 below for an explanation of this type.
1241 @item size_t blocksize
1242 The block size of the algorithm, in bytes.
1244 The length of the key, in bits.
1245 @item size_t contextsize
1246 The size of the algorithm-specific `context', that should be allocated
1248 @item gcry_cipher_setkey_t setkey
1249 The function responsible for initializing a handle with a provided
1250 key. See below for a description of this type.
1251 @item gcry_cipher_encrypt_t encrypt
1252 The function responsible for encrypting a single block. See below for
1253 a description of this type.
1254 @item gcry_cipher_decrypt_t decrypt
1255 The function responsible for decrypting a single block. See below for
1256 a description of this type.
1257 @item gcry_cipher_stencrypt_t stencrypt
1258 Like `encrypt', for stream ciphers. See below for a description of
1260 @item gcry_cipher_stdecrypt_t stdecrypt
1261 Like `decrypt', for stream ciphers. See below for a description of
1266 @deftp {Data type} gcry_cipher_oid_spec_t
1267 This type is used for associating a user-provided algorithm
1268 implementation with certain OIDs. It contains the following members:
1270 @item const char *oid
1271 Textual representation of the OID.
1273 Cipher mode for which this OID is valid.
1277 @deftp {Data type} gcry_cipher_setkey_t
1278 Type for the `setkey' function, defined as: gcry_err_code_t
1279 (*gcry_cipher_setkey_t) (void *c, const unsigned char *key, unsigned
1283 @deftp {Data type} gcry_cipher_encrypt_t
1284 Type for the `encrypt' function, defined as: gcry_err_code_t
1285 (*gcry_cipher_encrypt_t) (void *c, const unsigned char *outbuf, const
1286 unsigned char *inbuf)
1289 @deftp {Data type} gcry_cipher_decrypt_t
1290 Type for the `decrypt' function, defined as: gcry_err_code_t
1291 (*gcry_cipher_decrypt_t) (void *c, const unsigned char *outbuf, const
1292 unsigned char *inbuf)
1295 @deftp {Data type} gcry_cipher_stencrypt_t
1296 Type for the `stencrypt' function, defined as: gcry_err_code_t
1297 (*gcry_cipher_stencrypt_t) (void *c, const unsigned char *outbuf, const
1298 unsigned char *, unsigned int n)
1301 @deftp {Data type} gcry_cipher_stdecrypt_t
1302 Type for the `stdecrypt' function, defined as: gcry_err_code_t
1303 (*gcry_cipher_stdecrypt_t) (void *c, const unsigned char *outbuf, const
1304 unsigned char *, unsigned int n)
1307 @deftypefun gcry_error_t gcry_cipher_register (gcry_cipher_spec_t *@var{cipher}, unsigned int *algorithm_id, gcry_module_t *@var{module})
1309 Register a new cipher module whose specification can be found in
1310 @var{cipher}. On success, a new algorithm ID is stored in
1311 @var{algorithm_id} and a pointer representing this module is stored
1315 @deftypefun void gcry_cipher_unregister (gcry_module_t @var{module})
1316 Unregister the cipher identified by @var{module}, which must have been
1317 registered with gcry_cipher_register.
1320 @deftypefun gcry_error_t gcry_cipher_list (int *@var{list}, int *@var{list_length})
1321 Get a list consisting of the IDs of the loaded cipher modules. If
1322 @var{list} is zero, write the number of loaded cipher modules to
1323 @var{list_length} and return. If @var{list} is non-zero, the first
1324 *@var{list_length} algorithm IDs are stored in @var{list}, which must
1325 be of according size. In case there are less cipher modules than
1326 *@var{list_length}, *@var{list_length} is updated to the correct
1330 @node Available cipher modes
1331 @section Available cipher modes
1334 @item GCRY_CIPHER_MODE_NONE
1335 No mode specified, may be set later using other functions. The value
1336 of this constant is always 0.
1338 @item GCRY_CIPHER_MODE_ECB
1339 Electronic Codebook mode.
1341 @item GCRY_CIPHER_MODE_CFB
1342 Cipher Feedback mode.
1344 @item GCRY_CIPHER_MODE_CBC
1345 Cipher Block Chaining mode.
1347 @item GCRY_CIPHER_MODE_STREAM
1348 Stream mode, only to be used with stream cipher algorithms.
1350 @item GCRY_CIPHER_MODE_OFB
1351 Output Feedback mode.
1353 @item GCRY_CIPHER_MODE_CTR
1358 @node Working with cipher handles
1359 @section Working with cipher handles
1361 To use a cipher algorithm, you must first allocate an according
1362 handle. This is to be done using the open function:
1364 @deftypefun gcry_error_t gcry_cipher_open (gcry_cipher_hd_t *@var{hd}, int @var{algo}, int @var{mode}, unsigned int @var{flags})
1366 This function creates the context handle required for most of the
1367 other cipher functions and returns a handle to it in `hd'. In case of
1368 an error, an according error code is returned.
1370 The ID of algorithm to use must be specified via @var{algo}. See
1371 @xref{Available ciphers}, for a list of supported ciphers and the
1372 according constants.
1374 Besides using the constants directly, the function
1375 @code{gcry_cipher_map_name} may be used to convert the textual name of
1376 an algorithm into the according numeric ID.
1378 The cipher mode to use must be specified via @var{mode}. See
1379 @xref{Available cipher modes}, for a list of supported cipher modes
1380 and the according constants. Note that some modes are incompatible
1381 with some algorithms - in particular, stream mode
1382 (GCRY_CIPHER_MODE_STREAM) only works with stream ciphers. Any block
1383 cipher mode (GCRY_CIPHER_MODE_ECB, GCRY_CIPHER_MODE_CBC,
1384 GCRY_CIPHER_MODE_CFB, GCRY_CIPHER_MODE_OFB or GCRY_CIPHER_MODE_CTR)
1385 will work with any block cipher algorithm.
1387 The third argument @var{flags} can either be passed as @code{0} or as
1388 the bit-wise OR of the following constants.
1391 @item GCRY_CIPHER_SECURE
1392 Make sure that all operations are allocated in secure memory. This is
1393 useful when the key material is highly confidential.
1394 @item GCRY_CIPHER_ENABLE_SYNC
1395 This flag enables the CFB sync mode, which is a special feature of
1396 Libgcrypt's CFB mode implementation to allow for OpenPGP's CFB variant.
1397 See @code{gcry_cipher_sync}.
1398 @item GCRY_CIPHER_CBC_CTS
1399 Enable cipher text stealing (CTS) for the CBC mode. Cannot be used
1400 simultaneous as GCRY_CIPHER_CBC_MAC. CTS mode makes it possible to
1401 transform data of almost arbitrary size (only limitation is that it
1402 must be greater than the algorithm's block size).
1403 @item GCRY_CIPHER_CBC_MAC
1404 Compute CBC-MAC keyed checksums. This is the same as CBC mode, but
1405 only output the last block. Cannot be used simultaneous as
1406 GCRY_CIPHER_CBC_CTS.
1410 Use the following function to release an existing handle:
1412 @deftypefun void gcry_cipher_close (gcry_cipher_hd_t @var{h})
1414 This function releases the context created by @code{gcry_cipher_open}.
1417 In order to use a handle for performing cryptographic operations, a
1418 `key' has to be set first:
1420 @deftypefun gcry_error_t gcry_cipher_setkey (gcry_cipher_hd_t @var{h}, void *@var{k}, size_t @var{l})
1422 Set the key @var{k} used for encryption or decryption in the context
1423 denoted by the handle @var{h}. The length @var{l} of the key @var{k}
1424 must match the required length of the algorithm set for this context or
1425 be in the allowed range for algorithms with variable key size. The
1426 function checks this and returns an error if there is a problem. A
1427 caller should always check for an error.
1429 Note that this is currently implemented as a macro but may be changed
1430 to a function in the future.
1433 Most crypto modes requires an initialization vector (IV), which
1434 usually is a non-secret random string acting as a kind of salt value.
1435 The CTR mode requires a counter, which is also similar to a salt
1436 value. To set the IV or CTR, use these functions:
1438 @deftypefun gcry_error_t gcry_cipher_setiv (gcry_cipher_hd_t @var{h}, void *@var{k}, size_t @var{l})
1440 Set the initialization vector used for encryption or decryption. The
1441 vector is passed as the buffer @var{K} of length @var{l} and copied to
1442 internal data structures. The function checks that the IV matches the
1443 requirement of the selected algorithm and mode. Note that this is
1444 implemented as a macro.
1447 @deftypefun gcry_error_t gcry_cipher_setctr (gcry_cipher_hd_t @var{h}, void *@var{c}, size_t @var{l})
1449 Set the counter vector used for encryption or decryption. The counter
1450 is passed as the buffer @var{c} of length @var{l} and copied to
1451 internal data structures. The function checks that the counter
1452 matches the requirement of the selected algorithm (i.e., it must be
1453 the same size as the block size). Note that this is implemented as a
1457 @deftypefun gcry_error_t gcry_cipher_reset (gcry_cipher_hd_t @var{h})
1459 Set the given handle's context back to the state it had after the last
1460 call to gcry_cipher_setkey and clear the initialization vector.
1462 Note that gcry_cipher_reset is implemented as a macro.
1465 The actual encryption and decryption is done by using one of the
1466 following functions. They may be used as often as required to process
1469 @deftypefun gcry_error_t gcry_cipher_encrypt (gcry_cipher_hd_t @var{h}, unsigned char *{out}, size_t @var{outsize}, const unsigned char *@var{in}, size_t @var{inlen})
1471 @code{gcry_cipher_encrypt} is used to encrypt the data. This function
1472 can either work in place or with two buffers. It uses the cipher
1473 context already setup and described by the handle @var{h}. There are 2
1474 ways to use the function: If @var{in} is passed as @code{NULL} and
1475 @var{inlen} is @code{0}, in-place encryption of the data in @var{out} or
1476 length @var{outsize} takes place. With @var{in} being not @code{NULL},
1477 @var{inlen} bytes are encrypted to the buffer @var{out} which must have
1478 at least a size of @var{inlen}. @var{outsize} must be set to the
1479 allocated size of @var{out}, so that the function can check that there
1480 is sufficient space. Note that overlapping buffers are not allowed.
1482 Depending on the selected algorithms and encryption mode, the length of
1483 the buffers must be a multiple of the block size.
1485 The function returns @code{0} on success or an error code.
1489 @deftypefun gcry_error_t gcry_cipher_decrypt (gcry_cipher_hd_t @var{h}, unsigned char *{out}, size_t @var{outsize}, const unsigned char *@var{in}, size_t @var{inlen})
1491 @code{gcry_cipher_decrypt} is used to decrypt the data. This function
1492 can either work in place or with two buffers. It uses the cipher
1493 context already setup and described by the handle @var{h}. There are 2
1494 ways to use the function: If @var{in} is passed as @code{NULL} and
1495 @var{inlen} is @code{0}, in-place decryption of the data in @var{out} or
1496 length @var{outsize} takes place. With @var{in} being not @code{NULL},
1497 @var{inlen} bytes are decrypted to the buffer @var{out} which must have
1498 at least a size of @var{inlen}. @var{outsize} must be set to the
1499 allocated size of @var{out}, so that the function can check that there
1500 is sufficient space. Note that overlapping buffers are not allowed.
1502 Depending on the selected algorithms and encryption mode, the length of
1503 the buffers must be a multiple of the block size.
1505 The function returns @code{0} on success or an error code.
1509 OpenPGP (as defined in RFC-2440) requires a special sync operation in
1510 some places. The following function is used for this:
1512 @deftypefun gcry_error_t gcry_cipher_sync (gcry_cipher_hd_t @var{h})
1514 Perform the OpenPGP sync operation on context @var{h}. Note that this
1515 is a no-op unless the context was created with the flag
1516 @code{GCRY_CIPHER_ENABLE_SYNC}
1519 Some of the described functions are implemented as macros utilizing a
1520 catch-all control function. This control function is rarely used
1521 directly but there is nothing which would inhibit it:
1523 @deftypefun gcry_error_t gcry_cipher_ctl (gcry_cipher_hd_t @var{h}, int @var{cmd}, void *@var{buffer}, size_t @var{buflen})
1525 @code{gcry_cipher_ctl} controls various aspects of the cipher module and
1526 specific cipher contexts. Usually some more specialized functions or
1527 macros are used for this purpose. The semantics of the function and its
1528 parameters depends on the the command @var{cmd} and the passed context
1529 handle @var{h}. Please see the comments in the source code
1530 (@code{src/global.c}) for details.
1533 @deftypefun gcry_error_t gcry_cipher_info (gcry_cipher_hd_t @var{h}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes})
1535 @code{gcry_cipher_info} is used to retrieve various
1536 information about a cipher context or the cipher module in general.
1538 Currently no information is available.
1541 @node General cipher functions
1542 @section General cipher functions
1544 To work with the algorithms, several functions are available to map
1545 algorithm names to the internal identifiers, as well as ways to
1546 retrieve information about an algorithm or the current cipher context.
1548 @deftypefun gcry_error_t gcry_cipher_algo_info (int @var{algo}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes})
1550 This function is used to retrieve information on a specific algorithm.
1551 You pass the cipher algorithm ID as @var{algo} and the type of
1552 information requested as @var{what}. The result is either returned as
1553 the return code of the function or copied to the provided @var{buffer}
1554 whose allocated length must be available in an integer variable with the
1555 address passed in @var{nbytes}. This variable will also receive the
1556 actual used length of the buffer.
1558 Here is a list of supported codes for @var{what}:
1560 @c begin constants for gcry_cipher_algo_info
1562 @item GCRYCTL_GET_KEYLEN:
1563 Return the length of the key. If the algorithm supports multiple key
1564 lengths, the maximum supported value is returned. The length is
1565 returned as number of octets (bytes) and not as number of bits in
1566 @var{nbytes}; @var{buffer} must be zero.
1568 @item GCRYCTL_GET_BLKLEN:
1569 Return the block length of the algorithm. The length is returned as a
1570 number of octets in @var{nbytes}; @var{buffer} must be zero.
1572 @item GCRYCTL_TEST_ALGO:
1573 Returns @code{0} when the specified algorithm is available for use.
1574 @var{buffer} and @var{nbytes} must be zero.
1577 @c end constants for gcry_cipher_algo_info
1580 @c end gcry_cipher_algo_info
1582 @deftypefun const char *gcry_cipher_algo_name (int @var{algo})
1584 @code{gcry_cipher_algo_name} returns a string with the name of the
1585 cipher algorithm @var{algo}. If the algorithm is not known or another
1586 error occurred, the string @code{"?"} is returned. This function should
1587 not be used to test for the availability of an algorithm.
1590 @deftypefun int gcry_cipher_map_name (const char *@var{name})
1592 @code{gcry_cipher_map_name} returns the algorithm identifier for the
1593 cipher algorithm described by the string @var{name}. If this algorithm
1594 is not available @code{0} is returned.
1597 @deftypefun int gcry_cipher_mode_from_oid (const char *@var{string})
1599 Return the cipher mode associated with an @acronym{ASN.1} object
1600 identifier. The object identifier is expected to be in the
1601 @acronym{IETF}-style dotted decimal notation. The function returns
1602 @code{0} for an unknown object identifier or when no mode is associated
1607 @c **********************************************************
1608 @c ******************* Hash Functions *********************
1609 @c **********************************************************
1613 Libgcrypt provides an easy and consistent to use interface
1614 for hashing. Hashing is buffered and several hash algorithms can be
1615 updated at once. It is possible to calculate a MAC using the same
1616 routines. The programming model follows an open/process/close
1617 paradigm and is in that similar to other building blocks provided by
1620 For convenience reasons, a few cyclic redundancy check value operations
1624 * Available hash algorithms:: List of hash algorithms supported by the library.
1625 * Hash algorithm modules:: How to work with hash algorithm modules.
1626 * Working with hash algorithms:: List of functions related to hashing.
1629 @node Available hash algorithms
1630 @section Available hash algorithms
1632 @c begin table of hash algorithms
1635 This is not a real algorithm but used by some functions as an error
1636 return value. This constant is guaranteed to have the value @code{0}.
1639 This is the SHA-1 algorithm which yields a message digest of 20 bytes.
1641 @item GCRY_MD_RMD160
1642 This is the 160 bit version of the RIPE message digest (RIPE-MD-160).
1643 Like SHA-1 it also yields a digest of 20 bytes.
1646 This is the well known MD5 algorithm, which yields a message digest of
1650 This is the MD4 algorithm, which yields a message digest of 16 bytes.
1653 This is an reserved identifier for MD-2; there is no implementation yet.
1656 This is the TIGER/192 algorithm which yields a message digest of 24 bytes.
1659 This is an reserved for the HAVAL algorithm with 5 passes and 160
1660 bit. It yields a message digest of 20 bytes. Note that there is no
1661 implementation yet available.
1663 @item GCRY_MD_SHA224
1664 This is the SHA-224 algorithm which yields a message digest of 28 bytes.
1665 See Change Notice 1 for FIPS 180-2 for the specification.
1667 @item GCRY_MD_SHA256
1668 This is the SHA-256 algorithm which yields a message digest of 32 bytes.
1669 See FIPS 180-2 for the specification.
1671 @item GCRY_MD_SHA384
1672 This is the SHA-384 algorithm which yields a message digest of 48 bytes.
1673 See FIPS 180-2 for the specification.
1675 @item GCRY_MD_SHA512
1676 This is the SHA-384 algorithm which yields a message digest of 64 bytes.
1677 See FIPS 180-2 for the specification.
1680 This is the ISO 3309 and ITU-T V.42 cyclic redundancy check. It
1681 yields an output of 4 bytes.
1683 @item GCRY_MD_CRC32_RFC1510
1684 This is the above cyclic redundancy check function, as modified by RFC
1685 1510. It yields an output of 4 bytes.
1687 @item GCRY_MD_CRC24_RFC2440
1688 This is the OpenPGP cyclic redundancy check function. It yields an
1691 @item GCRY_MD_WHIRLPOOL
1692 This is the Whirlpool algorithm which yields a message digest of 64
1696 @c end table of hash algorithms
1698 @node Hash algorithm modules
1699 @section Hash algorithm modules
1701 Libgcrypt makes it possible to load additional `message
1702 digest modules'; these digests can be used just like the message digest
1703 algorithms that are built into the library directly. For an
1704 introduction into extension modules, see @xref{Modules}.
1706 @deftp {Data type} gcry_md_spec_t
1707 This is the `module specification structure' needed for registering
1708 message digest modules, which has to be filled in by the user before
1709 it can be used to register a module. It contains the following
1713 @item const char *name
1714 The primary name of this algorithm.
1715 @item unsigned char *asnoid
1716 Array of bytes that form the ASN OID.
1718 Length of bytes in `asnoid'.
1719 @item gcry_md_oid_spec_t *oids
1720 A list of OIDs that are to be associated with the algorithm. The
1721 list's last element must have it's `oid' member set to NULL. See
1722 below for an explanation of this type. See below for an explanation
1725 Length of the message digest algorithm. See below for an explanation
1727 @item gcry_md_init_t init
1728 The function responsible for initializing a handle. See below for an
1729 explanation of this type.
1730 @item gcry_md_write_t write
1731 The function responsible for writing data into a message digest
1732 context. See below for an explanation of this type.
1733 @item gcry_md_final_t final
1734 The function responsible for `finalizing' a message digest context.
1735 See below for an explanation of this type.
1736 @item gcry_md_read_t read
1737 The function responsible for reading out a message digest result. See
1738 below for an explanation of this type.
1739 @item size_t contextsize
1740 The size of the algorithm-specific `context', that should be
1741 allocated for each handle.
1745 @deftp {Data type} gcry_md_oid_spec_t
1746 This type is used for associating a user-provided algorithm
1747 implementation with certain OIDs. It contains the following members:
1750 @item const char *oidstring
1751 Textual representation of the OID.
1755 @deftp {Data type} gcry_md_init_t
1756 Type for the `init' function, defined as: void (*gcry_md_init_t) (void
1760 @deftp {Data type} gcry_md_write_t
1761 Type for the `write' function, defined as: void (*gcry_md_write_t)
1762 (void *c, unsigned char *buf, size_t nbytes)
1765 @deftp {Data type} gcry_md_final_t
1766 Type for the `final' function, defined as: void (*gcry_md_final_t)
1770 @deftp {Data type} gcry_md_read_t
1771 Type for the `read' function, defined as: unsigned char
1772 *(*gcry_md_read_t) (void *c)
1775 @deftypefun gcry_error_t gcry_md_register (gcry_md_spec_t *@var{digest}, unsigned int *algorithm_id, gcry_module_t *@var{module})
1777 Register a new digest module whose specification can be found in
1778 @var{digest}. On success, a new algorithm ID is stored in
1779 @var{algorithm_id} and a pointer representing this module is stored
1783 @deftypefun void gcry_md_unregister (gcry_module_t @var{module})
1784 Unregister the digest identified by @var{module}, which must have been
1785 registered with gcry_md_register.
1788 @deftypefun gcry_error_t gcry_md_list (int *@var{list}, int *@var{list_length})
1789 Get a list consisting of the IDs of the loaded message digest modules.
1790 If @var{list} is zero, write the number of loaded message digest
1791 modules to @var{list_length} and return. If @var{list} is non-zero,
1792 the first *@var{list_length} algorithm IDs are stored in @var{list},
1793 which must be of according size. In case there are less message
1794 digests modules than *@var{list_length}, *@var{list_length} is updated
1795 to the correct number.
1798 @node Working with hash algorithms
1799 @section Working with hash algorithms
1801 To use most of these function it is necessary to create a context;
1804 @deftypefun gcry_error_t gcry_md_open (gcry_md_hd_t *@var{hd}, int @var{algo}, unsigned int @var{flags})
1806 Create a message digest object for algorithm @var{algo}. @var{flags}
1807 may be given as an bitwise OR of constants described below. @var{algo}
1808 may be given as @code{0} if the algorithms to use are later set using
1809 @code{gcry_md_enable}. @var{hd} is guaranteed to either receive a valid
1812 For a list of supported algorithms, see @xref{Available hash
1815 The flags allowed for @var{mode} are:
1817 @c begin table of hash flags
1819 @item GCRY_MD_FLAG_SECURE
1820 Allocate all buffers and the resulting digest in "secure memory". Use
1821 this is the hashed data is highly confidential.
1823 @item GCRY_MD_FLAG_HMAC
1824 Turn the algorithm into a HMAC message authentication algorithm. This
1825 only works if just one algorithm is enabled for the handle. Note that the function
1826 @code{gcry_md_setkey} must be used to set the MAC key. If you want CBC
1827 message authentication codes based on a cipher, see @xref{Working with
1831 @c begin table of hash flags
1833 You may use the function @code{gcry_md_is_enabled} to later check
1834 whether an algorithm has been enabled.
1837 @c end function gcry_md_open
1839 If you want to calculate several hash algorithms at the same time, you
1840 have to use the following function right after the @code{gcry_md_open}:
1842 @deftypefun gcry_error_t gcry_md_enable (gcry_md_hd_t @var{h}, int @var{algo})
1844 Add the message digest algorithm @var{algo} to the digest object
1845 described by handle @var{h}. Duplicated enabling of algorithms is
1846 detected and ignored.
1849 If the flag @code{GCRY_MD_FLAG_HMAC} was used, the key for the MAC must
1850 be set using the function:
1852 @deftypefun gcry_error_t gcry_md_setkey (gcry_md_hd_t @var{h}, const void *@var{key}, size_t @var{keylen})
1854 For use with the HMAC feature, set the MAC key to the value of @var{key}
1855 of length @var{keylen}.
1859 After you are done with the hash calculation, you should release the
1862 @deftypefun void gcry_md_close (gcry_md_hd_t @var{h})
1864 Release all resources of hash context @var{h}. @var{h} should not be
1865 used after a call to this function. A @code{NULL} passed as @var{h} is
1870 Often you have to do several hash operations using the same algorithm.
1871 To avoid the overhead of creating and releasing context, a reset function
1874 @deftypefun void gcry_md_reset (gcry_md_hd_t @var{h})
1876 Reset the current context to its initial state. This is effectively
1877 identical to a close followed by an open and enabling all currently
1882 Often it is necessary to start hashing some data and then continue to
1883 hash different data. To avoid hashing the same data several times (which
1884 might not even be possible if the data is received from a pipe), a
1885 snapshot of the current hash context can be taken and turned into a new
1888 @deftypefun gcry_error_t gcry_md_copy (gcry_md_hd_t *@var{handle_dst}, gcry_md_hd_t @var{handle_src})
1890 Create a new digest object as an exact copy of the object described by
1891 handle @var{handle_src} and store it in @var{handle_dst}. The context
1892 is not reset and you can continue to hash data using this context and
1893 independently using the original context.
1897 Now that we have prepared everything to calculate hashes, it is time to
1898 see how it is actually done. There are two ways for this, one to
1899 update the hash with a block of memory and one macro to update the hash
1900 by just one character. Both methods can be used on the same hash context.
1902 @deftypefun void gcry_md_write (gcry_md_hd_t @var{h}, const void *@var{buffer}, size_t @var{length})
1904 Pass @var{length} bytes of the data in @var{buffer} to the digest object
1905 with handle @var{h} to update the digest values. This
1906 function should be used for large blocks of data.
1909 @deftypefun void gcry_md_putc (gcry_md_hd_t @var{h}, int @var{c})
1911 Pass the byte in @var{c} to the digest object with handle @var{h} to
1912 update the digest value. This is an efficient function, implemented as
1913 a macro to buffer the data before an actual update.
1916 The semantics of the hash functions do not provide for reading out intermediate
1917 message digests because the calculation must be finalized first. This
1918 finalization may for example include the number of bytes hashed in the
1919 message digest or some padding.
1921 @deftypefun void gcry_md_final (gcry_md_hd_t @var{h})
1923 Finalize the message digest calculation. This is not really needed
1924 because @code{gcry_md_read} does this implicitly. After this has been
1925 done no further updates (by means of @code{gcry_md_write} or
1926 @code{gcry_md_putc} are allowed. Only the first call to this function
1927 has an effect. It is implemented as a macro.
1930 The way to read out the calculated message digest is by using the
1933 @deftypefun unsigned char *gcry_md_read (gcry_md_hd_t @var{h}, int @var{algo})
1935 @code{gcry_md_read} returns the message digest after finalizing the
1936 calculation. This function may be used as often as required but it will
1937 always return the same value for one handle. The returned message digest
1938 is allocated within the message context and therefore valid until the
1939 handle is released or reseted (using @code{gcry_md_close} or
1940 @code{gcry_md_reset}. @var{algo} may be given as 0 to return the only
1941 enabled message digest or it may specify one of the enabled algorithms.
1942 The function does return @code{NULL} if the requested algorithm has not
1946 Because it is often necessary to get the message digest of one block of
1947 memory, a fast convenience function is available for this task:
1949 @deftypefun void gcry_md_hash_buffer (int @var{algo}, void *@var{digest}, const void *@var{buffer}, size_t @var{length});
1951 @code{gcry_md_hash_buffer} is a shortcut function to calculate a message
1952 digest of a buffer. This function does not require a context and
1953 immediately returns the message digest of the @var{length} bytes at
1954 @var{buffer}. @var{digest} must be allocated by the caller, large
1955 enough to hold the message digest yielded by the the specified algorithm
1956 @var{algo}. This required size may be obtained by using the function
1957 @code{gcry_md_get_algo_dlen}.
1959 Note that this function will abort the process if an unavailable
1963 @c ***********************************
1964 @c ***** MD info functions ***********
1965 @c ***********************************
1967 Hash algorithms are identified by internal algorithm numbers (see
1968 @code{gcry_md_open} for a list). However, in most applications they are
1969 used by names, so two functions are available to map between string
1970 representations and hash algorithm identifiers.
1972 @deftypefun const char *gcry_md_algo_name (int @var{algo})
1974 Map the digest algorithm id @var{algo} to a string representation of the
1975 algorithm name. For unknown algorithms this function returns the
1976 string @code{"?"}. This function should not be used to test for the
1977 availability of an algorithm.
1980 @deftypefun int gcry_md_map_name (const char *@var{name})
1982 Map the algorithm with @var{name} to a digest algorithm identifier.
1983 Returns 0 if the algorithm name is not known. Names representing
1984 @acronym{ASN.1} object identifiers are recognized if the @acronym{IETF}
1985 dotted format is used and the OID is prefixed with either "@code{oid.}"
1986 or "@code{OID.}". For a list of supported OIDs, see the source code at
1987 @file{cipher/md.c}. This function should not be used to test for the
1988 availability of an algorithm.
1991 @deftypefun gcry_error_t gcry_md_get_asnoid (int @var{algo}, void *@var{buffer}, size_t *@var{length})
1993 Return an DER encoded ASN.1 OID for the algorithm @var{algo} in the
1994 user allocated @var{buffer}. @var{length} must point to variable with
1995 the available size of @var{buffer} and receives after return the
1996 actual size of the returned OID. The returned error code may be
1997 @code{GPG_ERR_TOO_SHORT} if the provided buffer is to short to receive
1998 the OID; it is possible to call the function with @code{NULL} for
1999 @var{buffer} to have it only return the required size. The function
2000 returns 0 on success.
2005 To test whether an algorithm is actually available for use, the
2006 following macro should be used:
2008 @deftypefun gcry_error_t gcry_md_test_algo (int @var{algo})
2010 The macro returns 0 if the algorithm @var{algo} is available for use.
2013 If the length of a message digest is not known, it can be retrieved
2014 using the following function:
2016 @deftypefun unsigned int gcry_md_get_algo_dlen (int @var{algo})
2018 Retrieve the length in bytes of the digest yielded by algorithm
2019 @var{algo}. This is often used prior to @code{gcry_md_read} to allocate
2020 sufficient memory for the digest.
2024 In some situations it might be hard to remember the algorithm used for
2025 the ongoing hashing. The following function might be used to get that
2028 @deftypefun int gcry_md_get_algo (gcry_md_hd_t @var{h})
2030 Retrieve the algorithm used with the handle @var{h}. Note that this
2031 does not work reliable if more than one algorithm is enabled in @var{h}.
2034 The following macro might also be useful:
2036 @deftypefun int gcry_md_is_secure (gcry_md_hd_t @var{h})
2038 This function returns true when the digest object @var{h} is allocated
2039 in "secure memory"; i.e. @var{h} was created with the
2040 @code{GCRY_MD_FLAG_SECURE}.
2043 @deftypefun int gcry_md_is_enabled (gcry_md_hd_t @var{h}, int @var{algo})
2045 This function returns true when the algorithm @var{algo} has been
2046 enabled for the digest object @var{h}.
2051 Tracking bugs related to hashing is often a cumbersome task which
2052 requires to add a lot of printf statements into the code.
2053 Libgcrypt provides an easy way to avoid this. The actual data
2054 hashed can be written to files on request.
2056 @deftypefun void gcry_md_debug (gcry_md_hd_t @var{h}, const char *@var{suffix})
2058 Enable debugging for the digest object with handle @var{h}. This
2059 creates create files named @file{dbgmd-<n>.<string>} while doing the
2060 actual hashing. @var{suffix} is the string part in the filename. The
2061 number is a counter incremented for each new hashing. The data in the
2062 file is the raw data as passed to @code{gcry_md_write} or
2063 @code{gcry_md_putc}. If @code{NULL} is used for @var{suffix}, the
2064 debugging is stopped and the file closed. This is only rarely required
2065 because @code{gcry_md_close} implicitly stops debugging.
2069 The following two deprecated macros are used for debugging by old code.
2070 They shopuld be replaced by @code{gcry_md_debug}.
2072 @deftypefun void gcry_md_start_debug (gcry_md_hd_t @var{h}, const char *@var{suffix})
2074 Enable debugging for the digest object with handle @var{h}. This
2075 creates create files named @file{dbgmd-<n>.<string>} while doing the
2076 actual hashing. @var{suffix} is the string part in the filename. The
2077 number is a counter incremented for each new hashing. The data in the
2078 file is the raw data as passed to @code{gcry_md_write} or
2079 @code{gcry_md_putc}.
2083 @deftypefun void gcry_md_stop_debug (gcry_md_hd_t @var{h}, int @var{reserved})
2085 Stop debugging on handle @var{h}. @var{reserved} should be specified as
2086 0. This function is usually not required because @code{gcry_md_close}
2087 does implicitly stop debugging.
2091 @c **********************************************************
2092 @c ******************* Public Key *************************
2093 @c **********************************************************
2094 @node Public Key cryptography (I)
2095 @chapter Public Key cryptography (I)
2097 Public key cryptography, also known as asymmetric cryptography, is an
2098 easy way for key management and to provide digital signatures.
2099 Libgcrypt provides two completely different interfaces to
2100 public key cryptography, this chapter explains the one based on
2104 * Available algorithms:: Algorithms supported by the library.
2105 * Used S-expressions:: Introduction into the used S-expression.
2106 * Public key modules:: How to work with public key modules.
2107 * Cryptographic Functions:: Functions for performing the cryptographic actions.
2108 * General public-key related Functions:: General functions, not implementing any cryptography.
2111 @node Available algorithms
2112 @section Available algorithms
2114 Libgcrypt supports the RSA (Rivest-Shamir-Adleman) algorithms as well
2115 as DSA (Digital Signature Algorithm) and ElGamal. The versatile
2116 interface allows to add more algorithms in the future.
2118 @node Used S-expressions
2119 @section Used S-expressions
2121 Libgcrypt's API for asymmetric cryptography is based on data
2122 structures called S-expressions (see XXXX) and does not work with
2123 contexts as most of the other building blocks of Libgcrypt
2126 The following information are stored in S-expressions:
2131 @item plain text data
2133 @item encrypted data
2140 To describe how Libgcrypt expect keys, we use some examples. Note that
2148 indicate parameters whereas lowercase words are literals.
2161 This specifies a DSA private key with the following parameters:
2167 DSA group order @math{q} (which is a prime divisor of @math{p-1}).
2169 DSA group generator @math{g}.
2171 DSA public key value @math{y = g^x \bmod p}.
2173 DSA secret exponent x.
2176 All the MPI values are expected to be in @code{GCRYMPI_FMT_USG} format.
2177 The public key is similar with "private-key" replaced by "public-key"
2180 An easy way to create such an S-expressions is by using
2181 @code{gcry_sexp_build} which allows to pass a string with printf-like
2182 escapes to insert MPI values.
2185 Here is an example for an RSA key:
2203 RSA public modulus @math{n}.
2205 RSA public exponent @math{e}.
2207 RSA secret exponent @math{d = e^{-1} \bmod (p-1)(q-1)}.
2209 RSA secret prime @math{p}.
2211 RSA secret prime @math{q} with @math{q > p}.
2213 multiplicative inverse @math{u = p^{-1} \bmod q}.
2216 @node Public key modules
2217 @section Public key modules
2219 Libgcrypt makes it possible to load additional `public key
2220 modules'; these public key algorithms can be used just like the
2221 algorithms that are built into the library directly. For an
2222 introduction into extension modules, see @xref{Modules}.
2224 @deftp {Data type} gcry_pk_spec_t
2225 This is the `module specification structure' needed for registering
2226 public key modules, which has to be filled in by the user before it
2227 can be used to register a module. It contains the following members:
2230 @item const char *name
2231 The primary name of this algorithm.
2232 @item char **aliases
2233 A list of strings that are `aliases' for the algorithm. The list
2234 must be terminated with a NULL element.
2235 @item const char *elements_pkey
2236 String containing the one-letter names of the MPI values contained in
2238 @item const char *element_skey
2239 String containing the one-letter names of the MPI values contained in
2241 @item const char *elements_enc
2242 String containing the one-letter names of the MPI values that are the
2243 result of an encryption operation using this algorithm.
2244 @item const char *elements_sig
2245 String containing the one-letter names of the MPI values that are the
2246 result of a sign operation using this algorithm.
2247 @item const char *elements_grip
2248 String containing the one-letter names of the MPI values that are to
2249 be included in the `key grip'.
2251 The bitwise-OR of the following flags, depending on the abilities of
2254 @item GCRY_PK_USAGE_SIGN
2255 The algorithm supports signing and verifying of data.
2256 @item GCRY_PK_USAGE_ENCR
2257 The algorithm supports the encryption and decryption of data.
2259 @item gcry_pk_generate_t generate
2260 The function responsible for generating a new key pair. See below for
2261 a description of this type.
2262 @item gcry_pk_check_secret_key_t check_secret_key
2263 The function responsible for checking the sanity of a provided secret
2264 key. See below for a description of this type.
2265 @item gcry_pk_encrypt_t encrypt
2266 The function responsible for encrypting data. See below for a
2267 description of this type.
2268 @item gcry_pk_decrypt_t decrypt
2269 The function responsible for decrypting data. See below for a
2270 description of this type.
2271 @item gcry_pk_sign_t sign
2272 The function responsible for signing data. See below for a description
2274 @item gcry_pk_verify_t verify
2275 The function responsible for verifying that the provided signature
2276 matches the provided data. See below for a description of this type.
2277 @item gcry_pk_get_nbits_t get_nbits
2278 The function responsible for returning the number of bits of a provided
2279 key. See below for a description of this type.
2283 @deftp {Data type} gcry_pk_generate_t
2284 Type for the `generate' function, defined as: gcry_err_code_t
2285 (*gcry_pk_generate_t) (int algo, unsigned int nbits, unsigned long
2286 use_e, gcry_mpi_t *skey, gcry_mpi_t **retfactors)
2289 @deftp {Data type} gcry_pk_check_secret_key_t
2290 Type for the `check_secret_key' function, defined as: gcry_err_code_t
2291 (*gcry_pk_check_secret_key_t) (int algo, gcry_mpi_t *skey)
2294 @deftp {Data type} gcry_pk_encrypt_t
2295 Type for the `encrypt' function, defined as: gcry_err_code_t
2296 (*gcry_pk_encrypt_t) (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
2297 gcry_mpi_t *pkey, int flags)
2300 @deftp {Data type} gcry_pk_decrypt_t
2301 Type for the `decrypt' function, defined as: gcry_err_code_t
2302 (*gcry_pk_decrypt_t) (int algo, gcry_mpi_t *result, gcry_mpi_t *data,
2303 gcry_mpi_t *skey, int flags)
2306 @deftp {Data type} gcry_pk_sign_t
2307 Type for the `sign' function, defined as: gcry_err_code_t
2308 (*gcry_pk_sign_t) (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
2312 @deftp {Data type} gcry_pk_verify_t
2313 Type for the `verify' function, defined as: gcry_err_code_t
2314 (*gcry_pk_verify_t) (int algo, gcry_mpi_t hash, gcry_mpi_t *data,
2315 gcry_mpi_t *pkey, int (*cmp) (void *, gcry_mpi_t), void *opaquev)
2318 @deftp {Data type} gcry_pk_get_nbits_t
2319 Type for the `get_nbits' function, defined as: unsigned
2320 (*gcry_pk_get_nbits_t) (int algo, gcry_mpi_t *pkey)
2323 @deftypefun gcry_error_t gcry_pk_register (gcry_pk_spec_t *@var{pubkey}, unsigned int *algorithm_id, gcry_module_t *@var{module})
2325 Register a new public key module whose specification can be found in
2326 @var{pubkey}. On success, a new algorithm ID is stored in
2327 @var{algorithm_id} and a pointer representing this module is stored
2331 @deftypefun void gcry_pk_unregister (gcry_module_t @var{module})
2332 Unregister the public key module identified by @var{module}, which
2333 must have been registered with gcry_pk_register.
2336 @deftypefun gcry_error_t gcry_pk_list (int *@var{list}, int *@var{list_length})
2337 Get a list consisting of the IDs of the loaded pubkey modules. If
2338 @var{list} is zero, write the number of loaded pubkey modules to
2339 @var{list_length} and return. If @var{list} is non-zero, the first
2340 *@var{list_length} algorithm IDs are stored in @var{list}, which must
2341 be of according size. In case there are less pubkey modules than
2342 *@var{list_length}, *@var{list_length} is updated to the correct
2346 @node Cryptographic Functions
2347 @section Cryptographic Functions
2350 Note that we will in future allow to use keys without p,q and u
2351 specified and may also support other parameters for performance
2356 Some functions operating on S-expressions support `flags', that
2357 influence the operation. These flags have to be listed in a
2358 sub-S-expression named `flags'; the following flags are known:
2362 Use PKCS#1 block type 2 padding.
2364 Do not use a technique called `blinding', which is used by default in
2365 order to prevent leaking of secret information. Blinding is only
2366 implemented by RSA, but it might be implemented by other algorithms in
2367 the future as well, when necessary.
2371 Now that we know the key basics, we can carry on and explain how to
2372 encrypt and decrypt data. In almost all cases the data is a random
2373 session key which is in turn used for the actual encryption of the real
2374 data. There are 2 functions to do this:
2376 @deftypefun gcry_error_t gcry_pk_encrypt (@w{gcry_sexp_t *@var{r_ciph},} @w{gcry_sexp_t @var{data},} @w{gcry_sexp_t @var{pkey}})
2378 Obviously a public key must be provided for encryption. It is
2379 expected as an appropriate S-expression (see above) in @var{pkey}.
2380 The data to be encrypted can either be in the simple old format, which
2381 is a very simple S-expression consisting only of one MPI, or it may be
2382 a more complex S-expression which also allows to specify flags for
2383 operation, like e.g. padding rules.
2386 If you don't want to let Libgcrypt handle the padding, you must pass an
2387 appropriate MPI using this expression for @var{data}:
2396 This has the same semantics as the old style MPI only way. @var{MPI} is
2397 the actual data, already padded appropriate for your protocol. Most
2398 systems however use PKCS#1 padding and so you can use this S-expression
2404 (value @var{block}))
2408 Here, the "flags" list has the "pkcs1" flag which let the function know
2409 that it should provide PKCS#1 block type 2 padding. The actual data to
2410 be encrypted is passed as a string of octets in @var{block}. The
2411 function checks that this data actually can be used with the given key,
2412 does the padding and encrypts it.
2414 If the function could successfully perform the encryption, the return
2415 value will be 0 and a a new S-expression with the encrypted result is
2416 allocated and assigned to the variable at the address of @var{r_ciph}.
2417 The caller is responsible to release this value using
2418 @code{gcry_sexp_release}. In case of an error, an error code is
2419 returned and @var{r_ciph} will be set to @code{NULL}.
2422 The returned S-expression has this format when used with RSA:
2431 Where @var{a-mpi} is an MPI with the result of the RSA operation. When
2432 using the ElGamal algorithm, the return value will have this format:
2442 Where @var{a-mpi} and @var{b-mpi} are MPIs with the result of the
2443 ElGamal encryption operation.
2445 @c end gcry_pk_encrypt
2447 @deftypefun gcry_error_t gcry_pk_decrypt (@w{gcry_sexp_t *@var{r_plain},} @w{gcry_sexp_t @var{data},} @w{gcry_sexp_t @var{skey}})
2449 Obviously a private key must be provided for decryption. It is expected
2450 as an appropriate S-expression (see above) in @var{skey}. The data to
2451 be decrypted must match the format of the result as returned by
2452 @code{gcry_pk_encrypt}, but should be enlarged with a @code{flags}
2464 Note that this function currently does not know of any padding
2465 methods and the caller must do any un-padding on his own.
2468 The function returns 0 on success or an error code. The variable at the
2469 address of @var{r_plain} will be set to NULL on error or receive the
2470 decrypted value on success. The format of @var{r_plain} is a
2471 simple S-expression part (i.e. not a valid one) with just one MPI if
2472 there was no @code{flags} element in @var{data}; if at least an empty
2473 @code{flags} is passed in @var{data}, the format is:
2476 (value @var{plaintext})
2479 @c end gcry_pk_decrypt
2482 Another operation commonly performed using public key cryptography is
2483 signing data. In some sense this is even more important than
2484 encryption because digital signatures are an important instrument for
2485 key management. Libgcrypt supports digital signatures using
2486 2 functions, similar to the encryption functions:
2488 @deftypefun gcry_error_t gcry_pk_sign (@w{gcry_sexp_t *@var{r_sig},} @w{gcry_sexp_t @var{data},} @w{gcry_sexp_t @var{skey}})
2490 This function creates a digital signature for @var{data} using the
2491 private key @var{skey} and place it into the variable at the address of
2492 @var{r_sig}. @var{data} may either be the simple old style S-expression
2493 with just one MPI or a modern and more versatile S-expression which
2494 allows to let Libgcrypt handle padding:
2499 (hash @var{hash-algo} @var{block}))
2503 This example requests to sign the data in @var{block} after applying
2504 PKCS#1 block type 1 style padding. @var{hash-algo} is a string with the
2505 hash algorithm to be encoded into the signature, this may be any hash
2506 algorithm name as supported by Libgcrypt. Most likely, this will be
2507 "sha1", "rmd160" or "md5". It is obvious that the length of @var{block}
2508 must match the size of that message digests; the function checks that
2509 this and other constraints are valid.
2512 If PKCS#1 padding is not required (because the caller does already
2513 provide a padded value), either the old format or better the following
2514 format should be used:
2523 Here, the data to be signed is directly given as an @var{MPI}.
2526 The signature is returned as a newly allocated S-expression in
2527 @var{r_sig} using this format for RSA:
2535 Where @var{s-mpi} is the result of the RSA sign operation. For DSA the
2536 S-expression returned is:
2545 Where @var{r-mpi} and @var{s-mpi} are the result of the DSA sign
2546 operation. For ElGamal signing (which is slow, yields large numbers
2547 and probably is not as secure as the other algorithms), the same format is
2548 used with "elg" replacing "dsa".
2553 The operation most commonly used is definitely the verification of a
2554 signature. Libgcrypt provides this function:
2556 @deftypefun gcry_error_t gcry_pk_verify (@w{gcry_sexp_t @var{sig}}, @w{gcry_sexp_t @var{data}}, @w{gcry_sexp_t @var{pkey}})
2558 This is used to check whether the signature @var{sig} matches the
2559 @var{data}. The public key @var{pkey} must be provided to perform this
2560 verification. This function is similar in its parameters to
2561 @code{gcry_pk_sign} with the exceptions that the public key is used
2562 instead of the private key and that no signature is created but a
2563 signature, in a format as created by @code{gcry_pk_sign}, is passed to
2564 the function in @var{sig}.
2567 The result is 0 for success (i.e. the data matches the signature), or an
2568 error code where the most relevant code is @code{GCRYERR_BAD_SIGNATURE}
2569 to indicate that the signature does not match the provided data.
2572 @c end gcry_pk_verify
2574 @node General public-key related Functions
2575 @section General public-key related Functions
2578 A couple of utility functions are available to retrieve the length of
2579 the key, map algorithm identifiers and perform sanity checks:
2581 @deftypefun {const char *} gcry_pk_algo_name (int @var{algo})
2583 Map the public key algorithm id @var{algo} to a string representation of
2584 the algorithm name. For unknown algorithms this functions returns the
2585 string @code{"?"}. This function should not be used to test for the
2586 availability of an algorithm.
2589 @deftypefun int gcry_pk_map_name (const char *@var{name})
2591 Map the algorithm @var{name} to a public key algorithm Id. Returns 0 if
2592 the algorithm name is not known.
2595 @deftypefun int gcry_pk_test_algo (int @var{algo})
2597 Return 0 if the public key algorithm @var{algo} is available for use.
2598 Note that this is implemented as a macro.
2602 @deftypefun {unsigned int} gcry_pk_get_nbits (gcry_sexp_t @var{key})
2604 Return what is commonly referred as the key length for the given
2605 public or private in @var{key}.
2608 @deftypefun {unsigned char *} gcry_pk_get_keygrip (@w{gcry_sexp_t @var{key}}, @w{unsigned char *@var{array}})
2610 Return the so called "keygrip" which is the SHA-1 hash of the public key
2611 parameters expressed in a way depended on the algorithm. @var{array}
2612 must either provide space for 20 bytes or be @code{NULL}. In the latter
2613 case a newly allocated array of that size is returned. On success a
2614 pointer to the newly allocated space or to @var{array} is returned.
2615 @code{NULL} is returned to indicate an error which is most likely an
2616 unknown algorithm or one where a "keygrip" has not yet been defined.
2617 The function accepts public or secret keys in @var{key}.
2620 @deftypefun gcry_error_t gcry_pk_testkey (gcry_sexp_t @var{key})
2622 Return zero if the private key @var{key} is `sane', an error code otherwise.
2623 Note that it is not possible to check the `saneness' of a public key.
2628 @deftypefun gcry_error_t gcry_pk_algo_info (@w{int @var{algo}}, @w{int @var{what}}, @w{void *@var{buffer}}, @w{size_t *@var{nbytes}})
2630 Depending on the value of @var{what} return various information about
2631 the public key algorithm with the id @var{algo}. Note that the
2632 function returns @code{-1} on error and the actual error code must be
2633 retrieved using the function @code{gcry_errno}. The currently defined
2634 values for @var{what} are:
2637 @item GCRYCTL_TEST_ALGO:
2638 Return 0 when the specified algorithm is available for use.
2639 @var{buffer} must be @code{NULL}, @var{nbytes} may be passed as
2640 @code{NULL} or point to a variable with the required usage of the
2641 algorithm. This may be 0 for "don't care" or the bit-wise OR of these
2645 @item GCRY_PK_USAGE_SIGN
2646 Algorithm is usable for signing.
2647 @item GCRY_PK_USAGE_ENCR
2648 Algorithm is usable for encryption.
2651 @item GCRYCTL_GET_ALGO_USAGE:
2652 Return the usage flags for the given algorithm. An invalid algorithm
2653 return 0. Disabled algorithms are ignored here because we
2654 want to know whether the algorithm is at all capable of a certain usage.
2656 @item GCRYCTL_GET_ALGO_NPKEY
2657 Return the number of elements the public key for algorithm @var{algo}
2658 consist of. Return 0 for an unknown algorithm.
2660 @item GCRYCTL_GET_ALGO_NSKEY
2661 Return the number of elements the private key for algorithm @var{algo}
2662 consist of. Note that this value is always larger than that of the
2663 public key. Return 0 for an unknown algorithm.
2665 @item GCRYCTL_GET_ALGO_NSIGN
2666 Return the number of elements a signature created with the algorithm
2667 @var{algo} consists of. Return 0 for an unknown algorithm or for an
2668 algorithm not capable of creating signatures.
2670 @item GCRYCTL_GET_ALGO_NENC
2671 Return the number of elements a encrypted message created with the algorithm
2672 @var{algo} consists of. Return 0 for an unknown algorithm or for an
2673 algorithm not capable of encryption.
2677 Please note that parameters not required should be passed as @code{NULL}.
2679 @c end gcry_pk_algo_info
2682 @deftypefun gcry_error_t gcry_pk_ctl (@w{int @var{cmd}}, @w{void *@var{buffer}}, @w{size_t @var{buflen}})
2684 This is a general purpose function to perform certain control
2685 operations. @var{cmd} controls what is to be done. The return value is
2686 0 for success or an error code. Currently supported values for
2690 @item GCRYCTL_DISABLE_ALGO
2691 Disable the algorithm given as an algorithm id in @var{buffer}.
2692 @var{buffer} must point to an @code{int} variable with the algorithm id
2693 and @var{buflen} must have the value @code{sizeof (int)}.
2700 Libgcrypt also provides a function for generating public key
2703 @deftypefun gcry_error_t gcry_pk_genkey (@w{gcry_sexp_t *@var{r_key}}, @w{gcry_sexp_t @var{parms}})
2705 This function create a new public key pair using information given in
2706 the S-expression @var{parms} and stores the private and the public key
2707 in one new S-expression at the address given by @var{r_key}. In case of
2708 an error, @var{r_key} is set to @code{NULL}. The return code is 0 for
2709 success or an error code otherwise.
2712 Here is an example for @var{parms} for creating a 1024 bit RSA key:
2721 To create an ElGamal key, substitute "elg" for "rsa" and to create a DSA
2722 key use "dsa". Valid ranges for the key length depend on the
2723 algorithms; all commonly used key lengths are supported. Currently
2724 supported parameters are:
2728 This is always required to specify the length of the key. The argument
2729 is a string with a number in C-notation. The value should be a multiple
2733 This is only used with RSA to give a hint for the public exponent. The
2734 value will be used as a base to test for a usable exponent. Some values
2739 Use a secure and fast value. This is currently the number 41.
2741 Use a secure value as required by some specification. This is currently
2748 If this parameter is not used, Libgcrypt uses for historic reasons
2752 This is only meanigful for DSA keys. If it is given the DSA key is
2753 generated with a Q parameyer of this size. If it is not given or zero
2754 Q is deduced from NBITS in this way:
2756 @item 512 <= N <= 1024
2767 Note that in this case only the values for N, as given in the table,
2768 are allowed. When specifying Q all values of N in the range 512 to
2769 15680 are valid as long as they are multiples of 8.
2772 @c end table of parameters
2775 The key pair is returned in a format depending on the algorithm. Both
2776 private and public keys are returned in one container and may be
2777 accompanied by some miscellaneous information.
2780 As an example, here is what the ElGamal key generation returns:
2796 (pm1-factors @var{n1 n2 ... nn})))
2800 As you can see, some of the information is duplicated, but this provides
2801 an easy way to extract either the public or the private key. Note that
2802 the order of the elements is not defined, e.g. the private key may be
2803 stored before the public key. @var{n1 n2 ... nn} is a list of prime
2804 numbers used to composite @var{p-mpi}; this is in general not a very
2807 @c end gcry_pk_genkey
2809 @node Public Key cryptography (II)
2810 @chapter Public Key cryptography (II)
2812 This chapter documents the alternative interface to asymmetric
2813 cryptography (ac) that is not based on S-expressions, but on native C
2814 data structures. As opposed to the pk interface described in the
2815 former chapter, this one follows an open/use/close paradigm like other
2816 building blocks of the library.
2819 * Available asymmetric algorithms:: List of algorithms supported by the library.
2820 * Working with sets of data:: How to work with sets of data.
2821 * Working with IO objects:: How to work with IO objects.
2822 * Working with handles:: How to use handles.
2823 * Working with keys:: How to work with keys.
2824 * Using cryptographic functions:: How to perform cryptographic operations.
2825 * Handle-independent functions:: General functions independent of handles.
2828 @node Available asymmetric algorithms
2829 @section Available asymmetric algorithms
2831 Libgcrypt supports the RSA (Rivest-Shamir-Adleman)
2832 algorithms as well as DSA (Digital Signature Algorithm) and ElGamal.
2833 The versatile interface allows to add more algorithms in the future.
2835 @deftp {Data type} gcry_ac_id_t
2837 The following constants are defined for this type:
2841 Riven-Shamir-Adleman
2843 Digital Signature Algorithm
2847 ElGamal, encryption only.
2851 @node Working with sets of data
2852 @section Working with sets of data
2854 In the context of this interface the term `data set' refers to a list
2855 of `named MPI values' that is used by functions performing
2856 cryptographic operations; a named MPI value is a an MPI value,
2857 associated with a label.
2859 Such data sets are used for representing keys, since keys simply
2860 consist of a variable amount of numbers. Furthermore some functions
2861 return data sets to the caller that are to be provided to other
2864 This section documents the data types, symbols and functions that are
2865 relevant for working with data sets.
2867 @deftp {Data type} gcry_ac_data_t
2871 The following flags are supported:
2874 @item GCRY_AC_FLAG_DEALLOC
2875 Used for storing data in a data set. If given, the data will be
2876 released by the library. Note that whenever one of the ac functions
2877 is about to release objects because of this flag, the objects are
2878 expected to be stored in memory allocated through the Libgcrypt memory
2879 management. In other words: gcry_free() is used instead of free().
2881 @item GCRY_AC_FLAG_COPY
2882 Used for storing/retrieving data in/from a data set. If given, the
2883 library will create copies of the provided/contained data, which will
2884 then be given to the user/associated with the data set.
2887 @deftypefun gcry_error_t gcry_ac_data_new (gcry_ac_data_t *@var{data})
2888 Creates a new, empty data set and stores it in @var{data}.
2891 @deftypefun void gcry_ac_data_destroy (gcry_ac_data_t @var{data})
2892 Destroys the data set @var{data}.
2895 @deftypefun gcry_error_t gcry_ac_data_set (gcry_ac_data_t @var{data}, unsigned int @var{flags}, char *@var{name}, gcry_mpi_t @var{mpi})
2896 Add the value @var{mpi} to @var{data} with the label @var{name}. If
2897 @var{flags} contains GCRY_AC_FLAG_DATA_COPY, the data set will contain
2898 copies of @var{name} and @var{mpi}. If @var{flags} contains
2899 GCRY_AC_FLAG_DATA_DEALLOC or GCRY_AC_FLAG_DATA_COPY, the values
2900 contained in the data set will be deallocated when they are to be
2901 removed from the data set.
2904 @deftypefun gcry_error_t gcry_ac_data_copy (gcry_ac_data_t *@var{data_cp}, gcry_ac_data_t @var{data})
2905 Create a copy of the data set @var{data} and store it in
2906 @var{data_cp}. FIXME: exact semantics undefined.
2909 @deftypefun unsigned int gcry_ac_data_length (gcry_ac_data_t @var{data})
2910 Returns the number of named MPI values inside of the data set
2914 @deftypefun gcry_error_t gcry_ac_data_get_name (gcry_ac_data_t @var{data}, unsigned int @var{flags}, char *@var{name}, gcry_mpi_t *@var{mpi})
2915 Store the value labelled with @var{name} found in @var{data} in
2916 @var{mpi}. If @var{flags} contains GCRY_AC_FLAG_COPY, store a copy of
2917 the @var{mpi} value contained in the data set. @var{mpi} may be NULL
2918 (this might be useful for checking the existence of an MPI with
2922 @deftypefun gcry_error_t gcry_ac_data_get_index (gcry_ac_data_t @var{data}, unsigned int flags, unsigned int @var{index}, const char **@var{name}, gcry_mpi_t *@var{mpi})
2923 Stores in @var{name} and @var{mpi} the named @var{mpi} value contained
2924 in the data set @var{data} with the index @var{idx}. If @var{flags}
2925 contains GCRY_AC_FLAG_COPY, store copies of the values contained in
2926 the data set. @var{name} or @var{mpi} may be NULL.
2929 @deftypefun void gcry_ac_data_clear (gcry_ac_data_t @var{data})
2930 Destroys any values contained in the data set @var{data}.
2933 @deftypefun gcry_error_t gcry_ac_data_to_sexp (gcry_ac_data_t @var{data}, gcry_sexp_t *@var{sexp}, const char **@var{identifiers})
2934 This function converts the data set @var{data} into a newly created
2935 S-Expression, which is to be stored in @var{sexp}; @var{identifiers}
2936 is a NULL terminated list of C strings, which specifies the structure
2937 of the S-Expression.
2941 If @var{identifiers} is a list of pointers to the strings ``foo'' and
2942 ``bar'' and if @var{data} is a data set containing the values ``val1 =
2943 0x01'' and ``val2 = 0x02'', then the resulting S-Expression will look
2944 like this: (foo (bar ((val1 0x01) (val2 0x02))).
2947 @deftypefun gcry_error gcry_ac_data_from_sexp (gcry_ac_data_t *@var{data}, gcry_sexp_t @var{sexp}, const char **@var{identifiers})
2948 This function converts the S-Expression @var{sexp} into a newly
2949 created data set, which is to be stored in @var{data};
2950 @var{identifiers} is a NULL terminated list of C strings, which
2951 specifies the structure of the S-Expression. If the list of
2952 identifiers does not match the structure of the S-Expression, the
2956 @node Working with IO objects
2957 @section Working with IO objects
2959 Note: IO objects are currently only used in the context of message
2960 encoding/decoding and encryption/signature schemes.
2962 @deftp {Data type} {gcry_ac_io_t}
2963 @code{gcry_ac_io_t} is the type to be used for IO objects.
2966 IO objects provide an uniform IO layer on top of different underlying
2967 IO mechanisms; either they can be used for providing data to the
2968 library (mode is GCRY_AC_IO_READABLE) or they can be used for
2969 retrieving data from the library (mode is GCRY_AC_IO_WRITABLE).
2971 IO object need to be initialized by calling on of the following
2974 @deftypefun void gcry_ac_io_init (gcry_ac_io_t *@var{ac_io}, gcry_ac_io_mode_t @var{mode}, gcry_ac_io_type_t @var{type}, ...);
2975 Initialize @var{ac_io} according to @var{mode}, @var{type} and the
2976 variable list of arguments. The list of variable arguments to specify
2977 depends on the given @var{type}.
2980 @deftypefun void gcry_ac_io_init_va (gcry_ac_io_t *@var{ac_io}, gcry_ac_io_mode_t @var{mode}, gcry_ac_io_type_t @var{type}, va_list @var{ap});
2981 Initialize @var{ac_io} according to @var{mode}, @var{type} and the
2982 variable list of arguments @var{ap}. The list of variable arguments
2983 to specify depends on the given @var{type}.
2986 The following types of IO objects exist:
2989 @item GCRY_AC_IO_STRING
2990 In case of GCRY_AC_IO_READABLE the IO object will provide data from a
2991 memory string. Arguments to specify at initialization time:
2993 @item unsigned char *
2994 Pointer to the beginning of the memory string
2996 Size of the memory string
2998 In case of GCRY_AC_IO_WRITABLE the object will store retrieved data in
2999 a newly allocated memory string. Arguments to specify at
3000 initialization time:
3002 @item unsigned char **
3003 Pointer to address, at which the pointer to the newly created memory
3004 string is to be stored
3006 Pointer to address, at which the size of the newly created memory
3007 string is to be stored
3010 @item GCRY_AC_IO_CALLBACK
3011 In case of GCRY_AC_IO_READABLE the object will forward read requests
3012 to a provided callback function. Arguments to specify at
3013 initialization time:
3015 @item gcry_ac_data_read_cb_t
3016 Callback function to use
3018 Opaque argument to provide to the callback function
3020 In case of GCRY_AC_IO_WRITABLE the object will forward write requests
3021 to a provided callback function. Arguments to specify at
3022 initialization time:
3024 @item gcry_ac_data_write_cb_t
3025 Callback function to use
3027 Opaque argument to provide to the callback function
3031 @node Working with handles
3032 @section Working with handles
3034 In order to use an algorithm, an according handle must be created.
3035 This is done using the following function:
3037 @deftypefun gcry_error_t gcry_ac_open (gcry_ac_handle_t *@var{handle}, int @var{algorithm}, int @var{flags})
3039 Creates a new handle for the algorithm @var{algorithm} and stores it
3040 in @var{handle}. @var{flags} is not used currently.
3042 @var{algorithm} must be a valid algorithm ID, see @xref{Available
3043 algorithms}, for a list of supported algorithms and the according
3044 constants. Besides using the listed constants directly, the functions
3045 @code{gcry_pk_name_to_id} may be used to convert the textual name of
3046 an algorithm into the according numeric ID.
3049 @deftypefun void gcry_ac_close (gcry_ac_handle_t @var{handle})
3050 Destroys the handle @var{handle}.
3053 @node Working with keys
3054 @section Working with keys
3056 @deftp {Data type} gcry_ac_key_type_t
3060 @item GCRY_AC_KEY_TYPE_SECRET
3061 Specifies a secret key.
3062 @item GCRY_AC_KEY_TYPE_PUBLIC
3063 Specifies a public key.
3067 @deftp {Data type} gcry_ac_key_t
3068 This type represents a single `key', either a secret one or a public
3072 @deftp {Data type} gcry_ac_key_pair_t
3073 This type represents a `key pair' containing a secret and a public key.
3076 Key data structures can be created in two different ways; a new key
3077 pair can be generated, resulting in ready-to-use key. Alternatively a
3078 key can be initialized from a given data set.
3080 @deftypefun gcry_error_t gcry_ac_key_init (gcry_ac_key_t *@var{key}, gcry_ac_handle_t @var{handle}, gcry_ac_key_type_t @var{type}, gcry_ac_data_t @var{data})
3081 Creates a new key of type @var{type}, consisting of the MPI values
3082 contained in the data set @var{data} and stores it in @var{key}.
3085 @deftypefun gcry_error_t gcry_ac_key_pair_generate (gcry_ac_handle_t @var{handle}, unsigned int @var{nbits}, void *@var{key_spec}, gcry_ac_key_pair_t *@var{key_pair}, gcry_mpi_t **@var{misc_data})
3087 Generates a new key pair via the handle @var{handle} of @var{NBITS}
3088 bits and stores it in @var{key_pair}.
3090 In case non-standard settings are wanted, a pointer to a structure of
3091 type @code{gcry_ac_key_spec_<algorithm>_t}, matching the selected
3092 algorithm, can be given as @var{key_spec}. @var{misc_data} is not
3093 used yet. Such a structure does only exist for RSA. A descriptions
3094 of the members of the supported structures follows.
3097 @item gcry_ac_key_spec_rsa_t
3100 Generate the key pair using a special @code{e}. The value of @code{e}
3101 has the following meanings:
3104 Let Libgcrypt decide what exponent should be used.
3106 Request the use of a ``secure'' exponent; this is required by some
3107 specification to be 65537.
3109 Try starting at this value until a working exponent is found. Note
3110 that the current implementation leaks some information about the
3111 private key because the incrementation used is not randomized. Thus,
3112 this function will be changed in the future to return a random
3113 exponent of the given size.
3121 gcry_ac_key_pair_t key_pair;
3122 gcry_ac_key_spec_rsa_t rsa_spec;
3124 rsa_spec.e = gcry_mpi_new (0);
3125 gcry_mpi_set_ui (rsa_spec.e, 1)
3127 err = gcry_ac_open (&handle, GCRY_AC_RSA, 0);
3130 err = gcry_ac_key_pair_generate (handle, &key_pair, 1024, (void *) &rsa_spec);
3137 @deftypefun gcry_ac_key_t gcry_ac_key_pair_extract (gcry_ac_key_pair_t @var{key_pair}, gcry_ac_key_type_t @var{which})
3138 Returns the key of type @var{which} out of the key pair
3142 @deftypefun void gcry_ac_key_destroy (gcry_ac_key_t @var{key})
3143 Destroys the key @var{key}.
3146 @deftypefun void gcry_ac_key_pair_destroy (gcry_ac_key_pair_t @var{key_pair})
3147 Destroys the key pair @var{key_pair}.
3150 @deftypefun gcry_ac_data_t gcry_ac_key_data_get (gcry_ac_key_t @var{key})
3151 Returns the data set contained in the key @var{key}.
3154 @deftypefun gcry_error_t gcry_ac_key_test (gcry_ac_handle_t @var{handle}, gcry_ac_key_t @var{key})
3155 Verifies that the private key @var{key} is sane via @var{handle}.
3158 @deftypefun gcry_error_t gcry_ac_key_get_nbits (gcry_ac_handle_t @var{handle}, gcry_ac_key_t @var{key}, unsigned int *@var{nbits})
3159 Stores the number of bits of the key @var{key} in @var{nbits} via @var{handle}.
3162 @deftypefun gcry_error_t gcry_ac_key_get_grip (gcry_ac_handle_t @var{handle}, gcry_ac_key_t @var{key}, unsigned char *@var{key_grip})
3163 Writes the 20 byte long key grip of the key @var{key} to
3164 @var{key_grip} via @var{handle}.
3167 @node Using cryptographic functions
3168 @section Using cryptographic functions
3170 The following flags might be relevant:
3173 @item GCRY_AC_FLAG_NO_BLINDING
3174 Disable any blinding, which might be supported by the chosen
3175 algorithm; blinding is the default.
3178 There exist two kinds of cryptographic functions available through the
3179 ac interface: primitives, and high-level functions.
3181 Primitives deal with MPIs (data sets) directly; what they provide is
3182 direct access to the cryptographic operations provided by an algorithm
3185 High-level functions deal with octet strings, according to a specified
3186 ``scheme''. Schemes make use of ``encoding methods'', which are
3187 responsible for converting the provided octet strings into MPIs, which
3188 are then forwared to the cryptographic primitives. Since schemes are
3189 to be used for a special purpose in order to achieve a particular
3190 security goal, there exist ``encryption schemes'' and ``signature
3191 schemes''. Encoding methods can be used seperately or implicitly
3194 What follows is a description of the cryptographic primitives.
3196 @deftypefun gcry_error_t gcry_ac_data_encrypt (gcry_ac_handle_t @var{handle}, unsigned int @var{flags}, gcry_ac_key_t @var{key}, gcry_mpi_t @var{data_plain}, gcry_ac_data_t **@var{data_encrypted})
3197 Encrypts the plain text MPI value @var{data_plain} with the key public
3198 @var{key} under the control of the flags @var{flags} and stores the
3199 resulting data set into @var{data_encrypted}.
3202 @deftypefun gcry_error_t gcry_ac_data_decrypt (gcry_ac_handle_t @var{handle}, unsigned int @var{flags}, gcry_ac_key_t @var{key}, gcry_mpi_t *@var{data_plain}, gcry_ac_data_t @var{data_encrypted})
3203 Decrypts the encrypted data contained in the data set
3204 @var{data_encrypted} with the secret key KEY under the control of the
3205 flags @var{flags} and stores the resulting plain text MPI value in
3209 @deftypefun gcry_error_t gcry_ac_data_sign (gcry_ac_handle_t @var{handle}, gcry_ac_key_t @var{key}, gcry_mpi_t @var{data}, gcry_ac_data_t *@var{data_signature})
3210 Signs the data contained in @var{data} with the secret key @var{key}
3211 and stores the resulting signature in the data set
3212 @var{data_signature}.
3215 @deftypefun gcry_error_t gcry_ac_data_verify (gcry_ac_handle_t @var{handle}, gcry_ac_key_t @var{key}, gcry_mpi_t @var{data}, gcry_ac_data_t @var{data_signature})
3216 Verifies that the signature contained in the data set
3217 @var{data_signature} is indeed the result of signing the data
3218 contained in @var{data} with the secret key belonging to the public
3222 What follows is a description of the high-level functions.
3224 The type ``gcry_ac_em_t'' is used for specifying encoding methods; the
3225 following methods are supported:
3228 @item GCRY_AC_EME_PKCS_V1_5
3229 PKCS-V1_5 Encoding Method for Encryption. Options must be provided
3230 through a pointer to a correctly initialized object of type
3231 gcry_ac_eme_pkcs_v1_5_t.
3233 @item GCRY_AC_EMSA_PKCS_V1_5
3234 PKCS-V1_5 Encoding Method for Signatures with Appendix. Options must
3235 be provided through a pointer to a correctly initialized object of
3236 type gcry_ac_emsa_pkcs_v1_5_t.
3239 Option structure types:
3242 @item gcry_ac_eme_pkcs_v1_5_t
3244 @item gcry_ac_key_t key
3245 @item gcry_ac_handle_t handle
3247 @item gcry_ac_emsa_pkcs_v1_5_t
3249 @item gcry_md_algo_t md
3254 Encoding methods can be used directly through the following functions:
3256 @deftypefun gcry_error_t gcry_ac_data_encode (gcry_ac_em_t @var{method}, unsigned int @var{flags}, void *@var{options}, unsigned char *@var{m}, size_t @var{m_n}, unsigned char **@var{em}, size_t *@var{em_n})
3257 Encodes the message contained in @var{m} of size @var{m_n} according
3258 to @var{method}, @var{flags} and @var{options}. The newly created
3259 encoded message is stored in @var{em} and @var{em_n}.
3262 @deftypefun gcry_error_t gcry_ac_data_decode (gcry_ac_em_t @var{method}, unsigned int @var{flags}, void *@var{options}, unsigned char *@var{em}, size_t @var{em_n}, unsigned char **@var{m}, size_t *@var{m_n})
3263 Decodes the message contained in @var{em} of size @var{em_n} according
3264 to @var{method}, @var{flags} and @var{options}. The newly created
3265 decoded message is stored in @var{m} and @var{m_n}.
3268 The type ``gcry_ac_scheme_t'' is used for specifying schemes; the
3269 following schemes are supported:
3272 @item GCRY_AC_ES_PKCS_V1_5
3273 PKCS-V1_5 Encryption Scheme. No options can be provided.
3274 @item GCRY_AC_SSA_PKCS_V1_5
3275 PKCS-V1_5 Signature Scheme (with Appendix). Options can be provided
3276 through a pointer to a correctly initialized object of type
3277 gcry_ac_ssa_pkcs_v1_5_t.
3280 Option structure types:
3283 @item gcry_ac_ssa_pkcs_v1_5_t
3285 @item gcry_md_algo_t md
3289 The functions implementing schemes:
3291 @deftypefun gcry_error_t gcry_ac_data_encrypt_scheme (gcry_ac_handle_t @var{handle}, gcry_ac_scheme_t @var{scheme}, unsigned int @var{flags}, void *@var{opts}, gcry_ac_key_t @var{key}, gcry_ac_io_t *@var{io_message}, gcry_ac_io_t *@var{io_cipher})
3292 Encrypts the plain text readable from @var{io_message} through
3293 @var{handle} with the public key @var{key} according to @var{scheme},
3294 @var{flags} and @var{opts}. If @var{opts} is not NULL, it has to be a
3295 pointer to a structure specific to the chosen scheme (gcry_ac_es_*_t).
3296 The encrypted message is written to @var{io_cipher}.
3299 @deftypefun gcry_error_t gcry_ac_data_decrypt_scheme (gcry_ac_handle_t @var{handle}, gcry_ac_scheme_t @var{scheme}, unsigned int @var{flags}, void *@var{opts}, gcry_ac_key_t @var{key}, gcry_ac_io_t *@var{io_cipher}, gcry_ac_io_t *@var{io_message})
3300 Decrypts the cipher text readable from @var{io_cipher} through
3301 @var{handle} with the secret key @var{key} according to @var{scheme},
3302 @var{flags} and @var{opts}. If @var{opts} is not NULL, it has to be a
3303 pointer to a structure specific to the chosen scheme (gcry_ac_es_*_t).
3304 The decrypted message is written to @var{io_message}.
3307 @deftypefun gcry_error_t gcry_ac_data_sign_scheme (gcry_ac_handle_t @var{handle}, gcry_ac_scheme_t @var{scheme}, unsigned int @var{flags}, void *@var{opts}, gcry_ac_key_t @var{key}, gcry_ac_io_t *@var{io_message}, gcry_ac_io_t *@var{io_signature})
3308 Signs the message readable from @var{io_message} through @var{handle}
3309 with the secret key @var{key} according to @var{scheme}, @var{flags}
3310 and @var{opts}. If @var{opts} is not NULL, it has to be a pointer to
3311 a structure specific to the chosen scheme (gcry_ac_ssa_*_t). The
3312 signature is written to @var{io_signature}.
3315 @deftypefun gcry_error_t gcry_ac_data_verify_scheme (gcry_ac_handle_t @var{handle}, gcry_ac_scheme_t @var{scheme}, unsigned int @var{flags}, void *@var{opts}, gcry_ac_key_t @var{key}, gcry_ac_io_t *@var{io_message}, gcry_ac_io_t *@var{io_signature})
3316 Verifies through @var{handle} that the signature readable from
3317 @var{io_signature} is indeed the result of signing the message
3318 readable from @var{io_message} with the secret key belonging to the
3319 public key @var{key} according to @var{scheme} and @var{opts}. If
3320 @var{opts} is not NULL, it has to be an anonymous structure
3321 (gcry_ac_ssa_*_t) specific to the chosen scheme.
3324 @node Handle-independent functions
3325 @section Handle-independent functions
3327 These two functions are deprecated; do not use them for new code.
3329 @deftypefun gcry_error_t gcry_ac_id_to_name (gcry_ac_id_t @var{algorithm}, const char **@var{name})
3330 Stores the textual representation of the algorithm whose id is given
3331 in @var{algorithm} in @var{name}. Deprecated; use @code{gcry_pk_algo_name}.
3334 @deftypefun gcry_error_t gcry_ac_name_to_id (const char *@var{name}, gcry_ac_id_t *@var{algorithm})
3335 Stores the numeric ID of the algorithm whose textual representation is
3336 contained in @var{name} in @var{algorithm}. Deprecated; use
3337 @code{gcry_pk_map_name}.
3340 @c **********************************************************
3341 @c ******************* Random *****************************
3342 @c **********************************************************
3343 @node Random Numbers
3344 @chapter Random Numbers
3347 * Quality of random numbers:: Libgcrypt uses different quality levels.
3348 * Retrieving random numbers:: How to retrieve random numbers.
3351 @node Quality of random numbers
3352 @section Quality of random numbers
3354 @acronym{Libgcypt} offers random numbers of different quality levels:
3356 @deftp {Data type} enum gcry_random_level
3357 The constants for the random quality levels are of this type.
3361 @item GCRY_WEAK_RANDOM
3362 This should not anymore be used. It has recently been changed to an
3363 alias of GCRY_STRONG_RANDOM. Use @code{gcry_create_nonce} instead.
3364 @item GCRY_STRONG_RANDOM
3365 Use this level for e.g. session keys and similar purposes.
3366 @item GCRY_VERY_STRONG_RANDOM
3367 Use this level for e.g. key material.
3370 @node Retrieving random numbers
3371 @section Retrieving random numbers
3373 @deftypefun void gcry_randomize (unsigned char *@var{buffer}, size_t @var{length}, enum gcry_random_level @var{level})
3375 Fill @var{buffer} with @var{length} random bytes using a random quality
3376 as defined by @var{level}.
3379 @deftypefun void * gcry_random_bytes (size_t @var{nbytes}, enum gcry_random_level @var{level})
3381 Allocate a memory block consisting of @var{nbytes} fresh random bytes
3382 using a random quality as defined by @var{level}.
3385 @deftypefun void * gcry_random_bytes_secure (size_t @var{nbytes}, enum gcry_random_level @var{level})
3387 Allocate a memory block consisting of @var{nbytes} fresh random bytes
3388 using a random quality as defined by @var{level}. This function
3389 differs from @code{gcry_random_bytes} in that the returned buffer is
3390 allocated in a ``secure'' area of the memory.
3393 @deftypefun void gcry_create_nonce (unsigned char *@var{buffer}, size_t @var{length})
3395 Fill @var{buffer} with @var{length} unpredictable bytes. This is
3396 commonly called a nonce and may also be used for initialization
3397 vectors and padding. This is an extra function nearly independent of
3398 the other random function for 3 reasons: It better protects the
3399 regular random generator's internal state, provides better performance
3400 and does not drain the precious entropy pool.
3406 @c **********************************************************
3407 @c ******************* S-Expressions ***********************
3408 @c **********************************************************
3410 @chapter S-expressions
3412 S-expressions are used by the public key functions to pass complex data
3413 structures around. These LISP like objects are used by some
3414 cryptographic protocols (cf. RFC-2692) and Libgcrypt provides functions
3415 to parse and construct them. For detailed information, see
3416 @cite{Ron Rivest, code and description of S-expressions,
3417 @uref{http://theory.lcs.mit.edu/~rivest/sexp.html}}.
3420 * Data types for S-expressions:: Data types related with S-expressions.
3421 * Working with S-expressions:: How to work with S-expressions.
3424 @node Data types for S-expressions
3425 @section Data types for S-expressions
3427 @deftp {Data type} gcry_sexp_t
3428 The @code{gcry_sexp_t} type describes an object with the Libgcrypt internal
3429 representation of an S-expression.
3432 @node Working with S-expressions
3433 @section Working with S-expressions
3436 There are several functions to create an Libgcrypt S-expression object
3437 from its external representation or from a string template. There is
3438 also a function to convert the internal representation back into one of
3439 the external formats:
3442 @deftypefun gcry_error_t gcry_sexp_new (@w{gcry_sexp_t *@var{r_sexp}}, @w{const void *@var{buffer}}, @w{size_t @var{length}}, @w{int @var{autodetect}})
3444 This is the generic function to create an new S-expression object from
3445 its external representation in @var{buffer} of @var{length} bytes. On
3446 success the result is stored at the address given by @var{r_sexp}.
3447 With @var{autodetect} set to 0, the data in @var{buffer} is expected to
3448 be in canonized format, with @var{autodetect} set to 1 the parses any of
3449 the defined external formats. If @var{buffer} does not hold a valid
3450 S-expression an error code is returned and @var{r_sexp} set to
3452 Note that the caller is responsible for releasing the newly allocated
3453 S-expression using @code{gcry_sexp_release}.
3456 @deftypefun gcry_error_t gcry_sexp_create (@w{gcry_sexp_t *@var{r_sexp}}, @w{void *@var{buffer}}, @w{size_t @var{length}}, @w{int @var{autodetect}}, @w{void (*@var{freefnc})(void*)})
3458 This function is identical to @code{gcry_sexp_new} but has an extra
3459 argument @var{freefnc}, which, when not set to @code{NULL}, is expected
3460 to be a function to release the @var{buffer}; most likely the standard
3461 @code{free} function is used for this argument. This has the effect of
3462 transferring the ownership of @var{buffer} to the created object in
3463 @var{r_sexp}. The advantage of using this function is that Libgcrypt
3464 might decide to directly use the provided buffer and thus avoid extra
3468 @deftypefun gcry_error_t gcry_sexp_sscan (@w{gcry_sexp_t *@var{r_sexp}}, @w{size_t *@var{erroff}}, @w{const char *@var{buffer}}, @w{size_t @var{length}})
3470 This is another variant of the above functions. It behaves nearly
3471 identical but provides an @var{erroff} argument which will receive the
3472 offset into the buffer where the parsing stopped on error.
3475 @deftypefun gcry_error_t gcry_sexp_build (@w{gcry_sexp_t *@var{r_sexp}}, @w{size_t *@var{erroff}}, @w{const char *@var{format}, ...})
3477 This function creates an internal S-expression from the string template
3478 @var{format} and stores it at the address of @var{r_sexp}. If there is a
3479 parsing error, the function returns an appropriate error code and stores
3480 the offset into @var{format} where the parsing stopped in @var{erroff}.
3481 The function supports a couple of printf-like formatting characters and
3482 expects arguments for some of these escape sequences right after
3483 @var{format}. The following format characters are defined:
3487 The next argument is expected to be of type @code{gcry_mpi_t} and a copy of
3488 its value is inserted into the resulting S-expression.
3490 The next argument is expected to be of type @code{char *} and that
3491 string is inserted into the resulting S-expression.
3493 The next argument is expected to be of type @code{int} and its value is
3494 inserted into the resulting S-expression.
3496 The next argument is expected to be of type @code{int} directly
3497 followed by an argument of type @code{char *}. This represents a
3498 buffer of given length to be inserted into the resulting regular
3503 No other format characters are defined and would return an error. Note
3504 that the format character @samp{%%} does not exists, because a percent
3505 sign is not a valid character in an S-expression.
3508 @deftypefun void gcry_sexp_release (@w{gcry_sexp_t @var{sexp}})
3510 Release the S-expression object @var{sexp}.
3515 The next 2 functions are used to convert the internal representation
3516 back into a regular external S-expression format and to show the
3517 structure for debugging.
3519 @deftypefun size_t gcry_sexp_sprint (@w{gcry_sexp_t @var{sexp}}, @w{int @var{mode}}, @w{char *@var{buffer}}, @w{size_t @var{maxlength}})
3521 Copies the S-expression object @var{sexp} into @var{buffer} using the
3522 format specified in @var{mode}. @var{maxlength} must be set to the
3523 allocated length of @var{buffer}. The function returns the actual
3524 length of valid bytes put into @var{buffer} or 0 if the provided buffer
3525 is too short. Passing @code{NULL} for @var{buffer} returns the required
3526 length for @var{buffer}. For convenience reasons an extra byte with
3527 value 0 is appended to the buffer.
3530 The following formats are supported:
3533 @item GCRYSEXP_FMT_DEFAULT
3534 Returns a convenient external S-expression representation.
3536 @item GCRYSEXP_FMT_CANON
3537 Return the S-expression in canonical format.
3539 @item GCRYSEXP_FMT_BASE64
3540 Not currently supported.
3542 @item GCRYSEXP_FMT_ADVANCED
3543 Returns the S-expression in advanced format.
3547 @deftypefun void gcry_sexp_dump (@w{gcry_sexp_t @var{sexp}})
3549 Dumps @var{sexp} in a format suitable for debugging to Libgcrypt's
3554 Often canonical encoding is used in the external representation. The
3555 following function can be used to check for valid encoding and to learn
3556 the length of the S-expression"
3558 @deftypefun size_t gcry_sexp_canon_len (@w{const unsigned char *@var{buffer}}, @w{size_t @var{length}}, @w{size_t *@var{erroff}}, @w{int *@var{errcode}})
3560 Scan the canonical encoded @var{buffer} with implicit length values and
3561 return the actual length this S-expression uses. For a valid S-expression
3562 it should never return 0. If @var{length} is not 0, the maximum
3563 length to scan is given; this can be used for syntax checks of
3564 data passed from outside. @var{errcode} and @var{erroff} may both be
3565 passed as @code{NULL}.
3571 There are a couple of functions to parse S-expressions and retrieve
3574 @deftypefun gcry_sexp_t gcry_sexp_find_token (@w{const gcry_sexp_t @var{list}}, @w{const char *@var{token}}, @w{size_t @var{toklen}})
3576 Scan the S-expression for a sublist with a type (the car of the list)
3577 matching the string @var{token}. If @var{toklen} is not 0, the token is
3578 assumed to be raw memory of this length. The function returns a newly
3579 allocated S-expression consisting of the found sublist or @code{NULL}
3584 @deftypefun int gcry_sexp_length (@w{const gcry_sexp_t @var{list}})
3586 Return the length of the @var{list}. For a valid S-expression this
3587 should be at least 1.
3591 @deftypefun gcry_sexp_t gcry_sexp_nth (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}})
3593 Create and return a new S-expression from the element with index @var{number} in
3594 @var{list}. Note that the first element has the index 0. If there is
3595 no such element, @code{NULL} is returned.
3598 @deftypefun gcry_sexp_t gcry_sexp_car (@w{const gcry_sexp_t @var{list}})
3600 Create and return a new S-expression from the first element in
3601 @var{list}; this called the "type" and should always exist and be a
3602 string. @code{NULL} is returned in case of a problem.
3605 @deftypefun gcry_sexp_t gcry_sexp_cdr (@w{const gcry_sexp_t @var{list}})
3607 Create and return a new list form all elements except for the first one.
3608 Note that this function may return an invalid S-expression because it
3609 is not guaranteed, that the type exists and is a string. However, for
3610 parsing a complex S-expression it might be useful for intermediate
3611 lists. Returns @code{NULL} on error.
3615 @deftypefun {const char *} gcry_sexp_nth_data (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{size_t *@var{datalen}})
3617 This function is used to get data from a @var{list}. A pointer to the
3618 actual data with index @var{number} is returned and the length of this
3619 data will be stored to @var{datalen}. If there is no data at the given
3620 index or the index represents another list, @code{NULL} is returned.
3621 @strong{Caution:} The returned pointer is valid as long as @var{list} is
3622 not modified or released.
3625 Here is an example on how to extract and print the surname (Meier) from
3626 the S-expression @samp{(Name Otto Meier (address Burgplatz 3))}:
3632 name = gcry_sexp_nth_data (list, 2, &len);
3633 printf ("my name is %.*s\n", (int)len, name);
3637 @deftypefun gcry_mpi_t gcry_sexp_nth_mpi (@w{gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{int @var{mpifmt}})
3639 This function is used to get and convert data from a @var{list}. This
3640 data is assumed to be an MPI stored in the format described by
3641 @var{mpifmt} and returned as a standard Libgcrypt MPI. The caller must
3642 release this returned value using @code{gcry_mpi_release}. If there is
3643 no data at the given index, the index represents a list or the value
3644 can't be converted to an MPI, @code{NULL} is returned.
3648 @c **********************************************************
3649 @c ******************* MPIs ******** ***********************
3650 @c **********************************************************
3652 @chapter MPI library
3655 * Data types:: MPI related data types.
3656 * Basic functions:: First steps with MPI numbers.
3657 * MPI formats:: External representation of MPIs.
3658 * Calculations:: Performing MPI calculations.
3659 * Comparisons:: How to compare MPI values.
3660 * Bit manipulations:: How to access single bits of MPI values.
3661 * Miscellaneous:: Miscellaneous MPI functions.
3664 Public key cryptography is based on mathematics with large numbers. To
3665 implement the public key functions, a library for handling these large
3666 numbers is required. Because of the general usefulness of such a
3667 library, its interface is exposed by Libgcrypt. The implementation is
3668 based on an old release of GNU Multi-Precision Library (GMP) but in the
3669 meantime heavily modified and stripped down to what is required for
3670 cryptography. For a lot of CPUs, high performance assembler
3671 implementations of some very low level functions are used to gain much
3672 better performance than with the standard C implementation.
3675 In the context of Libgcrypt and in most other applications, these large
3676 numbers are called MPIs (multi-precision-integers).
3681 @deftp {Data type} gcry_mpi_t
3682 The @code{gcry_mpi_t} type represents an object to hold an MPI.
3685 @node Basic functions
3686 @section Basic functions
3689 To work with MPIs, storage must be allocated and released for the
3690 numbers. This can be done with one of these functions:
3692 @deftypefun gcry_mpi_t gcry_mpi_new (@w{unsigned int @var{nbits}})
3694 Allocate a new MPI object, initialize it to 0 and initially allocate
3695 enough memory for a number of at least @var{nbits}. This pre-allocation is
3696 only a small performance issue and not actually necessary because
3697 Libgcrypt automatically re-allocates the required memory.
3700 @deftypefun gcry_mpi_t gcry_mpi_snew (@w{unsigned int @var{nbits}})
3702 This is identical to @code{gcry_mpi_new} but allocates the MPI in the so
3703 called "secure memory" which in turn will take care that all derived
3704 values will also be stored in this "secure memory". Use this for highly
3705 confidential data like private key parameters.
3708 @deftypefun gcry_mpi_t gcry_mpi_copy (@w{const gcry_mpi_t @var{a}})
3710 Create a new MPI as the exact copy of @var{a}.
3714 @deftypefun void gcry_mpi_release (@w{gcry_mpi_t @var{a}})
3716 Release the MPI @var{a} and free all associated resources. Passing
3717 @code{NULL} is allowed and ignored. When a MPI stored in the "secure
3718 memory" is released, that memory gets wiped out immediately.
3722 The simplest operations are used to assign a new value to an MPI:
3724 @deftypefun gcry_mpi_t gcry_mpi_set (@w{gcry_mpi_t @var{w}}, @w{const gcry_mpi_t @var{u}})
3726 Assign the value of @var{u} to @var{w} and return @var{w}. If
3727 @code{NULL} is passed for @var{w}, a new MPI is allocated, set to the
3728 value of @var{u} and returned.
3731 @deftypefun gcry_mpi_t gcry_mpi_set_ui (@w{gcry_mpi_t @var{w}}, @w{unsigned long @var{u}})
3733 Assign the value of @var{u} to @var{w} and return @var{w}. If
3734 @code{NULL} is passed for @var{w}, a new MPI is allocated, set to the
3735 value of @var{u} and returned. This function takes an @code{unsigned
3736 int} as type for @var{u} and thus it is only possible to set @var{w} to
3737 small values (usually up to the word size of the CPU).
3740 @deftypefun void gcry_mpi_swap (@w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}})
3742 Swap the values of @var{a} and @var{b}.
3746 @section MPI formats
3749 The following functions are used to convert between an external
3750 representation of an MPI and the internal one of Libgcrypt.
3752 @deftypefun gcry_error_t gcry_mpi_scan (@w{gcry_mpi_t *@var{r_mpi}}, @w{enum gcry_mpi_format @var{format}}, @w{const unsigned char *@var{buffer}}, @w{size_t @var{buflen}}, @w{size_t *@var{nscanned}})
3754 Convert the external representation of an integer stored in @var{buffer}
3755 with a length of @var{buflen} into a newly created MPI returned which
3756 will be stored at the address of @var{r_mpi}. For certain formats the
3757 length argument is not required and may be passed as @code{0}. After a
3758 successful operation the variable @var{nscanned} receives the number of
3759 bytes actually scanned unless @var{nscanned} was given as
3760 @code{NULL}. @var{format} describes the format of the MPI as stored in
3764 @item GCRYMPI_FMT_STD
3765 2-complement stored without a length header.
3767 @item GCRYMPI_FMT_PGP
3768 As used by OpenPGP (only defined as unsigned). This is basically
3769 @code{GCRYMPI_FMT_STD} with a 2 byte big endian length header.
3771 @item GCRYMPI_FMT_SSH
3772 As used in the Secure Shell protocol. This is @code{GCRYMPI_FMT_STD}
3773 with a 4 byte big endian header.
3775 @item GCRYMPI_FMT_HEX
3776 Stored as a C style string with each byte of the MPI encoded as 2 hex
3777 digits. When using this format, @var{buflen} must be zero.
3779 @item GCRYMPI_FMT_USG
3780 Simple unsigned integer.
3784 Note that all of the above formats store the integer in big-endian
3789 @deftypefun gcry_error_t gcry_mpi_print (@w{enum gcry_mpi_format @var{format}}, @w{unsigned char *@var{buffer}}, @w{size_t @var{buflen}}, @w{size_t *@var{nwritten}}, @w{const gcry_mpi_t @var{a}})
3791 Convert the MPI @var{a} into an external representation described by
3792 @var{format} (see above) and store it in the provided @var{buffer}
3793 which has a usable length of at least the @var{buflen} bytes. If
3794 @var{nwritten} is not NULL, it will receive the number of bytes
3795 actually stored in @var{buffer} after a successful operation.
3798 @deftypefun gcry_error_t gcry_mpi_aprint (@w{enum gcry_mpi_format @var{format}}, @w{unsigned char **@var{buffer}}, @w{size_t *@var{nbytes}}, @w{const gcry_mpi_t @var{a}})
3800 Convert the MPI @var{a} into an external representation described by
3801 @var{format} (see above) and store it in a newly allocated buffer which
3802 address will be stored in the variable @var{buffer} points to. The
3803 number of bytes stored in this buffer will be stored in the variable
3804 @var{nbytes} points to, unless @var{nbytes} is @code{NULL}.
3807 @deftypefun void gcry_mpi_dump (@w{const gcry_mpi_t @var{a}})
3809 Dump the value of @var{a} in a format suitable for debugging to
3810 Libgcrypt's logging stream. Note that one leading space but no trailing
3811 space or linefeed will be printed. It is okay to pass @code{NULL} for
3817 @section Calculations
3820 Basic arithmetic operations:
3822 @deftypefun void gcry_mpi_add (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
3824 @math{@var{w} = @var{u} + @var{v}}.
3828 @deftypefun void gcry_mpi_add_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
3830 @math{@var{w} = @var{u} + @var{v}}. Note that @var{v} is an unsigned integer.
3834 @deftypefun void gcry_mpi_addm (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}}, @w{gcry_mpi_t @var{m}})
3836 @math{@var{w} = @var{u} + @var{v} \bmod @var{m}}.
3839 @deftypefun void gcry_mpi_sub (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
3841 @math{@var{w} = @var{u} - @var{v}}.
3844 @deftypefun void gcry_mpi_sub_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
3846 @math{@var{w} = @var{u} - @var{v}}. @var{v} is an unsigned integer.
3849 @deftypefun void gcry_mpi_subm (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}}, @w{gcry_mpi_t @var{m}})
3851 @math{@var{w} = @var{u} - @var{v} \bmod @var{m}}.
3854 @deftypefun void gcry_mpi_mul (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
3856 @math{@var{w} = @var{u} * @var{v}}.
3859 @deftypefun void gcry_mpi_mul_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
3861 @math{@var{w} = @var{u} * @var{v}}. @var{v} is an unsigned integer.
3864 @deftypefun void gcry_mpi_mulm (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}}, @w{gcry_mpi_t @var{m}})
3866 @math{@var{w} = @var{u} * @var{v} \bmod @var{m}}.
3869 @deftypefun void gcry_mpi_mul_2exp (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{e}})
3871 @c FIXME: I am in need for a real TeX{info} guru:
3872 @c I don't know why TeX can grok @var{e} here.
3873 @math{@var{w} = @var{u} * 2^e}.
3876 @deftypefun void gcry_mpi_div (@w{gcry_mpi_t @var{q}}, @w{gcry_mpi_t @var{r}}, @w{gcry_mpi_t @var{dividend}}, @w{gcry_mpi_t @var{divisor}}, @w{int @var{round}})
3878 @math{@var{q} = @var{dividend} / @var{divisor}}, @math{@var{r} =
3879 @var{dividend} \bmod @var{divisor}}. @var{q} and @var{r} may be passed
3880 as @code{NULL}. @var{round} should be negative or 0.
3883 @deftypefun void gcry_mpi_mod (@w{gcry_mpi_t @var{r}}, @w{gcry_mpi_t @var{dividend}}, @w{gcry_mpi_t @var{divisor}})
3885 @math{@var{r} = @var{dividend} \bmod @var{divisor}}.
3888 @deftypefun void gcry_mpi_powm (@w{gcry_mpi_t @var{w}}, @w{const gcry_mpi_t @var{b}}, @w{const gcry_mpi_t @var{e}}, @w{const gcry_mpi_t @var{m}})
3890 @c I don't know why TeX can grok @var{e} here.
3891 @math{@var{w} = @var{b}^e \bmod @var{m}}.
3894 @deftypefun int gcry_mpi_gcd (@w{gcry_mpi_t @var{g}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}})
3896 Set @var{g} to the greatest common divisor of @var{a} and @var{b}.
3897 Return true if the @var{g} is 1.
3900 @deftypefun int gcry_mpi_invm (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{m}})
3902 Set @var{x} to the multiplicative inverse of @math{@var{a} \bmod @var{m}}.
3903 Return true if the inverse exists.
3908 @section Comparisons
3911 The next 2 functions are used to compare MPIs:
3914 @deftypefun int gcry_mpi_cmp (@w{const gcry_mpi_t @var{u}}, @w{const gcry_mpi_t @var{v}})
3916 Compare the big integer number @var{u} and @var{v} returning 0 for
3917 equality, a positive value for @var{u} > @var{v} and a negative for
3921 @deftypefun int gcry_mpi_cmp_ui (@w{const gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
3923 Compare the big integer number @var{u} with the unsigned integer @var{v}
3924 returning 0 for equality, a positive value for @var{u} > @var{v} and a
3925 negative for @var{u} < @var{v}.
3929 @node Bit manipulations
3930 @section Bit manipulations
3933 There are a couple of functions to get information on arbitrary bits
3934 in an MPI and to set or clear them:
3936 @deftypefun {unsigned int} gcry_mpi_get_nbits (@w{gcry_mpi_t @var{a}})
3938 Return the number of bits required to represent @var{a}.
3941 @deftypefun int gcry_mpi_test_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
3943 Return true if bit number @var{n} (counting from 0) is set in @var{a}.
3946 @deftypefun void gcry_mpi_set_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
3948 Set bit number @var{n} in @var{a}.
3951 @deftypefun void gcry_mpi_clear_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
3953 Clear bit number @var{n} in @var{a}.
3956 @deftypefun void gcry_mpi_set_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
3958 Set bit number @var{n} in @var{a} and clear all bits greater than @var{n}.
3961 @deftypefun void gcry_mpi_clear_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
3963 Clear bit number @var{n} in @var{a} and all bits greater than @var{n}.
3966 @deftypefun void gcry_mpi_rshift (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
3968 Shift the value of @var{a} by @var{n} bits to the right and store the
3973 @section Miscellaneous
3975 @deftypefun gcry_mpi_t gcry_mpi_set_opaque (@w{gcry_mpi_t @var{a}}, @w{void *@var{p}}, @w{unsigned int @var{nbits}})
3977 Store @var{nbits} of the value @var{p} points to in @var{a} and mark
3978 @var{a} as an opaque value (i.e. an value that can't be used for any
3979 math calculation and is only used to store an arbitrary bit pattern in
3982 WARNING: Never use an opaque MPI for actual math operations. The only
3983 valid functions are gcry_mpi_get_opaque and gcry_mpi_release. Use
3984 gcry_mpi_scan to convert a string of arbitrary bytes into an MPI.
3988 @deftypefun {void *} gcry_mpi_get_opaque (@w{gcry_mpi_t @var{a}}, @w{unsigned int *@var{nbits}})
3990 Return a pointer to an opaque value stored in @var{a} and return its
3991 size in @var{nbits}. Note that the returned pointer is still owned by
3992 @var{a} and that the function should never be used for an non-opaque
3996 @deftypefun void gcry_mpi_set_flag (@w{gcry_mpi_t @var{a}}, @w{enum gcry_mpi_flag @var{flag}})
3998 Set the @var{flag} for the MPI @var{a}. Currently only the flag
3999 @code{GCRYMPI_FLAG_SECURE} is allowed to convert @var{a} into an MPI
4000 stored in "secure memory".
4003 @deftypefun void gcry_mpi_clear_flag (@w{gcry_mpi_t @var{a}}, @w{enum gcry_mpi_flag @var{flag}})
4005 Clear @var{flag} for the big integer @var{a}. Note that this function is
4006 currently useless as no flags are allowed.
4009 @deftypefun int gcry_mpi_get_flag (@w{gcry_mpi_t @var{a}}, @w{enum gcry_mpi_flag @var{flag}})
4011 Return true when the @var{flag} is set for @var{a}.
4014 @deftypefun void gcry_mpi_randomize (@w{gcry_mpi_t @var{w}}, @w{unsigned int @var{nbits}}, @w{enum gcry_random_level @var{level}})
4016 Set the big integer @var{w} to a random value of @var{nbits}, using
4017 random data quality of level @var{level}. In case @var{nbits} is not
4018 a multiple of a byte, @var{nbits} is rounded up to the next byte
4022 @c **********************************************************
4023 @c ******************** Prime numbers ***********************
4024 @c **********************************************************
4026 @chapter Prime numbers
4029 * Generation:: Generation of new prime numbers.
4030 * Checking:: Checking if a given number is prime.
4036 @deftypefun gcry_error_t gcry_prime_generate (gcry_mpi_t *@var{prime},unsigned int @var{prime_bits}, unsigned int @var{factor_bits}, gcry_mpi_t **@var{factors}, gcry_prime_check_func_t @var{cb_func}, void *@var{cb_arg}, gcry_random_level_t @var{random_level}, unsigned int @var{flags})
4038 Generate a new prime number of @var{prime_bits} bits and store it in
4039 @var{prime}. If @var{factor_bits} is non-zero, one of the prime factors
4040 of (@var{prime} - 1) / 2 must be @var{factor_bits} bits long. If
4041 @var{factors} is non-zero, allocate a new, @code{NULL}-terminated array
4042 holding the prime factors and store it in @var{factors}. @var{flags}
4043 might be used to influence the prime number generation process.
4046 @deftypefun gcry_prime_group_generator (gcry_mpi_t *@var{r_g},
4047 gcry_mpi_t @var{prime}, gcry_mpi_t *@var{factors}, gcry_mpi_t @var{start_g})
4049 Find a generator for @var{prime} where the factorization of
4050 (@var{prime}-1) is in the @code{NULL} terminated array @var{factors}.
4051 Return the generator as a newly allocated MPI in @var{r_g}. If
4052 @var{start_g} is not NULL, use this as the start for the search.
4055 @deftypefun void gcry_prime_release_factors (gcry_mpi_t *@var{factors})
4057 Convenience function to release the @var{factors} array.
4063 @deftypefun gcry_error_t gcry_prime_check (gcry_mpi_t @var{p}, unsigned int @var{flags})
4065 Check wether the number @var{p} is prime. Returns zero in case @var{p}
4066 is indeed a prime, returns @code{GPG_ERR_NO_PRIME} in case @var{p} is
4067 not a prime and a different error code in case something went horribly
4071 @c **********************************************************
4072 @c ******************** Utilities ***************************
4073 @c **********************************************************
4078 * Memory allocation:: Functions related with memory allocation.
4081 @node Memory allocation
4082 @section Memory allocation
4084 @deftypefun void *gcry_malloc (size_t @var{n})
4086 This function tries to allocate @var{n} bytes of memory. On success
4087 it returns a pointer to the memory area, in an out-of-core condition,
4091 @deftypefun void *gcry_malloc_secure (size_t @var{n})
4092 Like @code{gcry_malloc}, but uses secure memory.
4095 @deftypefun void *gcry_calloc (size_t @var{n})
4097 This function tries to allocate @var{n} bytes of cleared memory
4098 (i.e. memory that is initialized with zero bytes). On success it
4099 returns a pointer to the memory area, in an out-of-core condition, it
4103 @deftypefun void *gcry_calloc_secure (size_t @var{n})
4104 Like @code{gcry_calloc}, but uses secure memory.
4107 @deftypefun void *gcry_realloc (void *@var{p}, size_t @var{n})
4109 This function tries to resize the memory area pointed to by @var{p} to
4110 @var{n} bytes. On success it returns a pointer to the new memory
4111 area, in an out-of-core condition, it returns NULL. Depending on
4112 whether the memory pointed to by @var{p} is secure memory or not,
4113 gcry_realloc tries to use secure memory as well.
4116 @deftypefun void gcry_free (void *@var{p})
4117 Release the memory area pointed to by @var{p}.
4120 @c **********************************************************
4121 @c ******************* Appendices *************************
4122 @c **********************************************************
4129 @unnumbered Concept Index
4133 @node Function and Data Index
4134 @unnumbered Function and Data Index
4140 /* Version check should be the very first gcry call because it
4141 makes sure that constructor functions are run. */
4142 if (!gcry_check_version (GCRYPT_VERSION))
4143 die ("version mismatch\n");
4144 /* Many applications don't require secure memory, so they should
4145 disable it right away. There won't be a problem unless one makes
4146 use of a feature which requires secure memory - in that case the
4147 process would abort because the secmem is not initialized. */
4148 gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
4150 /* .. add whatever initialization you want, but better don't make calls
4151 to libgcrypt from more than one thread ... */
4153 /* Tell Libgcrypt that initialization has completed. */
4154 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
4157 If you require secure memory, this code should be used:
4159 if (!gcry_check_version (GCRYPT_VERSION))
4160 die ("version mismatch\n");
4161 /* We don't want to see any warnings, e.g. because we have not yet
4162 parsed options which might be used to suppress such warnings */
4163 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
4167 /* Allocate a pool of 16k secure memory. This also drops privileges
4169 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
4171 /* It is now okay to let Libgcrypt complain when there was/is a problem
4172 with the secure memory. */
4173 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
4175 /* Tell Libgcrypt that initialization has completed. */
4176 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
4179 This sounds a bit complicated but has the advantage that the caller
4180 must decide whether he wants secure memory or not - there is no
4183 It is important that this initialization is not done by a library but
4184 in the application. The library might want to check for finished
4185 initialization using:
4187 if (!gcry_control (GCRYCTL_INITIALIZATION_FINISHED_P))
4188 return MYLIB_ERROR_LIBGCRYPT_NOT_INITIALIZED;
4191 @c LocalWords: int HD