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 @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 Certain parts of gcrypt.h may be excluded by defining these macros:
294 @item GCRYPT_NO_MPI_MACROS
295 Do not define the shorthand macros @code{mpi_*} for @code{gcry_mpi_*}.
297 @item GCRYPT_NO_DEPRECATED
298 Do not include defintions for deprecated features.
302 @node Building sources
303 @section Building sources
305 If you want to compile a source file including the `gcrypt.h' header
306 file, you must make sure that the compiler can find it in the
307 directory hierarchy. This is accomplished by adding the path to the
308 directory in which the header file is located to the compilers include
309 file search path (via the @option{-I} option).
311 However, the path to the include file is determined at the time the
312 source is configured. To solve this problem, Libgcrypt ships with a small
313 helper program @command{libgcrypt-config} that knows the path to the
314 include file and other configuration options. The options that need
315 to be added to the compiler invocation at compile time are output by
316 the @option{--cflags} option to @command{libgcrypt-config}. The following
317 example shows how it can be used at the command line:
320 gcc -c foo.c `libgcrypt-config --cflags`
323 Adding the output of @samp{libgcrypt-config --cflags} to the compilers
324 command line will ensure that the compiler can find the Libgcrypt header
327 A similar problem occurs when linking the program with the library.
328 Again, the compiler has to find the library files. For this to work,
329 the path to the library files has to be added to the library search path
330 (via the @option{-L} option). For this, the option @option{--libs} to
331 @command{libgcrypt-config} can be used. For convenience, this option
332 also outputs all other options that are required to link the program
333 with the Libgcrypt libraries (in particular, the @samp{-lgcrypt}
334 option). The example shows how to link @file{foo.o} with the Libgcrypt
335 library to a program @command{foo}.
338 gcc -o foo foo.o `libgcrypt-config --libs`
341 Of course you can also combine both examples to a single command by
342 specifying both options to @command{libgcrypt-config}:
345 gcc -o foo foo.c `libgcrypt-config --cflags --libs`
348 @node Building sources using Automake
349 @section Building sources using Automake
351 It is much easier if you use GNU Automake instead of writing your own
352 Makefiles. If you do that, you do not have to worry about finding and
353 invoking the @command{libgcrypt-config} script at all.
354 Libgcrypt provides an extension to Automake that does all
357 @c A simple macro for optional variables.
359 @r{[}@var{\varname\}@r{]}
361 @defmac AM_PATH_LIBGCRYPT (@ovar{minimum-version}, @ovar{action-if-found}, @ovar{action-if-not-found})
362 Check whether Libgcrypt (at least version
363 @var{minimum-version}, if given) exists on the host system. If it is
364 found, execute @var{action-if-found}, otherwise do
365 @var{action-if-not-found}, if given.
367 Additionally, the function defines @code{LIBGCRYPT_CFLAGS} to the
368 flags needed for compilation of the program to find the
369 @file{gcrypt.h} header file, and @code{LIBGCRYPT_LIBS} to the linker
370 flags needed to link the program to the Libgcrypt library.
373 You can use the defined Autoconf variables like this in your
377 AM_CPPFLAGS = $(LIBGCRYPT_CFLAGS)
378 LDADD = $(LIBGCRYPT_LIBS)
381 @node Initializing the library
382 @section Initializing the library
384 Before the library can be used, it must initialize itself. This is
385 achieved by invoking the function @code{gcry_check_version} described
388 Also, it is often desirable to check that the version of
389 Libgcrypt used is indeed one which fits all requirements.
390 Even with binary compatibility, new features may have been introduced,
391 but due to problem with the dynamic linker an old version may actually
392 be used. So you may want to check that the version is okay right
393 after program startup.
395 @deftypefun const char *gcry_check_version (const char *@var{req_version})
397 The function @code{gcry_check_version} initializes the sub-systems
398 used by Libgcrypt and must be invoked before any other function in the
399 library, with the exception of the @code{GCRYCTL_SET_THREAD_CBS}
400 command (called via the @code{gcry_control} function), see
401 @xref{Multi-Threading}.
403 Furthermore, this function returns the version number of the library.
404 It can also verify that the version number is higher than a certain
405 required version number @var{req_version}, if this value is not a null
410 @node Multi-Threading
411 @section Multi-Threading
413 As mentioned earlier, the Libgcrypt library is
414 thread-safe if you adhere to the following requirements:
418 If your application is multi-threaded, you must set the thread support
419 callbacks with the @code{GCRYCTL_SET_THREAD_CBS} command
420 @strong{before} any other function in the library.
422 This is easy enough if you are indeed writing an application using
423 Libgcrypt. It is rather problematic if you are writing a library
424 instead. Here are some tips what to do if you are writing a library:
426 If your library requires a certain thread package, just initialize
427 Libgcrypt to use this thread package. If your library supports multiple
428 thread packages, but needs to be configured, you will have to
429 implement a way to determine which thread package the application
430 wants to use with your library anyway. Then configure Libgcrypt to use
433 If your library is fully reentrant without any special support by a
434 thread package, then you are lucky indeed. Unfortunately, this does
435 not relieve you from doing either of the two above, or use a third
436 option. The third option is to let the application initialize Libgcrypt
437 for you. Then you are not using Libgcrypt transparently, though.
439 As if this was not difficult enough, a conflict may arise if two
440 libraries try to initialize Libgcrypt independently of each others, and
441 both such libraries are then linked into the same application. To
442 make it a bit simpler for you, this will probably work, but only if
443 both libraries have the same requirement for the thread package. This
444 is currently only supported for the non-threaded case, GNU Pth and
445 pthread. Support for more thread packages is easy to add, so contact
446 us if you require it.
449 The function @code{gcry_check_version} must be called before any other
450 function in the library, except the @code{GCRYCTL_SET_THREAD_CBS}
451 command (called via the @code{gcry_control} function), because it
452 initializes the thread support subsystem in Libgcrypt. To
453 achieve this in multi-threaded programs, you must synchronize the
454 memory with respect to other threads that also want to use
455 Libgcrypt. For this, it is sufficient to call
456 @code{gcry_check_version} before creating the other threads using
457 Libgcrypt@footnote{At least this is true for POSIX threads,
458 as @code{pthread_create} is a function that synchronizes memory with
459 respects to other threads. There are many functions which have this
460 property, a complete list can be found in POSIX, IEEE Std 1003.1-2003,
461 Base Definitions, Issue 6, in the definition of the term ``Memory
462 Synchronization''. For other thread packages, more relaxed or more
463 strict rules may apply.}.
467 Just like the function @code{gpg_strerror}, the function
468 @code{gcry_strerror} is not thread safe. You have to use
469 @code{gpg_strerror_r} instead.
473 Libgcrypt contains convenient macros, which define the
474 necessary thread callbacks for PThread and for GNU Pth:
477 @item GCRY_THREAD_OPTION_PTH_IMPL
479 This macro defines the following (static) symbols: gcry_pth_init,
480 gcry_pth_mutex_init, gcry_pth_mutex_destroy, gcry_pth_mutex_lock,
481 gcry_pth_mutex_unlock, gcry_pth_read, gcry_pth_write, gcry_pth_select,
482 gcry_pth_waitpid, gcry_pth_accept, gcry_pth_connect, gcry_threads_pth.
484 After including this macro, gcry_control() shall be used with a
485 command of GCRYCTL_SET_THREAD_CBS in order to register the thread
486 callback structure named ``gcry_threads_pth''.
488 @item GCRY_THREAD_OPTION_PTHREAD_IMPL
490 This macro defines the following (static) symbols:
491 gcry_pthread_mutex_init, gcry_pthread_mutex_destroy, gcry_mutex_lock,
492 gcry_mutex_unlock, gcry_threads_pthread.
494 After including this macro, gcry_control() shall be used with a
495 command of GCRYCTL_SET_THREAD_CBS in order to register the thread
496 callback structure named ``gcry_threads_pthread''.
499 Note that these macros need to be terminated with a semicolon. Keep
500 in mind that these are convenient macros for C programmers; C++
501 programmers might have to wrap these macros in an ``extern C'' body.
503 @c **********************************************************
504 @c ******************* General ****************************
505 @c **********************************************************
507 @chapter Generalities
510 * Controlling the library:: Controlling Libgcrypt's behavior.
511 * Modules:: Description of extension modules.
512 * Error Handling:: Error codes and such.
515 @node Controlling the library
516 @section Controlling the library
518 @deftypefun gcry_error_t gcry_control (enum gcry_ctl_cmds @var{cmd}, ...)
520 This function can be used to influence the general behavior of
521 Libgcrypt in several ways. Depending on @var{cmd}, more
522 arguments can or have to be provided.
525 @item GCRYCTL_ENABLE_M_GUARD; Arguments: none
526 This command enables the built-in memory guard. It must not be used to
527 activate the memory guard after the memory management has already been
528 used; therefore it can ONLY be used at initialization time. Note that
529 the memory guard is NOT used when the user of the library has set his
530 own memory management callbacks.
532 @item GCRYCTL_ENABLE_QUICK_RANDOM; Arguments: none
533 This command inhibits the use the very secure random quality level
534 (@code{GCRY_VERY_STRONG_RANDOM}) and degrades all request down to
535 @code{GCRY_STRONG_RANDOM}. In general this is not recommened. However,
536 for some applications the extra quality random Libgcrypt tries to create
537 is not justified and this option may help to get better performace.
538 Please check with a crypto expert whether this option can be used for
541 This option can only be used at initialization time.
544 @item GCRYCTL_DUMP_RANDOM_STATS
545 This command dumps PRNG related statistics to the librarys logging
548 @item GCRYCTL_DUMP_MEMORY_STATS
549 This command dumps memory manamgent related statistics to the librarys
552 @item GCRYCTL_DUMP_SECMEM_STATS
553 This command dumps secure memory manamgent related statistics to the
554 librarys logging stream.
556 @item GCRYCTL_DUMP_CONFIG; Arguments: none
557 This command dumps information pertaining to the configuration of
558 libgcrypt to the logging stream. It may be used before the
559 intialization has been finished but not before a gcry_version_check.
561 @item GCRYCTL_DROP_PRIVS
562 This command disables the use of secure memory and drops the priviliges
563 of the current process. FIXME.
565 @item GCRYCTL_DISABLE_SECMEM
566 This command disables the use of secure memory. FIXME.
568 @item GCRYCTL_INIT_SECMEM
569 @item GCRYCTL_TERM_SECMEM
570 @item GCRYCTL_DISABLE_SECMEM_WARN
571 @item GCRYCTL_SUSPEND_SECMEM_WARN
572 @item GCRYCTL_RESUME_SECMEM_WARN
574 @item GCRYCTL_USE_SECURE_RNDPOOL; Arguments: none
576 This command tells the PRNG to store random numbers in secure memory.
577 FIXME: what about initialization time?
579 @item GCRYCTL_SET_RANDOM_SEED_FILE; Arguments: const char *filename
581 This command specifies the file, which is to be used as seed file for
582 the PRNG. If the seed file is registered prior to initialization of the
583 PRNG, the seed file's content (if it exists and seems to be valid) is
584 fed into the PRNG pool. After the seed file has been registered, the
585 PRNG can be signalled to write out the PRNG pool's content into the seed
586 file with the following command.
589 @item GCRYCTL_UPDATE_RANDOM_SEED_FILE; Arguments: none
591 Write out the PRNG pool's content into the registered seed file.
593 Multiple instances of the applications sharing the same random seed file
594 can be started in parallel, in which case they will read out the same
595 pool and then race for updating it (the last update overwrites earlier
596 updates). They will differentiate only by the weak entropy that is
597 added in read_seed_file based on the PID and clock, and up to 16 bytes
598 of weak random non-blockingly. The consequence is that the output of
599 these different instances is correlated to some extent. In the perfect
600 scenario, the attacker can control (or at least guess) the PID and clock
601 of the application, and drain the system's entropy pool to reduce the
602 "up to 16 bytes" above to 0. Then the dependencies of the inital states
603 of the pools are completely known. Note that this is not an issue if
604 random of @code{GCRY_VERY_STRONG_RANDOM} quality is requested as in this
605 case enough extra entropy gets mixed.
607 @item GCRYCTL_SET_VERBOSITY
610 @item GCRYCTL_SET_DEBUG_FLAGS
611 @item GCRYCTL_CLEAR_DEBUG_FLAGS
612 @item GCRYCTL_DISABLE_INTERNAL_LOCKING
613 @item GCRYCTL_ANY_INITIALIZATION_P
614 @item GCRYCTL_INITIALIZATION_FINISHED_P
615 @item GCRYCTL_INITIALIZATION_FINISHED
617 @item GCRYCTL_SET_THREAD_CBS; Arguments: struct ath_ops *ath_ops
619 This command registers a thread-callback structure. See section ``multi
620 threading'' for more information on this command.
622 @item GCRYCTL_FAST_POLL
624 Run a fast random poll.
627 @item GCRYCTL_SET_RNDEGD_SOCKET; Arguments: const char *filename
629 This command may be used to override the default name of the EGD socket
630 to connect to. It may be used only during initialization as it is not
631 thread safe. Changing the socket name again is not supported. The
632 function may return an error if the given filename is too long for a
635 EGD is an alternative random gatherer, used only on a few systems.
646 Libgcrypt supports the use of `extension modules', which
647 implement algorithms in addition to those already built into the library
650 @deftp {Data type} gcry_module_t
651 This data type represents a `module'.
654 Functions registering modules provided by the user take a `module
655 specification structure' as input and return a value of
656 @code{gcry_module_t} and an ID that is unique in the modules'
657 category. This ID can be used to reference the newly registered
658 module. After registering a module successfully, the new functionality
659 should be able to be used through the normal functions provided by
660 Libgcrypt until it is unregistered again.
662 @c **********************************************************
663 @c ******************* Errors ****************************
664 @c **********************************************************
666 @section Error Handling
668 Many functions in Libgcrypt can return an error if they
669 fail. For this reason, the application should always catch the error
670 condition and take appropriate measures, for example by releasing the
671 resources and passing the error up to the caller, or by displaying a
672 descriptive message to the user and cancelling the operation.
674 Some error values do not indicate a system error or an error in the
675 operation, but the result of an operation that failed properly. For
676 example, if you try to decrypt a tempered message, the decryption will
677 fail. Another error value actually means that the end of a data
678 buffer or list has been reached. The following descriptions explain
679 for many error codes what they mean usually. Some error values have
680 specific meanings if returned by a certain functions. Such cases are
681 described in the documentation of those functions.
683 Libgcrypt uses the @code{libgpg-error} library. This allows to share
684 the error codes with other components of the GnuPG system, and to pass
685 error values transparently from the crypto engine, or some helper
686 application of the crypto engine, to the user. This way no
687 information is lost. As a consequence, Libgcrypt does not use its own
688 identifiers for error codes, but uses those provided by
689 @code{libgpg-error}. They usually start with @code{GPG_ERR_}.
691 However, Libgcrypt does provide aliases for the functions
692 defined in libgpg-error, which might be preferred for name space
696 Most functions in Libgcrypt return an error code in the case
697 of failure. For this reason, the application should always catch the
698 error condition and take appropriate measures, for example by
699 releasing the resources and passing the error up to the caller, or by
700 displaying a descriptive message to the user and canceling the
703 Some error values do not indicate a system error or an error in the
704 operation, but the result of an operation that failed properly.
706 GnuPG components, including Libgcrypt, use an extra library named
707 libgpg-error to provide a common error handling scheme. For more
708 information on libgpg-error, see the according manual.
711 * Error Values:: The error value and what it means.
712 * Error Sources:: A list of important error sources.
713 * Error Codes:: A list of important error codes.
714 * Error Strings:: How to get a descriptive string from a value.
719 @subsection Error Values
722 @cindex error sources
724 @deftp {Data type} {gcry_err_code_t}
725 The @code{gcry_err_code_t} type is an alias for the
726 @code{libgpg-error} type @code{gpg_err_code_t}. The error code
727 indicates the type of an error, or the reason why an operation failed.
729 A list of important error codes can be found in the next section.
732 @deftp {Data type} {gcry_err_source_t}
733 The @code{gcry_err_source_t} type is an alias for the
734 @code{libgpg-error} type @code{gpg_err_source_t}. The error source
735 has not a precisely defined meaning. Sometimes it is the place where
736 the error happened, sometimes it is the place where an error was
737 encoded into an error value. Usually the error source will give an
738 indication to where to look for the problem. This is not always true,
739 but it is attempted to achieve this goal.
741 A list of important error sources can be found in the next section.
744 @deftp {Data type} {gcry_error_t}
745 The @code{gcry_error_t} type is an alias for the @code{libgpg-error}
746 type @code{gpg_error_t}. An error value like this has always two
747 components, an error code and an error source. Both together form the
750 Thus, the error value can not be directly compared against an error
751 code, but the accessor functions described below must be used.
752 However, it is guaranteed that only 0 is used to indicate success
753 (@code{GPG_ERR_NO_ERROR}), and that in this case all other parts of
754 the error value are set to 0, too.
756 Note that in Libgcrypt, the error source is used purely for
757 diagnostic purposes. Only the error code should be checked to test
758 for a certain outcome of a function. The manual only documents the
759 error code part of an error value. The error source is left
760 unspecified and might be anything.
763 @deftypefun {gcry_err_code_t} gcry_err_code (@w{gcry_error_t @var{err}})
764 The static inline function @code{gcry_err_code} returns the
765 @code{gcry_err_code_t} component of the error value @var{err}. This
766 function must be used to extract the error code from an error value in
767 order to compare it with the @code{GPG_ERR_*} error code macros.
770 @deftypefun {gcry_err_source_t} gcry_err_source (@w{gcry_error_t @var{err}})
771 The static inline function @code{gcry_err_source} returns the
772 @code{gcry_err_source_t} component of the error value @var{err}. This
773 function must be used to extract the error source from an error value in
774 order to compare it with the @code{GPG_ERR_SOURCE_*} error source macros.
777 @deftypefun {gcry_error_t} gcry_err_make (@w{gcry_err_source_t @var{source}}, @w{gcry_err_code_t @var{code}})
778 The static inline function @code{gcry_err_make} returns the error
779 value consisting of the error source @var{source} and the error code
782 This function can be used in callback functions to construct an error
783 value to return it to the library.
786 @deftypefun {gcry_error_t} gcry_error (@w{gcry_err_code_t @var{code}})
787 The static inline function @code{gcry_error} returns the error value
788 consisting of the default error source and the error code @var{code}.
790 For @acronym{GCRY} applications, the default error source is
791 @code{GPG_ERR_SOURCE_USER_1}. You can define
792 @code{GCRY_ERR_SOURCE_DEFAULT} before including @file{gcrypt.h} to
795 This function can be used in callback functions to construct an error
796 value to return it to the library.
799 The @code{libgpg-error} library provides error codes for all system
800 error numbers it knows about. If @var{err} is an unknown error
801 number, the error code @code{GPG_ERR_UNKNOWN_ERRNO} is used. The
802 following functions can be used to construct error values from system
805 @deftypefun {gcry_error_t} gcry_err_make_from_errno (@w{gcry_err_source_t @var{source}}, @w{int @var{err}})
806 The function @code{gcry_err_make_from_errno} is like
807 @code{gcry_err_make}, but it takes a system error like @code{errno}
808 instead of a @code{gcry_err_code_t} error code.
811 @deftypefun {gcry_error_t} gcry_error_from_errno (@w{int @var{err}})
812 The function @code{gcry_error_from_errno} is like @code{gcry_error},
813 but it takes a system error like @code{errno} instead of a
814 @code{gcry_err_code_t} error code.
817 Sometimes you might want to map system error numbers to error codes
818 directly, or map an error code representing a system error back to the
819 system error number. The following functions can be used to do that.
821 @deftypefun {gcry_err_code_t} gcry_err_code_from_errno (@w{int @var{err}})
822 The function @code{gcry_err_code_from_errno} returns the error code
823 for the system error @var{err}. If @var{err} is not a known system
824 error, the function returns @code{GPG_ERR_UNKNOWN_ERRNO}.
827 @deftypefun {int} gcry_err_code_to_errno (@w{gcry_err_code_t @var{err}})
828 The function @code{gcry_err_code_to_errno} returns the system error
829 for the error code @var{err}. If @var{err} is not an error code
830 representing a system error, or if this system error is not defined on
831 this system, the function returns @code{0}.
836 @subsection Error Sources
837 @cindex error codes, list of
839 The library @code{libgpg-error} defines an error source for every
840 component of the GnuPG system. The error source part of an error
841 value is not well defined. As such it is mainly useful to improve the
842 diagnostic error message for the user.
844 If the error code part of an error value is @code{0}, the whole error
845 value will be @code{0}. In this case the error source part is of
846 course @code{GPG_ERR_SOURCE_UNKNOWN}.
848 The list of error sources that might occur in applications using
849 @acronym{Libgctypt} is:
852 @item GPG_ERR_SOURCE_UNKNOWN
853 The error source is not known. The value of this error source is
856 @item GPG_ERR_SOURCE_GPGME
857 The error source is @acronym{GPGME} itself.
859 @item GPG_ERR_SOURCE_GPG
860 The error source is GnuPG, which is the crypto engine used for the
863 @item GPG_ERR_SOURCE_GPGSM
864 The error source is GPGSM, which is the crypto engine used for the
867 @item GPG_ERR_SOURCE_GCRYPT
868 The error source is @code{libgcrypt}, which is used by crypto engines
869 to perform cryptographic operations.
871 @item GPG_ERR_SOURCE_GPGAGENT
872 The error source is @command{gpg-agent}, which is used by crypto
873 engines to perform operations with the secret key.
875 @item GPG_ERR_SOURCE_PINENTRY
876 The error source is @command{pinentry}, which is used by
877 @command{gpg-agent} to query the passphrase to unlock a secret key.
879 @item GPG_ERR_SOURCE_SCD
880 The error source is the SmartCard Daemon, which is used by
881 @command{gpg-agent} to delegate operations with the secret key to a
884 @item GPG_ERR_SOURCE_KEYBOX
885 The error source is @code{libkbx}, a library used by the crypto
886 engines to manage local keyrings.
888 @item GPG_ERR_SOURCE_USER_1
889 @item GPG_ERR_SOURCE_USER_2
890 @item GPG_ERR_SOURCE_USER_3
891 @item GPG_ERR_SOURCE_USER_4
892 These error sources are not used by any GnuPG component and can be
893 used by other software. For example, applications using
894 Libgcrypt can use them to mark error values coming from callback
895 handlers. Thus @code{GPG_ERR_SOURCE_USER_1} is the default for errors
896 created with @code{gcry_error} and @code{gcry_error_from_errno},
897 unless you define @code{GCRY_ERR_SOURCE_DEFAULT} before including
903 @subsection Error Codes
904 @cindex error codes, list of
906 The library @code{libgpg-error} defines many error values. The
907 following list includes the most important error codes.
911 This value indicates the end of a list, buffer or file.
913 @item GPG_ERR_NO_ERROR
914 This value indicates success. The value of this error code is
915 @code{0}. Also, it is guaranteed that an error value made from the
916 error code @code{0} will be @code{0} itself (as a whole). This means
917 that the error source information is lost for this error code,
918 however, as this error code indicates that no error occurred, this is
919 generally not a problem.
921 @item GPG_ERR_GENERAL
922 This value means that something went wrong, but either there is not
923 enough information about the problem to return a more useful error
924 value, or there is no separate error value for this type of problem.
927 This value means that an out-of-memory condition occurred.
930 System errors are mapped to GPG_ERR_EFOO where FOO is the symbol for
933 @item GPG_ERR_INV_VALUE
934 This value means that some user provided data was out of range.
936 @item GPG_ERR_UNUSABLE_PUBKEY
937 This value means that some recipients for a message were invalid.
939 @item GPG_ERR_UNUSABLE_SECKEY
940 This value means that some signers were invalid.
942 @item GPG_ERR_NO_DATA
943 This value means that data was expected where no data was found.
945 @item GPG_ERR_CONFLICT
946 This value means that a conflict of some sort occurred.
948 @item GPG_ERR_NOT_IMPLEMENTED
949 This value indicates that the specific function (or operation) is not
950 implemented. This error should never happen. It can only occur if
951 you use certain values or configuration options which do not work,
952 but for which we think that they should work at some later time.
954 @item GPG_ERR_DECRYPT_FAILED
955 This value indicates that a decryption operation was unsuccessful.
957 @item GPG_ERR_WRONG_KEY_USAGE
958 This value indicates that a key is not used appropriately.
960 @item GPG_ERR_NO_SECKEY
961 This value indicates that no secret key for the user ID is available.
963 @item GPG_ERR_UNSUPPORTED_ALGORITHM
964 This value means a verification failed because the cryptographic
965 algorithm is not supported by the crypto backend.
967 @item GPG_ERR_BAD_SIGNATURE
968 This value means a verification failed because the signature is bad.
970 @item GPG_ERR_NO_PUBKEY
971 This value means a verification failed because the public key is not
977 @item GPG_ERR_USER_16
978 These error codes are not used by any GnuPG component and can be
979 freely used by other software. Applications using Libgcrypt
980 might use them to mark specific errors returned by callback handlers
981 if no suitable error codes (including the system errors) for these
982 errors exist already.
987 @subsection Error Strings
988 @cindex error values, printing of
989 @cindex error codes, printing of
990 @cindex error sources, printing of
991 @cindex error strings
993 @deftypefun {const char *} gcry_strerror (@w{gcry_error_t @var{err}})
994 The function @code{gcry_strerror} returns a pointer to a statically
995 allocated string containing a description of the error code contained
996 in the error value @var{err}. This string can be used to output a
997 diagnostic message to the user.
1001 @deftypefun {const char *} gcry_strsource (@w{gcry_error_t @var{err}})
1002 The function @code{gcry_strerror} returns a pointer to a statically
1003 allocated string containing a description of the error source
1004 contained in the error value @var{err}. This string can be used to
1005 output a diagnostic message to the user.
1008 The following example illustrates the use of the functions described
1013 gcry_cipher_hd_t handle;
1014 gcry_error_t err = 0;
1016 err = gcry_cipher_open (&handle, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, 0);
1019 fprintf (stderr, "Failure: %s/%s\n",
1020 gcry_strsource (err),
1021 gcry_strerror (err));
1026 @c **********************************************************
1027 @c ******************* General ****************************
1028 @c **********************************************************
1029 @node Handler Functions
1030 @chapter Handler Functions
1032 Libgcrypt makes it possible to install so called `handler functions',
1033 which get called by Libgcrypt in case of certain events.
1036 * Progress handler:: Using a progress handler function.
1037 * Allocation handler:: Using special memory allocation functions.
1038 * Error handler:: Using error handler functions.
1039 * Logging handler:: Using a special logging function.
1042 @node Progress handler
1043 @section Progress handler
1045 It is often useful to retrieve some feedback while long running
1046 operations are performed.
1048 @deftp {Data type} gcry_handler_progress_t
1049 Progress handler functions have to be of the type
1050 @code{gcry_handler_progress_t}, which is defined as:
1052 @code{void (*gcry_handler_progress_t) (void *, const char *, int, int, int)}
1055 The following function may be used to register a handler function for
1058 @deftypefun void gcry_set_progress_handler (gcry_handler_progress_t @var{cb}, void *@var{cb_data})
1060 This function installs @var{cb} as the `Progress handler' function.
1061 @var{cb} must be defined as follows:
1065 my_progress_handler (void *@var{cb_data}, const char *@var{what},
1066 int @var{printchar}, int @var{current}, int @var{total})
1072 A description of the arguments of the progress handler function follows.
1076 The argument provided in the call to @code{gcry_set_progress_handler}.
1078 A string identifying the type of the progress output. The following
1079 values for @var{what} are defined:
1083 Not enough entropy is available. @var{total} holds the number of
1087 Values for @var{printchar}:
1092 Need to refresh the pool of prime numbers.
1094 Number of bits adjusted.
1096 Searching for a generator.
1098 Fermat test on 10 candidates failed.
1100 Restart with a new random value.
1102 Rabin Miller test passed.
1110 @node Allocation handler
1111 @section Allocation handler
1113 It is possible to make Libgcrypt use special memory
1114 allocation functions instead of the built-in ones.
1116 Memory allocation functions are of the following types:
1117 @deftp {Data type} gcry_handler_alloc_t
1118 This type is defined as: @code{void *(*gcry_handler_alloc_t) (size_t n)}.
1120 @deftp {Data type} gcry_handler_secure_check_t
1121 This type is defined as: @code{int *(*gcry_handler_secure_check_t) (const void *)}.
1123 @deftp {Data type} gcry_handler_realloc_t
1124 This type is defined as: @code{void *(*gcry_handler_realloc_t) (void *p, size_t n)}.
1126 @deftp {Data type} gcry_handler_free_t
1127 This type is defined as: @code{void *(*gcry_handler_free_t) (void *)}.
1130 Special memory allocation functions can be installed with the
1133 @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})
1134 Install the provided functions and use them instead of the built-in
1135 functions for doing memory allocation.
1139 @section Error handler
1141 The following functions may be used to register handler functions that
1142 are called by Libgcrypt in case certain error conditions
1145 @deftp {Data type} gcry_handler_no_mem_t
1146 This type is defined as: @code{void (*gcry_handler_no_mem_t) (void *, size_t, unsigned int)}
1148 @deftypefun void gcry_set_outofcore_handler (gcry_handler_no_mem_t @var{func_no_mem}, void *@var{cb_data})
1149 This function registers @var{func_no_mem} as `out-of-core handler',
1150 which means that it will be called in the case of not having enough
1154 @deftp {Data type} gcry_handler_error_t
1155 This type is defined as: @code{void (*gcry_handler_error_t) (void *, int, const char *)}
1158 @deftypefun void gcry_set_fatalerror_handler (gcry_handler_error_t @var{func_error}, void *@var{cb_data})
1159 This function registers @var{func_error} as `error handler',
1160 which means that it will be called in error conditions.
1163 @node Logging handler
1164 @section Logging handler
1166 @deftp {Data type} gcry_handler_log_t
1167 This type is defined as: @code{void (*gcry_handler_log_t) (void *, int, const char *, va_list)}
1170 @deftypefun void gcry_set_log_handler (gcry_handler_log_t @var{func_log}, void *@var{cb_data})
1171 This function registers @var{func_log} as `logging handler', which
1172 means that it will be called in case Libgcrypt wants to log
1176 @c **********************************************************
1177 @c ******************* Ciphers ****************************
1178 @c **********************************************************
1179 @c @include cipher-ref.texi
1180 @node Symmetric cryptography
1181 @chapter Symmetric cryptography
1183 The cipher functions are used for symmetrical cryptography,
1184 i.e. cryptography using a shared key. The programming model follows
1185 an open/process/close paradigm and is in that similar to other
1186 building blocks provided by Libgcrypt.
1189 * Available ciphers:: List of ciphers supported by the library.
1190 * Cipher modules:: How to work with cipher modules.
1191 * Available cipher modes:: List of cipher modes supported by the library.
1192 * Working with cipher handles:: How to perform operations related to cipher handles.
1193 * General cipher functions:: General cipher functions independent of cipher handles.
1196 @node Available ciphers
1197 @section Available ciphers
1200 @item GCRY_CIPHER_NONE
1201 This is not a real algorithm but used by some functions as error return.
1202 The value always evaluates to false.
1204 @item GCRY_CIPHER_IDEA
1205 This is the IDEA algorithm. The constant is provided but there is
1206 currently no implementation for it because the algorithm is patented.
1208 @item GCRY_CIPHER_3DES
1209 Triple-DES with 3 Keys as EDE. The key size of this algorithm is 168 but
1210 you have to pass 192 bits because the most significant bits of each byte
1213 @item GCRY_CIPHER_CAST5
1214 CAST128-5 block cipher algorithm. The key size is 128 bits.
1216 @item GCRY_CIPHER_BLOWFISH
1217 The blowfish algorithm. The current implementation allows only for a key
1220 @item GCRY_CIPHER_SAFER_SK128
1221 Reserved and not currently implemented.
1223 @item GCRY_CIPHER_DES_SK
1224 Reserved and not currently implemented.
1226 @item GCRY_CIPHER_AES
1227 @itemx GCRY_CIPHER_AES128
1228 @itemx GCRY_CIPHER_RIJNDAEL
1229 @itemx GCRY_CIPHER_RIJNDAEL128
1230 AES (Rijndael) with a 128 bit key.
1232 @item GCRY_CIPHER_AES192
1233 @itemx GCRY_CIPHER_RIJNDAEL192
1234 AES (Rijndael) with a 192 bit key.
1236 @item GCRY_CIPHER_AES256
1237 @itemx GCRY_CIPHER_RIJNDAEL256
1238 AES (Rijndael) with a 256 bit key.
1240 @item GCRY_CIPHER_TWOFISH
1241 The Twofish algorithm with a 256 bit key.
1243 @item GCRY_CIPHER_TWOFISH128
1244 The Twofish algorithm with a 128 bit key.
1246 @item GCRY_CIPHER_ARCFOUR
1247 An algorithm which is 100% compatible with RSA Inc.'s RC4 algorithm.
1248 Note that this is a stream cipher and must be used very carefully to
1249 avoid a couple of weaknesses.
1251 @item GCRY_CIPHER_DES
1252 Standard DES with a 56 bit key. You need to pass 64 bit but the high
1253 bits of each byte are ignored. Note, that this is a weak algorithm
1254 which can be broken in reasonable time using a brute force approach.
1256 @item GCRY_CIPHER_SERPENT128
1257 @itemx GCRY_CIPHER_SERPENT192
1258 @itemx GCRY_CIPHER_SERPENT256
1259 The Serpent cipher from the AES contest.
1261 @item GCRY_CIPHER_RFC2268_40
1262 @itemx GCRY_CIPHER_RFC2268_128
1263 Ron's Cipher 2 in the 40 and 128 bit variants. Note, that we currently
1264 only support the 40 bit variant. The identifier for 128 is reserved for
1267 @item GCRY_CIPHER_SEED
1268 A 128 bit cipher as described by RFC4269.
1270 @item GCRY_CIPHER_CAMELLIA128
1271 @itemx GCRY_CIPHER_CAMELLIA192
1272 @itemx GCRY_CIPHER_CAMELLIA256
1273 The Camellia cipher by NTT. See
1274 @uref{http://info.isl.ntt.co.jp/@/crypt/@/eng/@/camellia/@/specifications.html}.
1278 @node Cipher modules
1279 @section Cipher modules
1281 Libgcrypt makes it possible to load additional `cipher modules'; these
1282 ciphers can be used just like the cipher algorithms that are built
1283 into the library directly. For an introduction into extension
1284 modules, see @xref{Modules}.
1286 @deftp {Data type} gcry_cipher_spec_t
1287 This is the `module specification structure' needed for registering
1288 cipher modules, which has to be filled in by the user before it can be
1289 used to register a module. It contains the following members:
1292 @item const char *name
1293 The primary name of the algorithm.
1294 @item const char **aliases
1295 A list of strings that are `aliases' for the algorithm. The list must
1296 be terminated with a NULL element.
1297 @item gcry_cipher_oid_spec_t *oids
1298 A list of OIDs that are to be associated with the algorithm. The
1299 list's last element must have it's `oid' member set to NULL. See
1300 below for an explanation of this type.
1301 @item size_t blocksize
1302 The block size of the algorithm, in bytes.
1304 The length of the key, in bits.
1305 @item size_t contextsize
1306 The size of the algorithm-specific `context', that should be allocated
1308 @item gcry_cipher_setkey_t setkey
1309 The function responsible for initializing a handle with a provided
1310 key. See below for a description of this type.
1311 @item gcry_cipher_encrypt_t encrypt
1312 The function responsible for encrypting a single block. See below for
1313 a description of this type.
1314 @item gcry_cipher_decrypt_t decrypt
1315 The function responsible for decrypting a single block. See below for
1316 a description of this type.
1317 @item gcry_cipher_stencrypt_t stencrypt
1318 Like `encrypt', for stream ciphers. See below for a description of
1320 @item gcry_cipher_stdecrypt_t stdecrypt
1321 Like `decrypt', for stream ciphers. See below for a description of
1326 @deftp {Data type} gcry_cipher_oid_spec_t
1327 This type is used for associating a user-provided algorithm
1328 implementation with certain OIDs. It contains the following members:
1330 @item const char *oid
1331 Textual representation of the OID.
1333 Cipher mode for which this OID is valid.
1337 @deftp {Data type} gcry_cipher_setkey_t
1338 Type for the `setkey' function, defined as: gcry_err_code_t
1339 (*gcry_cipher_setkey_t) (void *c, const unsigned char *key, unsigned
1343 @deftp {Data type} gcry_cipher_encrypt_t
1344 Type for the `encrypt' function, defined as: gcry_err_code_t
1345 (*gcry_cipher_encrypt_t) (void *c, const unsigned char *outbuf, const
1346 unsigned char *inbuf)
1349 @deftp {Data type} gcry_cipher_decrypt_t
1350 Type for the `decrypt' function, defined as: gcry_err_code_t
1351 (*gcry_cipher_decrypt_t) (void *c, const unsigned char *outbuf, const
1352 unsigned char *inbuf)
1355 @deftp {Data type} gcry_cipher_stencrypt_t
1356 Type for the `stencrypt' function, defined as: gcry_err_code_t
1357 (*gcry_cipher_stencrypt_t) (void *c, const unsigned char *outbuf, const
1358 unsigned char *, unsigned int n)
1361 @deftp {Data type} gcry_cipher_stdecrypt_t
1362 Type for the `stdecrypt' function, defined as: gcry_err_code_t
1363 (*gcry_cipher_stdecrypt_t) (void *c, const unsigned char *outbuf, const
1364 unsigned char *, unsigned int n)
1367 @deftypefun gcry_error_t gcry_cipher_register (gcry_cipher_spec_t *@var{cipher}, unsigned int *algorithm_id, gcry_module_t *@var{module})
1369 Register a new cipher module whose specification can be found in
1370 @var{cipher}. On success, a new algorithm ID is stored in
1371 @var{algorithm_id} and a pointer representing this module is stored
1375 @deftypefun void gcry_cipher_unregister (gcry_module_t @var{module})
1376 Unregister the cipher identified by @var{module}, which must have been
1377 registered with gcry_cipher_register.
1380 @deftypefun gcry_error_t gcry_cipher_list (int *@var{list}, int *@var{list_length})
1381 Get a list consisting of the IDs of the loaded cipher modules. If
1382 @var{list} is zero, write the number of loaded cipher modules to
1383 @var{list_length} and return. If @var{list} is non-zero, the first
1384 *@var{list_length} algorithm IDs are stored in @var{list}, which must
1385 be of according size. In case there are less cipher modules than
1386 *@var{list_length}, *@var{list_length} is updated to the correct
1390 @node Available cipher modes
1391 @section Available cipher modes
1394 @item GCRY_CIPHER_MODE_NONE
1395 No mode specified, may be set later using other functions. The value
1396 of this constant is always 0.
1398 @item GCRY_CIPHER_MODE_ECB
1399 Electronic Codebook mode.
1401 @item GCRY_CIPHER_MODE_CFB
1402 Cipher Feedback mode.
1404 @item GCRY_CIPHER_MODE_CBC
1405 Cipher Block Chaining mode.
1407 @item GCRY_CIPHER_MODE_STREAM
1408 Stream mode, only to be used with stream cipher algorithms.
1410 @item GCRY_CIPHER_MODE_OFB
1411 Output Feedback mode.
1413 @item GCRY_CIPHER_MODE_CTR
1418 @node Working with cipher handles
1419 @section Working with cipher handles
1421 To use a cipher algorithm, you must first allocate an according
1422 handle. This is to be done using the open function:
1424 @deftypefun gcry_error_t gcry_cipher_open (gcry_cipher_hd_t *@var{hd}, int @var{algo}, int @var{mode}, unsigned int @var{flags})
1426 This function creates the context handle required for most of the
1427 other cipher functions and returns a handle to it in `hd'. In case of
1428 an error, an according error code is returned.
1430 The ID of algorithm to use must be specified via @var{algo}. See
1431 @xref{Available ciphers}, for a list of supported ciphers and the
1432 according constants.
1434 Besides using the constants directly, the function
1435 @code{gcry_cipher_map_name} may be used to convert the textual name of
1436 an algorithm into the according numeric ID.
1438 The cipher mode to use must be specified via @var{mode}. See
1439 @xref{Available cipher modes}, for a list of supported cipher modes
1440 and the according constants. Note that some modes are incompatible
1441 with some algorithms - in particular, stream mode
1442 (GCRY_CIPHER_MODE_STREAM) only works with stream ciphers. Any block
1443 cipher mode (GCRY_CIPHER_MODE_ECB, GCRY_CIPHER_MODE_CBC,
1444 GCRY_CIPHER_MODE_CFB, GCRY_CIPHER_MODE_OFB or GCRY_CIPHER_MODE_CTR)
1445 will work with any block cipher algorithm.
1447 The third argument @var{flags} can either be passed as @code{0} or as
1448 the bit-wise OR of the following constants.
1451 @item GCRY_CIPHER_SECURE
1452 Make sure that all operations are allocated in secure memory. This is
1453 useful when the key material is highly confidential.
1454 @item GCRY_CIPHER_ENABLE_SYNC
1455 This flag enables the CFB sync mode, which is a special feature of
1456 Libgcrypt's CFB mode implementation to allow for OpenPGP's CFB variant.
1457 See @code{gcry_cipher_sync}.
1458 @item GCRY_CIPHER_CBC_CTS
1459 Enable cipher text stealing (CTS) for the CBC mode. Cannot be used
1460 simultaneous as GCRY_CIPHER_CBC_MAC. CTS mode makes it possible to
1461 transform data of almost arbitrary size (only limitation is that it
1462 must be greater than the algorithm's block size).
1463 @item GCRY_CIPHER_CBC_MAC
1464 Compute CBC-MAC keyed checksums. This is the same as CBC mode, but
1465 only output the last block. Cannot be used simultaneous as
1466 GCRY_CIPHER_CBC_CTS.
1470 Use the following function to release an existing handle:
1472 @deftypefun void gcry_cipher_close (gcry_cipher_hd_t @var{h})
1474 This function releases the context created by @code{gcry_cipher_open}.
1477 In order to use a handle for performing cryptographic operations, a
1478 `key' has to be set first:
1480 @deftypefun gcry_error_t gcry_cipher_setkey (gcry_cipher_hd_t @var{h}, void *@var{k}, size_t @var{l})
1482 Set the key @var{k} used for encryption or decryption in the context
1483 denoted by the handle @var{h}. The length @var{l} of the key @var{k}
1484 must match the required length of the algorithm set for this context or
1485 be in the allowed range for algorithms with variable key size. The
1486 function checks this and returns an error if there is a problem. A
1487 caller should always check for an error.
1489 Note that this is currently implemented as a macro but may be changed
1490 to a function in the future.
1493 Most crypto modes requires an initialization vector (IV), which
1494 usually is a non-secret random string acting as a kind of salt value.
1495 The CTR mode requires a counter, which is also similar to a salt
1496 value. To set the IV or CTR, use these functions:
1498 @deftypefun gcry_error_t gcry_cipher_setiv (gcry_cipher_hd_t @var{h}, void *@var{k}, size_t @var{l})
1500 Set the initialization vector used for encryption or decryption. The
1501 vector is passed as the buffer @var{K} of length @var{l} and copied to
1502 internal data structures. The function checks that the IV matches the
1503 requirement of the selected algorithm and mode. Note that this is
1504 implemented as a macro.
1507 @deftypefun gcry_error_t gcry_cipher_setctr (gcry_cipher_hd_t @var{h}, void *@var{c}, size_t @var{l})
1509 Set the counter vector used for encryption or decryption. The counter
1510 is passed as the buffer @var{c} of length @var{l} and copied to
1511 internal data structures. The function checks that the counter
1512 matches the requirement of the selected algorithm (i.e., it must be
1513 the same size as the block size). Note that this is implemented as a
1517 @deftypefun gcry_error_t gcry_cipher_reset (gcry_cipher_hd_t @var{h})
1519 Set the given handle's context back to the state it had after the last
1520 call to gcry_cipher_setkey and clear the initialization vector.
1522 Note that gcry_cipher_reset is implemented as a macro.
1525 The actual encryption and decryption is done by using one of the
1526 following functions. They may be used as often as required to process
1529 @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})
1531 @code{gcry_cipher_encrypt} is used to encrypt the data. This function
1532 can either work in place or with two buffers. It uses the cipher
1533 context already setup and described by the handle @var{h}. There are 2
1534 ways to use the function: If @var{in} is passed as @code{NULL} and
1535 @var{inlen} is @code{0}, in-place encryption of the data in @var{out} or
1536 length @var{outsize} takes place. With @var{in} being not @code{NULL},
1537 @var{inlen} bytes are encrypted to the buffer @var{out} which must have
1538 at least a size of @var{inlen}. @var{outsize} must be set to the
1539 allocated size of @var{out}, so that the function can check that there
1540 is sufficient space. Note that overlapping buffers are not allowed.
1542 Depending on the selected algorithms and encryption mode, the length of
1543 the buffers must be a multiple of the block size.
1545 The function returns @code{0} on success or an error code.
1549 @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})
1551 @code{gcry_cipher_decrypt} is used to decrypt the data. This function
1552 can either work in place or with two buffers. It uses the cipher
1553 context already setup and described by the handle @var{h}. There are 2
1554 ways to use the function: If @var{in} is passed as @code{NULL} and
1555 @var{inlen} is @code{0}, in-place decryption of the data in @var{out} or
1556 length @var{outsize} takes place. With @var{in} being not @code{NULL},
1557 @var{inlen} bytes are decrypted to the buffer @var{out} which must have
1558 at least a size of @var{inlen}. @var{outsize} must be set to the
1559 allocated size of @var{out}, so that the function can check that there
1560 is sufficient space. Note that overlapping buffers are not allowed.
1562 Depending on the selected algorithms and encryption mode, the length of
1563 the buffers must be a multiple of the block size.
1565 The function returns @code{0} on success or an error code.
1569 OpenPGP (as defined in RFC-2440) requires a special sync operation in
1570 some places. The following function is used for this:
1572 @deftypefun gcry_error_t gcry_cipher_sync (gcry_cipher_hd_t @var{h})
1574 Perform the OpenPGP sync operation on context @var{h}. Note that this
1575 is a no-op unless the context was created with the flag
1576 @code{GCRY_CIPHER_ENABLE_SYNC}
1579 Some of the described functions are implemented as macros utilizing a
1580 catch-all control function. This control function is rarely used
1581 directly but there is nothing which would inhibit it:
1583 @deftypefun gcry_error_t gcry_cipher_ctl (gcry_cipher_hd_t @var{h}, int @var{cmd}, void *@var{buffer}, size_t @var{buflen})
1585 @code{gcry_cipher_ctl} controls various aspects of the cipher module and
1586 specific cipher contexts. Usually some more specialized functions or
1587 macros are used for this purpose. The semantics of the function and its
1588 parameters depends on the the command @var{cmd} and the passed context
1589 handle @var{h}. Please see the comments in the source code
1590 (@code{src/global.c}) for details.
1593 @deftypefun gcry_error_t gcry_cipher_info (gcry_cipher_hd_t @var{h}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes})
1595 @code{gcry_cipher_info} is used to retrieve various
1596 information about a cipher context or the cipher module in general.
1598 Currently no information is available.
1601 @node General cipher functions
1602 @section General cipher functions
1604 To work with the algorithms, several functions are available to map
1605 algorithm names to the internal identifiers, as well as ways to
1606 retrieve information about an algorithm or the current cipher context.
1608 @deftypefun gcry_error_t gcry_cipher_algo_info (int @var{algo}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes})
1610 This function is used to retrieve information on a specific algorithm.
1611 You pass the cipher algorithm ID as @var{algo} and the type of
1612 information requested as @var{what}. The result is either returned as
1613 the return code of the function or copied to the provided @var{buffer}
1614 whose allocated length must be available in an integer variable with the
1615 address passed in @var{nbytes}. This variable will also receive the
1616 actual used length of the buffer.
1618 Here is a list of supported codes for @var{what}:
1620 @c begin constants for gcry_cipher_algo_info
1622 @item GCRYCTL_GET_KEYLEN:
1623 Return the length of the key. If the algorithm supports multiple key
1624 lengths, the maximum supported value is returned. The length is
1625 returned as number of octets (bytes) and not as number of bits in
1626 @var{nbytes}; @var{buffer} must be zero.
1628 @item GCRYCTL_GET_BLKLEN:
1629 Return the block length of the algorithm. The length is returned as a
1630 number of octets in @var{nbytes}; @var{buffer} must be zero.
1632 @item GCRYCTL_TEST_ALGO:
1633 Returns @code{0} when the specified algorithm is available for use.
1634 @var{buffer} and @var{nbytes} must be zero.
1637 @c end constants for gcry_cipher_algo_info
1640 @c end gcry_cipher_algo_info
1642 @deftypefun const char *gcry_cipher_algo_name (int @var{algo})
1644 @code{gcry_cipher_algo_name} returns a string with the name of the
1645 cipher algorithm @var{algo}. If the algorithm is not known or another
1646 error occurred, the string @code{"?"} is returned. This function should
1647 not be used to test for the availability of an algorithm.
1650 @deftypefun int gcry_cipher_map_name (const char *@var{name})
1652 @code{gcry_cipher_map_name} returns the algorithm identifier for the
1653 cipher algorithm described by the string @var{name}. If this algorithm
1654 is not available @code{0} is returned.
1657 @deftypefun int gcry_cipher_mode_from_oid (const char *@var{string})
1659 Return the cipher mode associated with an @acronym{ASN.1} object
1660 identifier. The object identifier is expected to be in the
1661 @acronym{IETF}-style dotted decimal notation. The function returns
1662 @code{0} for an unknown object identifier or when no mode is associated
1667 @c **********************************************************
1668 @c ******************* Hash Functions *********************
1669 @c **********************************************************
1673 Libgcrypt provides an easy and consistent to use interface
1674 for hashing. Hashing is buffered and several hash algorithms can be
1675 updated at once. It is possible to calculate a MAC using the same
1676 routines. The programming model follows an open/process/close
1677 paradigm and is in that similar to other building blocks provided by
1680 For convenience reasons, a few cyclic redundancy check value operations
1684 * Available hash algorithms:: List of hash algorithms supported by the library.
1685 * Hash algorithm modules:: How to work with hash algorithm modules.
1686 * Working with hash algorithms:: List of functions related to hashing.
1689 @node Available hash algorithms
1690 @section Available hash algorithms
1692 @c begin table of hash algorithms
1695 This is not a real algorithm but used by some functions as an error
1696 return value. This constant is guaranteed to have the value @code{0}.
1699 This is the SHA-1 algorithm which yields a message digest of 20 bytes.
1701 @item GCRY_MD_RMD160
1702 This is the 160 bit version of the RIPE message digest (RIPE-MD-160).
1703 Like SHA-1 it also yields a digest of 20 bytes.
1706 This is the well known MD5 algorithm, which yields a message digest of
1710 This is the MD4 algorithm, which yields a message digest of 16 bytes.
1713 This is an reserved identifier for MD-2; there is no implementation yet.
1716 This is the TIGER/192 algorithm which yields a message digest of 24 bytes.
1719 This is an reserved for the HAVAL algorithm with 5 passes and 160
1720 bit. It yields a message digest of 20 bytes. Note that there is no
1721 implementation yet available.
1723 @item GCRY_MD_SHA224
1724 This is the SHA-224 algorithm which yields a message digest of 28 bytes.
1725 See Change Notice 1 for FIPS 180-2 for the specification.
1727 @item GCRY_MD_SHA256
1728 This is the SHA-256 algorithm which yields a message digest of 32 bytes.
1729 See FIPS 180-2 for the specification.
1731 @item GCRY_MD_SHA384
1732 This is the SHA-384 algorithm which yields a message digest of 48 bytes.
1733 See FIPS 180-2 for the specification.
1735 @item GCRY_MD_SHA512
1736 This is the SHA-384 algorithm which yields a message digest of 64 bytes.
1737 See FIPS 180-2 for the specification.
1740 This is the ISO 3309 and ITU-T V.42 cyclic redundancy check. It
1741 yields an output of 4 bytes.
1743 @item GCRY_MD_CRC32_RFC1510
1744 This is the above cyclic redundancy check function, as modified by RFC
1745 1510. It yields an output of 4 bytes.
1747 @item GCRY_MD_CRC24_RFC2440
1748 This is the OpenPGP cyclic redundancy check function. It yields an
1751 @item GCRY_MD_WHIRLPOOL
1752 This is the Whirlpool algorithm which yields a message digest of 64
1756 @c end table of hash algorithms
1758 @node Hash algorithm modules
1759 @section Hash algorithm modules
1761 Libgcrypt makes it possible to load additional `message
1762 digest modules'; these digests can be used just like the message digest
1763 algorithms that are built into the library directly. For an
1764 introduction into extension modules, see @xref{Modules}.
1766 @deftp {Data type} gcry_md_spec_t
1767 This is the `module specification structure' needed for registering
1768 message digest modules, which has to be filled in by the user before
1769 it can be used to register a module. It contains the following
1773 @item const char *name
1774 The primary name of this algorithm.
1775 @item unsigned char *asnoid
1776 Array of bytes that form the ASN OID.
1778 Length of bytes in `asnoid'.
1779 @item gcry_md_oid_spec_t *oids
1780 A list of OIDs that are to be associated with the algorithm. The
1781 list's last element must have it's `oid' member set to NULL. See
1782 below for an explanation of this type. See below for an explanation
1785 Length of the message digest algorithm. See below for an explanation
1787 @item gcry_md_init_t init
1788 The function responsible for initializing a handle. See below for an
1789 explanation of this type.
1790 @item gcry_md_write_t write
1791 The function responsible for writing data into a message digest
1792 context. See below for an explanation of this type.
1793 @item gcry_md_final_t final
1794 The function responsible for `finalizing' a message digest context.
1795 See below for an explanation of this type.
1796 @item gcry_md_read_t read
1797 The function responsible for reading out a message digest result. See
1798 below for an explanation of this type.
1799 @item size_t contextsize
1800 The size of the algorithm-specific `context', that should be
1801 allocated for each handle.
1805 @deftp {Data type} gcry_md_oid_spec_t
1806 This type is used for associating a user-provided algorithm
1807 implementation with certain OIDs. It contains the following members:
1810 @item const char *oidstring
1811 Textual representation of the OID.
1815 @deftp {Data type} gcry_md_init_t
1816 Type for the `init' function, defined as: void (*gcry_md_init_t) (void
1820 @deftp {Data type} gcry_md_write_t
1821 Type for the `write' function, defined as: void (*gcry_md_write_t)
1822 (void *c, unsigned char *buf, size_t nbytes)
1825 @deftp {Data type} gcry_md_final_t
1826 Type for the `final' function, defined as: void (*gcry_md_final_t)
1830 @deftp {Data type} gcry_md_read_t
1831 Type for the `read' function, defined as: unsigned char
1832 *(*gcry_md_read_t) (void *c)
1835 @deftypefun gcry_error_t gcry_md_register (gcry_md_spec_t *@var{digest}, unsigned int *algorithm_id, gcry_module_t *@var{module})
1837 Register a new digest module whose specification can be found in
1838 @var{digest}. On success, a new algorithm ID is stored in
1839 @var{algorithm_id} and a pointer representing this module is stored
1843 @deftypefun void gcry_md_unregister (gcry_module_t @var{module})
1844 Unregister the digest identified by @var{module}, which must have been
1845 registered with gcry_md_register.
1848 @deftypefun gcry_error_t gcry_md_list (int *@var{list}, int *@var{list_length})
1849 Get a list consisting of the IDs of the loaded message digest modules.
1850 If @var{list} is zero, write the number of loaded message digest
1851 modules to @var{list_length} and return. If @var{list} is non-zero,
1852 the first *@var{list_length} algorithm IDs are stored in @var{list},
1853 which must be of according size. In case there are less message
1854 digests modules than *@var{list_length}, *@var{list_length} is updated
1855 to the correct number.
1858 @node Working with hash algorithms
1859 @section Working with hash algorithms
1861 To use most of these function it is necessary to create a context;
1864 @deftypefun gcry_error_t gcry_md_open (gcry_md_hd_t *@var{hd}, int @var{algo}, unsigned int @var{flags})
1866 Create a message digest object for algorithm @var{algo}. @var{flags}
1867 may be given as an bitwise OR of constants described below. @var{algo}
1868 may be given as @code{0} if the algorithms to use are later set using
1869 @code{gcry_md_enable}. @var{hd} is guaranteed to either receive a valid
1872 For a list of supported algorithms, see @xref{Available hash
1875 The flags allowed for @var{mode} are:
1877 @c begin table of hash flags
1879 @item GCRY_MD_FLAG_SECURE
1880 Allocate all buffers and the resulting digest in "secure memory". Use
1881 this is the hashed data is highly confidential.
1883 @item GCRY_MD_FLAG_HMAC
1884 Turn the algorithm into a HMAC message authentication algorithm. This
1885 only works if just one algorithm is enabled for the handle. Note that the function
1886 @code{gcry_md_setkey} must be used to set the MAC key. If you want CBC
1887 message authentication codes based on a cipher, see @xref{Working with
1891 @c begin table of hash flags
1893 You may use the function @code{gcry_md_is_enabled} to later check
1894 whether an algorithm has been enabled.
1897 @c end function gcry_md_open
1899 If you want to calculate several hash algorithms at the same time, you
1900 have to use the following function right after the @code{gcry_md_open}:
1902 @deftypefun gcry_error_t gcry_md_enable (gcry_md_hd_t @var{h}, int @var{algo})
1904 Add the message digest algorithm @var{algo} to the digest object
1905 described by handle @var{h}. Duplicated enabling of algorithms is
1906 detected and ignored.
1909 If the flag @code{GCRY_MD_FLAG_HMAC} was used, the key for the MAC must
1910 be set using the function:
1912 @deftypefun gcry_error_t gcry_md_setkey (gcry_md_hd_t @var{h}, const void *@var{key}, size_t @var{keylen})
1914 For use with the HMAC feature, set the MAC key to the value of @var{key}
1915 of length @var{keylen}.
1919 After you are done with the hash calculation, you should release the
1922 @deftypefun void gcry_md_close (gcry_md_hd_t @var{h})
1924 Release all resources of hash context @var{h}. @var{h} should not be
1925 used after a call to this function. A @code{NULL} passed as @var{h} is
1930 Often you have to do several hash operations using the same algorithm.
1931 To avoid the overhead of creating and releasing context, a reset function
1934 @deftypefun void gcry_md_reset (gcry_md_hd_t @var{h})
1936 Reset the current context to its initial state. This is effectively
1937 identical to a close followed by an open and enabling all currently
1942 Often it is necessary to start hashing some data and then continue to
1943 hash different data. To avoid hashing the same data several times (which
1944 might not even be possible if the data is received from a pipe), a
1945 snapshot of the current hash context can be taken and turned into a new
1948 @deftypefun gcry_error_t gcry_md_copy (gcry_md_hd_t *@var{handle_dst}, gcry_md_hd_t @var{handle_src})
1950 Create a new digest object as an exact copy of the object described by
1951 handle @var{handle_src} and store it in @var{handle_dst}. The context
1952 is not reset and you can continue to hash data using this context and
1953 independently using the original context.
1957 Now that we have prepared everything to calculate hashes, it is time to
1958 see how it is actually done. There are two ways for this, one to
1959 update the hash with a block of memory and one macro to update the hash
1960 by just one character. Both methods can be used on the same hash context.
1962 @deftypefun void gcry_md_write (gcry_md_hd_t @var{h}, const void *@var{buffer}, size_t @var{length})
1964 Pass @var{length} bytes of the data in @var{buffer} to the digest object
1965 with handle @var{h} to update the digest values. This
1966 function should be used for large blocks of data.
1969 @deftypefun void gcry_md_putc (gcry_md_hd_t @var{h}, int @var{c})
1971 Pass the byte in @var{c} to the digest object with handle @var{h} to
1972 update the digest value. This is an efficient function, implemented as
1973 a macro to buffer the data before an actual update.
1976 The semantics of the hash functions do not provide for reading out intermediate
1977 message digests because the calculation must be finalized first. This
1978 finalization may for example include the number of bytes hashed in the
1979 message digest or some padding.
1981 @deftypefun void gcry_md_final (gcry_md_hd_t @var{h})
1983 Finalize the message digest calculation. This is not really needed
1984 because @code{gcry_md_read} does this implicitly. After this has been
1985 done no further updates (by means of @code{gcry_md_write} or
1986 @code{gcry_md_putc} are allowed. Only the first call to this function
1987 has an effect. It is implemented as a macro.
1990 The way to read out the calculated message digest is by using the
1993 @deftypefun unsigned char *gcry_md_read (gcry_md_hd_t @var{h}, int @var{algo})
1995 @code{gcry_md_read} returns the message digest after finalizing the
1996 calculation. This function may be used as often as required but it will
1997 always return the same value for one handle. The returned message digest
1998 is allocated within the message context and therefore valid until the
1999 handle is released or reseted (using @code{gcry_md_close} or
2000 @code{gcry_md_reset}. @var{algo} may be given as 0 to return the only
2001 enabled message digest or it may specify one of the enabled algorithms.
2002 The function does return @code{NULL} if the requested algorithm has not
2006 Because it is often necessary to get the message digest of one block of
2007 memory, a fast convenience function is available for this task:
2009 @deftypefun void gcry_md_hash_buffer (int @var{algo}, void *@var{digest}, const void *@var{buffer}, size_t @var{length});
2011 @code{gcry_md_hash_buffer} is a shortcut function to calculate a message
2012 digest of a buffer. This function does not require a context and
2013 immediately returns the message digest of the @var{length} bytes at
2014 @var{buffer}. @var{digest} must be allocated by the caller, large
2015 enough to hold the message digest yielded by the the specified algorithm
2016 @var{algo}. This required size may be obtained by using the function
2017 @code{gcry_md_get_algo_dlen}.
2019 Note that this function will abort the process if an unavailable
2023 @c ***********************************
2024 @c ***** MD info functions ***********
2025 @c ***********************************
2027 Hash algorithms are identified by internal algorithm numbers (see
2028 @code{gcry_md_open} for a list). However, in most applications they are
2029 used by names, so two functions are available to map between string
2030 representations and hash algorithm identifiers.
2032 @deftypefun const char *gcry_md_algo_name (int @var{algo})
2034 Map the digest algorithm id @var{algo} to a string representation of the
2035 algorithm name. For unknown algorithms this function returns the
2036 string @code{"?"}. This function should not be used to test for the
2037 availability of an algorithm.
2040 @deftypefun int gcry_md_map_name (const char *@var{name})
2042 Map the algorithm with @var{name} to a digest algorithm identifier.
2043 Returns 0 if the algorithm name is not known. Names representing
2044 @acronym{ASN.1} object identifiers are recognized if the @acronym{IETF}
2045 dotted format is used and the OID is prefixed with either "@code{oid.}"
2046 or "@code{OID.}". For a list of supported OIDs, see the source code at
2047 @file{cipher/md.c}. This function should not be used to test for the
2048 availability of an algorithm.
2051 @deftypefun gcry_error_t gcry_md_get_asnoid (int @var{algo}, void *@var{buffer}, size_t *@var{length})
2053 Return an DER encoded ASN.1 OID for the algorithm @var{algo} in the
2054 user allocated @var{buffer}. @var{length} must point to variable with
2055 the available size of @var{buffer} and receives after return the
2056 actual size of the returned OID. The returned error code may be
2057 @code{GPG_ERR_TOO_SHORT} if the provided buffer is to short to receive
2058 the OID; it is possible to call the function with @code{NULL} for
2059 @var{buffer} to have it only return the required size. The function
2060 returns 0 on success.
2065 To test whether an algorithm is actually available for use, the
2066 following macro should be used:
2068 @deftypefun gcry_error_t gcry_md_test_algo (int @var{algo})
2070 The macro returns 0 if the algorithm @var{algo} is available for use.
2073 If the length of a message digest is not known, it can be retrieved
2074 using the following function:
2076 @deftypefun unsigned int gcry_md_get_algo_dlen (int @var{algo})
2078 Retrieve the length in bytes of the digest yielded by algorithm
2079 @var{algo}. This is often used prior to @code{gcry_md_read} to allocate
2080 sufficient memory for the digest.
2084 In some situations it might be hard to remember the algorithm used for
2085 the ongoing hashing. The following function might be used to get that
2088 @deftypefun int gcry_md_get_algo (gcry_md_hd_t @var{h})
2090 Retrieve the algorithm used with the handle @var{h}. Note that this
2091 does not work reliable if more than one algorithm is enabled in @var{h}.
2094 The following macro might also be useful:
2096 @deftypefun int gcry_md_is_secure (gcry_md_hd_t @var{h})
2098 This function returns true when the digest object @var{h} is allocated
2099 in "secure memory"; i.e. @var{h} was created with the
2100 @code{GCRY_MD_FLAG_SECURE}.
2103 @deftypefun int gcry_md_is_enabled (gcry_md_hd_t @var{h}, int @var{algo})
2105 This function returns true when the algorithm @var{algo} has been
2106 enabled for the digest object @var{h}.
2111 Tracking bugs related to hashing is often a cumbersome task which
2112 requires to add a lot of printf statements into the code.
2113 Libgcrypt provides an easy way to avoid this. The actual data
2114 hashed can be written to files on request.
2116 @deftypefun void gcry_md_debug (gcry_md_hd_t @var{h}, const char *@var{suffix})
2118 Enable debugging for the digest object with handle @var{h}. This
2119 creates create files named @file{dbgmd-<n>.<string>} while doing the
2120 actual hashing. @var{suffix} is the string part in the filename. The
2121 number is a counter incremented for each new hashing. The data in the
2122 file is the raw data as passed to @code{gcry_md_write} or
2123 @code{gcry_md_putc}. If @code{NULL} is used for @var{suffix}, the
2124 debugging is stopped and the file closed. This is only rarely required
2125 because @code{gcry_md_close} implicitly stops debugging.
2129 The following two deprecated macros are used for debugging by old code.
2130 They shopuld be replaced by @code{gcry_md_debug}.
2132 @deftypefun void gcry_md_start_debug (gcry_md_hd_t @var{h}, const char *@var{suffix})
2134 Enable debugging for the digest object with handle @var{h}. This
2135 creates create files named @file{dbgmd-<n>.<string>} while doing the
2136 actual hashing. @var{suffix} is the string part in the filename. The
2137 number is a counter incremented for each new hashing. The data in the
2138 file is the raw data as passed to @code{gcry_md_write} or
2139 @code{gcry_md_putc}.
2143 @deftypefun void gcry_md_stop_debug (gcry_md_hd_t @var{h}, int @var{reserved})
2145 Stop debugging on handle @var{h}. @var{reserved} should be specified as
2146 0. This function is usually not required because @code{gcry_md_close}
2147 does implicitly stop debugging.
2151 @c **********************************************************
2152 @c ******************* Public Key *************************
2153 @c **********************************************************
2154 @node Public Key cryptography (I)
2155 @chapter Public Key cryptography (I)
2157 Public key cryptography, also known as asymmetric cryptography, is an
2158 easy way for key management and to provide digital signatures.
2159 Libgcrypt provides two completely different interfaces to
2160 public key cryptography, this chapter explains the one based on
2164 * Available algorithms:: Algorithms supported by the library.
2165 * Used S-expressions:: Introduction into the used S-expression.
2166 * Public key modules:: How to work with public key modules.
2167 * Cryptographic Functions:: Functions for performing the cryptographic actions.
2168 * General public-key related Functions:: General functions, not implementing any cryptography.
2171 @node Available algorithms
2172 @section Available algorithms
2174 Libgcrypt supports the RSA (Rivest-Shamir-Adleman) algorithms as well
2175 as DSA (Digital Signature Algorithm) and Elgamal. The versatile
2176 interface allows to add more algorithms in the future.
2178 @node Used S-expressions
2179 @section Used S-expressions
2181 Libgcrypt's API for asymmetric cryptography is based on data
2182 structures called S-expressions (see XXXX) and does not work with
2183 contexts as most of the other building blocks of Libgcrypt
2186 The following information are stored in S-expressions:
2191 @item plain text data
2193 @item encrypted data
2200 To describe how Libgcrypt expect keys, we use examples. Note that
2208 indicate parameters whereas lowercase words are literals.
2210 Note that all MPI (big integer) values are expected to be in
2211 @code{GCRYMPI_FMT_USG} format. An easy way to create S-expressions is
2212 by using @code{gcry_sexp_build} which allows to pass a string with
2213 printf-like escapes to insert MPI values.
2216 * RSA key parameters:: Parameters used with an RSA key.
2217 * DSA key parameters:: Parameters used with a DSA key.
2218 * ECC key parameters:: Parameters used with ECC keys.
2221 @node RSA key parameters
2222 @subsection RSA key parameters
2225 An RSA private key is described by this S-expression:
2239 An RSA public key is described by this S-expression:
2251 RSA public modulus @math{n}.
2253 RSA public exponent @math{e}.
2255 RSA secret exponent @math{d = e^{-1} \bmod (p-1)(q-1)}.
2257 RSA secret prime @math{p}.
2259 RSA secret prime @math{q} with @math{q > p}.
2261 multiplicative inverse @math{u = p^{-1} \bmod q}.
2266 @node DSA key parameters
2267 @subsection DSA key parameters
2270 A DSA private key is described by this S-expression:
2286 DSA group order @math{q} (which is a prime divisor of @math{p-1}).
2288 DSA group generator @math{g}.
2290 DSA public key value @math{y = g^x \bmod p}.
2292 DSA secret exponent x.
2295 The public key is similar with "private-key" replaced by "public-key"
2299 @node ECC key parameters
2300 @subsection ECC key parameters
2303 An ECC private key is described by this S-expression:
2319 Prime specifying the field @math{GF(p)}.
2322 The two coefficients of the Weierstrass equation @math{y^2 = x^3 + ax + b}
2324 Base point @math{g}.
2328 The point representing the public key @math{Q = dP}.
2330 The private key @math{d}
2333 All point values are encoded in standard format; Libgcrypt does
2334 currently only support uncompressed points, thus the first byte needs to
2337 The public key is similar with "private-key" replaced by "public-key"
2340 If the domain parameters are well-known, the name of this curve may be
2346 (curve "NIST P-192")
2351 The @code{curve} parameter may be given in any case and is used to replace
2355 Currently implemented curves are:
2358 @itemx 1.2.840.10045.3.1.1
2361 The NIST 192 bit curve, its OID, X9.62 and SECP aliases.
2365 The NIST 224 bit curve and its SECP alias.
2368 @itemx 1.2.840.10045.3.1.7
2371 The NIST 256 bit curve, its OID, X9.62 and SECP aliases.
2375 The NIST 384 bit curve and its SECP alias.
2379 The NIST 521 bit curve and its SECP alias.
2382 As usual the OIDs may optionally be prefixed with the string @code{OID.}
2387 @node Public key modules
2388 @section Public key modules
2390 Libgcrypt makes it possible to load additional `public key
2391 modules'; these public key algorithms can be used just like the
2392 algorithms that are built into the library directly. For an
2393 introduction into extension modules, see @xref{Modules}.
2395 @deftp {Data type} gcry_pk_spec_t
2396 This is the `module specification structure' needed for registering
2397 public key modules, which has to be filled in by the user before it
2398 can be used to register a module. It contains the following members:
2401 @item const char *name
2402 The primary name of this algorithm.
2403 @item char **aliases
2404 A list of strings that are `aliases' for the algorithm. The list
2405 must be terminated with a NULL element.
2406 @item const char *elements_pkey
2407 String containing the one-letter names of the MPI values contained in
2409 @item const char *element_skey
2410 String containing the one-letter names of the MPI values contained in
2412 @item const char *elements_enc
2413 String containing the one-letter names of the MPI values that are the
2414 result of an encryption operation using this algorithm.
2415 @item const char *elements_sig
2416 String containing the one-letter names of the MPI values that are the
2417 result of a sign operation using this algorithm.
2418 @item const char *elements_grip
2419 String containing the one-letter names of the MPI values that are to
2420 be included in the `key grip'.
2422 The bitwise-OR of the following flags, depending on the abilities of
2425 @item GCRY_PK_USAGE_SIGN
2426 The algorithm supports signing and verifying of data.
2427 @item GCRY_PK_USAGE_ENCR
2428 The algorithm supports the encryption and decryption of data.
2430 @item gcry_pk_generate_t generate
2431 The function responsible for generating a new key pair. See below for
2432 a description of this type.
2433 @item gcry_pk_check_secret_key_t check_secret_key
2434 The function responsible for checking the sanity of a provided secret
2435 key. See below for a description of this type.
2436 @item gcry_pk_encrypt_t encrypt
2437 The function responsible for encrypting data. See below for a
2438 description of this type.
2439 @item gcry_pk_decrypt_t decrypt
2440 The function responsible for decrypting data. See below for a
2441 description of this type.
2442 @item gcry_pk_sign_t sign
2443 The function responsible for signing data. See below for a description
2445 @item gcry_pk_verify_t verify
2446 The function responsible for verifying that the provided signature
2447 matches the provided data. See below for a description of this type.
2448 @item gcry_pk_get_nbits_t get_nbits
2449 The function responsible for returning the number of bits of a provided
2450 key. See below for a description of this type.
2454 @deftp {Data type} gcry_pk_generate_t
2455 Type for the `generate' function, defined as: gcry_err_code_t
2456 (*gcry_pk_generate_t) (int algo, unsigned int nbits, unsigned long
2457 use_e, gcry_mpi_t *skey, gcry_mpi_t **retfactors)
2460 @deftp {Data type} gcry_pk_check_secret_key_t
2461 Type for the `check_secret_key' function, defined as: gcry_err_code_t
2462 (*gcry_pk_check_secret_key_t) (int algo, gcry_mpi_t *skey)
2465 @deftp {Data type} gcry_pk_encrypt_t
2466 Type for the `encrypt' function, defined as: gcry_err_code_t
2467 (*gcry_pk_encrypt_t) (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
2468 gcry_mpi_t *pkey, int flags)
2471 @deftp {Data type} gcry_pk_decrypt_t
2472 Type for the `decrypt' function, defined as: gcry_err_code_t
2473 (*gcry_pk_decrypt_t) (int algo, gcry_mpi_t *result, gcry_mpi_t *data,
2474 gcry_mpi_t *skey, int flags)
2477 @deftp {Data type} gcry_pk_sign_t
2478 Type for the `sign' function, defined as: gcry_err_code_t
2479 (*gcry_pk_sign_t) (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
2483 @deftp {Data type} gcry_pk_verify_t
2484 Type for the `verify' function, defined as: gcry_err_code_t
2485 (*gcry_pk_verify_t) (int algo, gcry_mpi_t hash, gcry_mpi_t *data,
2486 gcry_mpi_t *pkey, int (*cmp) (void *, gcry_mpi_t), void *opaquev)
2489 @deftp {Data type} gcry_pk_get_nbits_t
2490 Type for the `get_nbits' function, defined as: unsigned
2491 (*gcry_pk_get_nbits_t) (int algo, gcry_mpi_t *pkey)
2494 @deftypefun gcry_error_t gcry_pk_register (gcry_pk_spec_t *@var{pubkey}, unsigned int *algorithm_id, gcry_module_t *@var{module})
2496 Register a new public key module whose specification can be found in
2497 @var{pubkey}. On success, a new algorithm ID is stored in
2498 @var{algorithm_id} and a pointer representing this module is stored
2502 @deftypefun void gcry_pk_unregister (gcry_module_t @var{module})
2503 Unregister the public key module identified by @var{module}, which
2504 must have been registered with gcry_pk_register.
2507 @deftypefun gcry_error_t gcry_pk_list (int *@var{list}, int *@var{list_length})
2508 Get a list consisting of the IDs of the loaded pubkey modules. If
2509 @var{list} is zero, write the number of loaded pubkey modules to
2510 @var{list_length} and return. If @var{list} is non-zero, the first
2511 *@var{list_length} algorithm IDs are stored in @var{list}, which must
2512 be of according size. In case there are less pubkey modules than
2513 *@var{list_length}, *@var{list_length} is updated to the correct
2517 @node Cryptographic Functions
2518 @section Cryptographic Functions
2521 Note that we will in future allow to use keys without p,q and u
2522 specified and may also support other parameters for performance
2527 Some functions operating on S-expressions support `flags', that
2528 influence the operation. These flags have to be listed in a
2529 sub-S-expression named `flags'; the following flags are known:
2533 Use PKCS#1 block type 2 padding.
2535 Do not use a technique called `blinding', which is used by default in
2536 order to prevent leaking of secret information. Blinding is only
2537 implemented by RSA, but it might be implemented by other algorithms in
2538 the future as well, when necessary.
2542 Now that we know the key basics, we can carry on and explain how to
2543 encrypt and decrypt data. In almost all cases the data is a random
2544 session key which is in turn used for the actual encryption of the real
2545 data. There are 2 functions to do this:
2547 @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}})
2549 Obviously a public key must be provided for encryption. It is
2550 expected as an appropriate S-expression (see above) in @var{pkey}.
2551 The data to be encrypted can either be in the simple old format, which
2552 is a very simple S-expression consisting only of one MPI, or it may be
2553 a more complex S-expression which also allows to specify flags for
2554 operation, like e.g. padding rules.
2557 If you don't want to let Libgcrypt handle the padding, you must pass an
2558 appropriate MPI using this expression for @var{data}:
2567 This has the same semantics as the old style MPI only way. @var{MPI} is
2568 the actual data, already padded appropriate for your protocol. Most
2569 systems however use PKCS#1 padding and so you can use this S-expression
2575 (value @var{block}))
2579 Here, the "flags" list has the "pkcs1" flag which let the function know
2580 that it should provide PKCS#1 block type 2 padding. The actual data to
2581 be encrypted is passed as a string of octets in @var{block}. The
2582 function checks that this data actually can be used with the given key,
2583 does the padding and encrypts it.
2585 If the function could successfully perform the encryption, the return
2586 value will be 0 and a a new S-expression with the encrypted result is
2587 allocated and assigned to the variable at the address of @var{r_ciph}.
2588 The caller is responsible to release this value using
2589 @code{gcry_sexp_release}. In case of an error, an error code is
2590 returned and @var{r_ciph} will be set to @code{NULL}.
2593 The returned S-expression has this format when used with RSA:
2602 Where @var{a-mpi} is an MPI with the result of the RSA operation. When
2603 using the Elgamal algorithm, the return value will have this format:
2613 Where @var{a-mpi} and @var{b-mpi} are MPIs with the result of the
2614 Elgamal encryption operation.
2616 @c end gcry_pk_encrypt
2618 @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}})
2620 Obviously a private key must be provided for decryption. It is expected
2621 as an appropriate S-expression (see above) in @var{skey}. The data to
2622 be decrypted must match the format of the result as returned by
2623 @code{gcry_pk_encrypt}, but should be enlarged with a @code{flags}
2635 Note that this function currently does not know of any padding
2636 methods and the caller must do any un-padding on his own.
2639 The function returns 0 on success or an error code. The variable at the
2640 address of @var{r_plain} will be set to NULL on error or receive the
2641 decrypted value on success. The format of @var{r_plain} is a
2642 simple S-expression part (i.e. not a valid one) with just one MPI if
2643 there was no @code{flags} element in @var{data}; if at least an empty
2644 @code{flags} is passed in @var{data}, the format is:
2647 (value @var{plaintext})
2650 @c end gcry_pk_decrypt
2653 Another operation commonly performed using public key cryptography is
2654 signing data. In some sense this is even more important than
2655 encryption because digital signatures are an important instrument for
2656 key management. Libgcrypt supports digital signatures using
2657 2 functions, similar to the encryption functions:
2659 @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}})
2661 This function creates a digital signature for @var{data} using the
2662 private key @var{skey} and place it into the variable at the address of
2663 @var{r_sig}. @var{data} may either be the simple old style S-expression
2664 with just one MPI or a modern and more versatile S-expression which
2665 allows to let Libgcrypt handle padding:
2670 (hash @var{hash-algo} @var{block}))
2674 This example requests to sign the data in @var{block} after applying
2675 PKCS#1 block type 1 style padding. @var{hash-algo} is a string with the
2676 hash algorithm to be encoded into the signature, this may be any hash
2677 algorithm name as supported by Libgcrypt. Most likely, this will be
2678 "sha1", "rmd160" or "md5". It is obvious that the length of @var{block}
2679 must match the size of that message digests; the function checks that
2680 this and other constraints are valid.
2683 If PKCS#1 padding is not required (because the caller does already
2684 provide a padded value), either the old format or better the following
2685 format should be used:
2694 Here, the data to be signed is directly given as an @var{MPI}.
2697 The signature is returned as a newly allocated S-expression in
2698 @var{r_sig} using this format for RSA:
2706 Where @var{s-mpi} is the result of the RSA sign operation. For DSA the
2707 S-expression returned is:
2716 Where @var{r-mpi} and @var{s-mpi} are the result of the DSA sign
2717 operation. For Elgamal signing (which is slow, yields large numbers
2718 and probably is not as secure as the other algorithms), the same format is
2719 used with "elg" replacing "dsa".
2724 The operation most commonly used is definitely the verification of a
2725 signature. Libgcrypt provides this function:
2727 @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}})
2729 This is used to check whether the signature @var{sig} matches the
2730 @var{data}. The public key @var{pkey} must be provided to perform this
2731 verification. This function is similar in its parameters to
2732 @code{gcry_pk_sign} with the exceptions that the public key is used
2733 instead of the private key and that no signature is created but a
2734 signature, in a format as created by @code{gcry_pk_sign}, is passed to
2735 the function in @var{sig}.
2738 The result is 0 for success (i.e. the data matches the signature), or an
2739 error code where the most relevant code is @code{GCRYERR_BAD_SIGNATURE}
2740 to indicate that the signature does not match the provided data.
2743 @c end gcry_pk_verify
2745 @node General public-key related Functions
2746 @section General public-key related Functions
2749 A couple of utility functions are available to retrieve the length of
2750 the key, map algorithm identifiers and perform sanity checks:
2752 @deftypefun {const char *} gcry_pk_algo_name (int @var{algo})
2754 Map the public key algorithm id @var{algo} to a string representation of
2755 the algorithm name. For unknown algorithms this functions returns the
2756 string @code{"?"}. This function should not be used to test for the
2757 availability of an algorithm.
2760 @deftypefun int gcry_pk_map_name (const char *@var{name})
2762 Map the algorithm @var{name} to a public key algorithm Id. Returns 0 if
2763 the algorithm name is not known.
2766 @deftypefun int gcry_pk_test_algo (int @var{algo})
2768 Return 0 if the public key algorithm @var{algo} is available for use.
2769 Note that this is implemented as a macro.
2773 @deftypefun {unsigned int} gcry_pk_get_nbits (gcry_sexp_t @var{key})
2775 Return what is commonly referred as the key length for the given
2776 public or private in @var{key}.
2779 @deftypefun {unsigned char *} gcry_pk_get_keygrip (@w{gcry_sexp_t @var{key}}, @w{unsigned char *@var{array}})
2781 Return the so called "keygrip" which is the SHA-1 hash of the public key
2782 parameters expressed in a way depended on the algorithm. @var{array}
2783 must either provide space for 20 bytes or be @code{NULL}. In the latter
2784 case a newly allocated array of that size is returned. On success a
2785 pointer to the newly allocated space or to @var{array} is returned.
2786 @code{NULL} is returned to indicate an error which is most likely an
2787 unknown algorithm or one where a "keygrip" has not yet been defined.
2788 The function accepts public or secret keys in @var{key}.
2791 @deftypefun gcry_error_t gcry_pk_testkey (gcry_sexp_t @var{key})
2793 Return zero if the private key @var{key} is `sane', an error code otherwise.
2794 Note that it is not possible to check the `saneness' of a public key.
2799 @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}})
2801 Depending on the value of @var{what} return various information about
2802 the public key algorithm with the id @var{algo}. Note that the
2803 function returns @code{-1} on error and the actual error code must be
2804 retrieved using the function @code{gcry_errno}. The currently defined
2805 values for @var{what} are:
2808 @item GCRYCTL_TEST_ALGO:
2809 Return 0 when the specified algorithm is available for use.
2810 @var{buffer} must be @code{NULL}, @var{nbytes} may be passed as
2811 @code{NULL} or point to a variable with the required usage of the
2812 algorithm. This may be 0 for "don't care" or the bit-wise OR of these
2816 @item GCRY_PK_USAGE_SIGN
2817 Algorithm is usable for signing.
2818 @item GCRY_PK_USAGE_ENCR
2819 Algorithm is usable for encryption.
2822 @item GCRYCTL_GET_ALGO_USAGE:
2823 Return the usage flags for the given algorithm. An invalid algorithm
2824 return 0. Disabled algorithms are ignored here because we
2825 want to know whether the algorithm is at all capable of a certain usage.
2827 @item GCRYCTL_GET_ALGO_NPKEY
2828 Return the number of elements the public key for algorithm @var{algo}
2829 consist of. Return 0 for an unknown algorithm.
2831 @item GCRYCTL_GET_ALGO_NSKEY
2832 Return the number of elements the private key for algorithm @var{algo}
2833 consist of. Note that this value is always larger than that of the
2834 public key. Return 0 for an unknown algorithm.
2836 @item GCRYCTL_GET_ALGO_NSIGN
2837 Return the number of elements a signature created with the algorithm
2838 @var{algo} consists of. Return 0 for an unknown algorithm or for an
2839 algorithm not capable of creating signatures.
2841 @item GCRYCTL_GET_ALGO_NENC
2842 Return the number of elements a encrypted message created with the algorithm
2843 @var{algo} consists of. Return 0 for an unknown algorithm or for an
2844 algorithm not capable of encryption.
2848 Please note that parameters not required should be passed as @code{NULL}.
2850 @c end gcry_pk_algo_info
2853 @deftypefun gcry_error_t gcry_pk_ctl (@w{int @var{cmd}}, @w{void *@var{buffer}}, @w{size_t @var{buflen}})
2855 This is a general purpose function to perform certain control
2856 operations. @var{cmd} controls what is to be done. The return value is
2857 0 for success or an error code. Currently supported values for
2861 @item GCRYCTL_DISABLE_ALGO
2862 Disable the algorithm given as an algorithm id in @var{buffer}.
2863 @var{buffer} must point to an @code{int} variable with the algorithm id
2864 and @var{buflen} must have the value @code{sizeof (int)}.
2871 Libgcrypt also provides a function for generating public key
2874 @deftypefun gcry_error_t gcry_pk_genkey (@w{gcry_sexp_t *@var{r_key}}, @w{gcry_sexp_t @var{parms}})
2876 This function create a new public key pair using information given in
2877 the S-expression @var{parms} and stores the private and the public key
2878 in one new S-expression at the address given by @var{r_key}. In case of
2879 an error, @var{r_key} is set to @code{NULL}. The return code is 0 for
2880 success or an error code otherwise.
2883 Here is an example for @var{parms} for creating a 1024 bit RSA key:
2892 To create an Elgamal key, substitute "elg" for "rsa" and to create a DSA
2893 key use "dsa". Valid ranges for the key length depend on the
2894 algorithms; all commonly used key lengths are supported. Currently
2895 supported parameters are:
2899 This is always required to specify the length of the key. The argument
2900 is a string with a number in C-notation. The value should be a multiple
2903 @item curve @var{name}
2904 For ECC a named curve may be used instead of giving the number of
2905 requested bits. This allows to request a specific curve to override a
2906 default selection Libgcrypt would have taken if @code{nbits} has been
2907 given. The available names are listed with the description of the ECC
2908 public key parameters.
2911 This is only used with RSA to give a hint for the public exponent. The
2912 value will be used as a base to test for a usable exponent. Some values
2917 Use a secure and fast value. This is currently the number 41.
2919 Use a secure value as required by some specification. This is currently
2926 If this parameter is not used, Libgcrypt uses for historic reasons
2930 This is only meanigful for DSA keys. If it is given the DSA key is
2931 generated with a Q parameyer of this size. If it is not given or zero
2932 Q is deduced from NBITS in this way:
2934 @item 512 <= N <= 1024
2945 Note that in this case only the values for N, as given in the table,
2946 are allowed. When specifying Q all values of N in the range 512 to
2947 15680 are valid as long as they are multiples of 8.
2950 @c end table of parameters
2953 The key pair is returned in a format depending on the algorithm. Both
2954 private and public keys are returned in one container and may be
2955 accompanied by some miscellaneous information.
2958 As an example, here is what the Elgamal key generation returns:
2974 (pm1-factors @var{n1 n2 ... nn})))
2978 As you can see, some of the information is duplicated, but this provides
2979 an easy way to extract either the public or the private key. Note that
2980 the order of the elements is not defined, e.g. the private key may be
2981 stored before the public key. @var{n1 n2 ... nn} is a list of prime
2982 numbers used to composite @var{p-mpi}; this is in general not a very
2985 @c end gcry_pk_genkey
2987 @node Public Key cryptography (II)
2988 @chapter Public Key cryptography (II)
2990 This chapter documents the alternative interface to asymmetric
2991 cryptography (ac) that is not based on S-expressions, but on native C
2992 data structures. As opposed to the pk interface described in the
2993 former chapter, this one follows an open/use/close paradigm like other
2994 building blocks of the library.
2996 @strong{This interface as some known problems; most noteworthy an
2997 inherent tendency to leak memory. It might even be removed in a some
2998 future version of Libgcrypt.}
3002 * Available asymmetric algorithms:: List of algorithms supported by the library.
3003 * Working with sets of data:: How to work with sets of data.
3004 * Working with IO objects:: How to work with IO objects.
3005 * Working with handles:: How to use handles.
3006 * Working with keys:: How to work with keys.
3007 * Using cryptographic functions:: How to perform cryptographic operations.
3008 * Handle-independent functions:: General functions independent of handles.
3011 @node Available asymmetric algorithms
3012 @section Available asymmetric algorithms
3014 Libgcrypt supports the RSA (Rivest-Shamir-Adleman)
3015 algorithms as well as DSA (Digital Signature Algorithm) and Elgamal.
3016 The versatile interface allows to add more algorithms in the future.
3018 @deftp {Data type} gcry_ac_id_t
3020 The following constants are defined for this type:
3024 Rivest-Shamir-Adleman
3026 Digital Signature Algorithm
3030 Elgamal, encryption only.
3034 @node Working with sets of data
3035 @section Working with sets of data
3037 In the context of this interface the term `data set' refers to a list
3038 of `named MPI values' that is used by functions performing
3039 cryptographic operations; a named MPI value is a an MPI value,
3040 associated with a label.
3042 Such data sets are used for representing keys, since keys simply
3043 consist of a variable amount of numbers. Furthermore some functions
3044 return data sets to the caller that are to be provided to other
3047 This section documents the data types, symbols and functions that are
3048 relevant for working with data sets.
3050 @deftp {Data type} gcry_ac_data_t
3054 The following flags are supported:
3057 @item GCRY_AC_FLAG_DEALLOC
3058 Used for storing data in a data set. If given, the data will be
3059 released by the library. Note that whenever one of the ac functions
3060 is about to release objects because of this flag, the objects are
3061 expected to be stored in memory allocated through the Libgcrypt memory
3062 management. In other words: gcry_free() is used instead of free().
3064 @item GCRY_AC_FLAG_COPY
3065 Used for storing/retrieving data in/from a data set. If given, the
3066 library will create copies of the provided/contained data, which will
3067 then be given to the user/associated with the data set.
3070 @deftypefun gcry_error_t gcry_ac_data_new (gcry_ac_data_t *@var{data})
3071 Creates a new, empty data set and stores it in @var{data}.
3074 @deftypefun void gcry_ac_data_destroy (gcry_ac_data_t @var{data})
3075 Destroys the data set @var{data}.
3078 @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})
3079 Add the value @var{mpi} to @var{data} with the label @var{name}. If
3080 @var{flags} contains GCRY_AC_FLAG_DATA_COPY, the data set will contain
3081 copies of @var{name} and @var{mpi}. If @var{flags} contains
3082 GCRY_AC_FLAG_DATA_DEALLOC or GCRY_AC_FLAG_DATA_COPY, the values
3083 contained in the data set will be deallocated when they are to be
3084 removed from the data set.
3087 @deftypefun gcry_error_t gcry_ac_data_copy (gcry_ac_data_t *@var{data_cp}, gcry_ac_data_t @var{data})
3088 Create a copy of the data set @var{data} and store it in
3089 @var{data_cp}. FIXME: exact semantics undefined.
3092 @deftypefun unsigned int gcry_ac_data_length (gcry_ac_data_t @var{data})
3093 Returns the number of named MPI values inside of the data set
3097 @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})
3098 Store the value labelled with @var{name} found in @var{data} in
3099 @var{mpi}. If @var{flags} contains GCRY_AC_FLAG_COPY, store a copy of
3100 the @var{mpi} value contained in the data set. @var{mpi} may be NULL
3101 (this might be useful for checking the existence of an MPI with
3105 @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})
3106 Stores in @var{name} and @var{mpi} the named @var{mpi} value contained
3107 in the data set @var{data} with the index @var{idx}. If @var{flags}
3108 contains GCRY_AC_FLAG_COPY, store copies of the values contained in
3109 the data set. @var{name} or @var{mpi} may be NULL.
3112 @deftypefun void gcry_ac_data_clear (gcry_ac_data_t @var{data})
3113 Destroys any values contained in the data set @var{data}.
3116 @deftypefun gcry_error_t gcry_ac_data_to_sexp (gcry_ac_data_t @var{data}, gcry_sexp_t *@var{sexp}, const char **@var{identifiers})
3117 This function converts the data set @var{data} into a newly created
3118 S-Expression, which is to be stored in @var{sexp}; @var{identifiers}
3119 is a NULL terminated list of C strings, which specifies the structure
3120 of the S-Expression.
3124 If @var{identifiers} is a list of pointers to the strings ``foo'' and
3125 ``bar'' and if @var{data} is a data set containing the values ``val1 =
3126 0x01'' and ``val2 = 0x02'', then the resulting S-Expression will look
3127 like this: (foo (bar ((val1 0x01) (val2 0x02))).
3130 @deftypefun gcry_error gcry_ac_data_from_sexp (gcry_ac_data_t *@var{data}, gcry_sexp_t @var{sexp}, const char **@var{identifiers})
3131 This function converts the S-Expression @var{sexp} into a newly
3132 created data set, which is to be stored in @var{data};
3133 @var{identifiers} is a NULL terminated list of C strings, which
3134 specifies the structure of the S-Expression. If the list of
3135 identifiers does not match the structure of the S-Expression, the
3139 @node Working with IO objects
3140 @section Working with IO objects
3142 Note: IO objects are currently only used in the context of message
3143 encoding/decoding and encryption/signature schemes.
3145 @deftp {Data type} {gcry_ac_io_t}
3146 @code{gcry_ac_io_t} is the type to be used for IO objects.
3149 IO objects provide an uniform IO layer on top of different underlying
3150 IO mechanisms; either they can be used for providing data to the
3151 library (mode is GCRY_AC_IO_READABLE) or they can be used for
3152 retrieving data from the library (mode is GCRY_AC_IO_WRITABLE).
3154 IO object need to be initialized by calling on of the following
3157 @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}, ...);
3158 Initialize @var{ac_io} according to @var{mode}, @var{type} and the
3159 variable list of arguments. The list of variable arguments to specify
3160 depends on the given @var{type}.
3163 @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});
3164 Initialize @var{ac_io} according to @var{mode}, @var{type} and the
3165 variable list of arguments @var{ap}. The list of variable arguments
3166 to specify depends on the given @var{type}.
3169 The following types of IO objects exist:
3172 @item GCRY_AC_IO_STRING
3173 In case of GCRY_AC_IO_READABLE the IO object will provide data from a
3174 memory string. Arguments to specify at initialization time:
3176 @item unsigned char *
3177 Pointer to the beginning of the memory string
3179 Size of the memory string
3181 In case of GCRY_AC_IO_WRITABLE the object will store retrieved data in
3182 a newly allocated memory string. Arguments to specify at
3183 initialization time:
3185 @item unsigned char **
3186 Pointer to address, at which the pointer to the newly created memory
3187 string is to be stored
3189 Pointer to address, at which the size of the newly created memory
3190 string is to be stored
3193 @item GCRY_AC_IO_CALLBACK
3194 In case of GCRY_AC_IO_READABLE the object will forward read requests
3195 to a provided callback function. Arguments to specify at
3196 initialization time:
3198 @item gcry_ac_data_read_cb_t
3199 Callback function to use
3201 Opaque argument to provide to the callback function
3203 In case of GCRY_AC_IO_WRITABLE the object will forward write requests
3204 to a provided callback function. Arguments to specify at
3205 initialization time:
3207 @item gcry_ac_data_write_cb_t
3208 Callback function to use
3210 Opaque argument to provide to the callback function
3214 @node Working with handles
3215 @section Working with handles
3217 In order to use an algorithm, an according handle must be created.
3218 This is done using the following function:
3220 @deftypefun gcry_error_t gcry_ac_open (gcry_ac_handle_t *@var{handle}, int @var{algorithm}, int @var{flags})
3222 Creates a new handle for the algorithm @var{algorithm} and stores it
3223 in @var{handle}. @var{flags} is not used currently.
3225 @var{algorithm} must be a valid algorithm ID, see @xref{Available
3226 algorithms}, for a list of supported algorithms and the according
3227 constants. Besides using the listed constants directly, the functions
3228 @code{gcry_pk_name_to_id} may be used to convert the textual name of
3229 an algorithm into the according numeric ID.
3232 @deftypefun void gcry_ac_close (gcry_ac_handle_t @var{handle})
3233 Destroys the handle @var{handle}.
3236 @node Working with keys
3237 @section Working with keys
3239 @deftp {Data type} gcry_ac_key_type_t
3243 @item GCRY_AC_KEY_TYPE_SECRET
3244 Specifies a secret key.
3245 @item GCRY_AC_KEY_TYPE_PUBLIC
3246 Specifies a public key.
3250 @deftp {Data type} gcry_ac_key_t
3251 This type represents a single `key', either a secret one or a public
3255 @deftp {Data type} gcry_ac_key_pair_t
3256 This type represents a `key pair' containing a secret and a public key.
3259 Key data structures can be created in two different ways; a new key
3260 pair can be generated, resulting in ready-to-use key. Alternatively a
3261 key can be initialized from a given data set.
3263 @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})
3264 Creates a new key of type @var{type}, consisting of the MPI values
3265 contained in the data set @var{data} and stores it in @var{key}.
3268 @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})
3270 Generates a new key pair via the handle @var{handle} of @var{NBITS}
3271 bits and stores it in @var{key_pair}.
3273 In case non-standard settings are wanted, a pointer to a structure of
3274 type @code{gcry_ac_key_spec_<algorithm>_t}, matching the selected
3275 algorithm, can be given as @var{key_spec}. @var{misc_data} is not
3276 used yet. Such a structure does only exist for RSA. A descriptions
3277 of the members of the supported structures follows.
3280 @item gcry_ac_key_spec_rsa_t
3283 Generate the key pair using a special @code{e}. The value of @code{e}
3284 has the following meanings:
3287 Let Libgcrypt decide what exponent should be used.
3289 Request the use of a ``secure'' exponent; this is required by some
3290 specification to be 65537.
3292 Try starting at this value until a working exponent is found. Note
3293 that the current implementation leaks some information about the
3294 private key because the incrementation used is not randomized. Thus,
3295 this function will be changed in the future to return a random
3296 exponent of the given size.
3304 gcry_ac_key_pair_t key_pair;
3305 gcry_ac_key_spec_rsa_t rsa_spec;
3307 rsa_spec.e = gcry_mpi_new (0);
3308 gcry_mpi_set_ui (rsa_spec.e, 1)
3310 err = gcry_ac_open (&handle, GCRY_AC_RSA, 0);
3313 err = gcry_ac_key_pair_generate (handle, &key_pair, 1024, (void *) &rsa_spec);
3320 @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})
3321 Returns the key of type @var{which} out of the key pair
3325 @deftypefun void gcry_ac_key_destroy (gcry_ac_key_t @var{key})
3326 Destroys the key @var{key}.
3329 @deftypefun void gcry_ac_key_pair_destroy (gcry_ac_key_pair_t @var{key_pair})
3330 Destroys the key pair @var{key_pair}.
3333 @deftypefun gcry_ac_data_t gcry_ac_key_data_get (gcry_ac_key_t @var{key})
3334 Returns the data set contained in the key @var{key}.
3337 @deftypefun gcry_error_t gcry_ac_key_test (gcry_ac_handle_t @var{handle}, gcry_ac_key_t @var{key})
3338 Verifies that the private key @var{key} is sane via @var{handle}.
3341 @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})
3342 Stores the number of bits of the key @var{key} in @var{nbits} via @var{handle}.
3345 @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})
3346 Writes the 20 byte long key grip of the key @var{key} to
3347 @var{key_grip} via @var{handle}.
3350 @node Using cryptographic functions
3351 @section Using cryptographic functions
3353 The following flags might be relevant:
3356 @item GCRY_AC_FLAG_NO_BLINDING
3357 Disable any blinding, which might be supported by the chosen
3358 algorithm; blinding is the default.
3361 There exist two kinds of cryptographic functions available through the
3362 ac interface: primitives, and high-level functions.
3364 Primitives deal with MPIs (data sets) directly; what they provide is
3365 direct access to the cryptographic operations provided by an algorithm
3368 High-level functions deal with octet strings, according to a specified
3369 ``scheme''. Schemes make use of ``encoding methods'', which are
3370 responsible for converting the provided octet strings into MPIs, which
3371 are then forwared to the cryptographic primitives. Since schemes are
3372 to be used for a special purpose in order to achieve a particular
3373 security goal, there exist ``encryption schemes'' and ``signature
3374 schemes''. Encoding methods can be used seperately or implicitly
3377 What follows is a description of the cryptographic primitives.
3379 @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})
3380 Encrypts the plain text MPI value @var{data_plain} with the key public
3381 @var{key} under the control of the flags @var{flags} and stores the
3382 resulting data set into @var{data_encrypted}.
3385 @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})
3386 Decrypts the encrypted data contained in the data set
3387 @var{data_encrypted} with the secret key KEY under the control of the
3388 flags @var{flags} and stores the resulting plain text MPI value in
3392 @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})
3393 Signs the data contained in @var{data} with the secret key @var{key}
3394 and stores the resulting signature in the data set
3395 @var{data_signature}.
3398 @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})
3399 Verifies that the signature contained in the data set
3400 @var{data_signature} is indeed the result of signing the data
3401 contained in @var{data} with the secret key belonging to the public
3405 What follows is a description of the high-level functions.
3407 The type ``gcry_ac_em_t'' is used for specifying encoding methods; the
3408 following methods are supported:
3411 @item GCRY_AC_EME_PKCS_V1_5
3412 PKCS-V1_5 Encoding Method for Encryption. Options must be provided
3413 through a pointer to a correctly initialized object of type
3414 gcry_ac_eme_pkcs_v1_5_t.
3416 @item GCRY_AC_EMSA_PKCS_V1_5
3417 PKCS-V1_5 Encoding Method for Signatures with Appendix. Options must
3418 be provided through a pointer to a correctly initialized object of
3419 type gcry_ac_emsa_pkcs_v1_5_t.
3422 Option structure types:
3425 @item gcry_ac_eme_pkcs_v1_5_t
3427 @item gcry_ac_key_t key
3428 @item gcry_ac_handle_t handle
3430 @item gcry_ac_emsa_pkcs_v1_5_t
3432 @item gcry_md_algo_t md
3437 Encoding methods can be used directly through the following functions:
3439 @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})
3440 Encodes the message contained in @var{m} of size @var{m_n} according
3441 to @var{method}, @var{flags} and @var{options}. The newly created
3442 encoded message is stored in @var{em} and @var{em_n}.
3445 @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})
3446 Decodes the message contained in @var{em} of size @var{em_n} according
3447 to @var{method}, @var{flags} and @var{options}. The newly created
3448 decoded message is stored in @var{m} and @var{m_n}.
3451 The type ``gcry_ac_scheme_t'' is used for specifying schemes; the
3452 following schemes are supported:
3455 @item GCRY_AC_ES_PKCS_V1_5
3456 PKCS-V1_5 Encryption Scheme. No options can be provided.
3457 @item GCRY_AC_SSA_PKCS_V1_5
3458 PKCS-V1_5 Signature Scheme (with Appendix). Options can be provided
3459 through a pointer to a correctly initialized object of type
3460 gcry_ac_ssa_pkcs_v1_5_t.
3463 Option structure types:
3466 @item gcry_ac_ssa_pkcs_v1_5_t
3468 @item gcry_md_algo_t md
3472 The functions implementing schemes:
3474 @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})
3475 Encrypts the plain text readable from @var{io_message} through
3476 @var{handle} with the public key @var{key} according to @var{scheme},
3477 @var{flags} and @var{opts}. If @var{opts} is not NULL, it has to be a
3478 pointer to a structure specific to the chosen scheme (gcry_ac_es_*_t).
3479 The encrypted message is written to @var{io_cipher}.
3482 @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})
3483 Decrypts the cipher text readable from @var{io_cipher} through
3484 @var{handle} with the secret key @var{key} according to @var{scheme},
3485 @var{flags} and @var{opts}. If @var{opts} is not NULL, it has to be a
3486 pointer to a structure specific to the chosen scheme (gcry_ac_es_*_t).
3487 The decrypted message is written to @var{io_message}.
3490 @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})
3491 Signs the message readable from @var{io_message} through @var{handle}
3492 with the secret key @var{key} according to @var{scheme}, @var{flags}
3493 and @var{opts}. If @var{opts} is not NULL, it has to be a pointer to
3494 a structure specific to the chosen scheme (gcry_ac_ssa_*_t). The
3495 signature is written to @var{io_signature}.
3498 @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})
3499 Verifies through @var{handle} that the signature readable from
3500 @var{io_signature} is indeed the result of signing the message
3501 readable from @var{io_message} with the secret key belonging to the
3502 public key @var{key} according to @var{scheme} and @var{opts}. If
3503 @var{opts} is not NULL, it has to be an anonymous structure
3504 (gcry_ac_ssa_*_t) specific to the chosen scheme.
3507 @node Handle-independent functions
3508 @section Handle-independent functions
3510 These two functions are deprecated; do not use them for new code.
3512 @deftypefun gcry_error_t gcry_ac_id_to_name (gcry_ac_id_t @var{algorithm}, const char **@var{name})
3513 Stores the textual representation of the algorithm whose id is given
3514 in @var{algorithm} in @var{name}. Deprecated; use @code{gcry_pk_algo_name}.
3517 @deftypefun gcry_error_t gcry_ac_name_to_id (const char *@var{name}, gcry_ac_id_t *@var{algorithm})
3518 Stores the numeric ID of the algorithm whose textual representation is
3519 contained in @var{name} in @var{algorithm}. Deprecated; use
3520 @code{gcry_pk_map_name}.
3523 @c **********************************************************
3524 @c ******************* Random *****************************
3525 @c **********************************************************
3526 @node Random Numbers
3527 @chapter Random Numbers
3530 * Quality of random numbers:: Libgcrypt uses different quality levels.
3531 * Retrieving random numbers:: How to retrieve random numbers.
3534 @node Quality of random numbers
3535 @section Quality of random numbers
3537 @acronym{Libgcypt} offers random numbers of different quality levels:
3539 @deftp {Data type} enum gcry_random_level
3540 The constants for the random quality levels are of this type.
3544 @item GCRY_WEAK_RANDOM
3545 This should not anymore be used. It has recently been changed to an
3546 alias of GCRY_STRONG_RANDOM. Use @code{gcry_create_nonce} instead.
3547 @item GCRY_STRONG_RANDOM
3548 Use this level for e.g. session keys and similar purposes.
3549 @item GCRY_VERY_STRONG_RANDOM
3550 Use this level for e.g. key material.
3553 @node Retrieving random numbers
3554 @section Retrieving random numbers
3556 @deftypefun void gcry_randomize (unsigned char *@var{buffer}, size_t @var{length}, enum gcry_random_level @var{level})
3558 Fill @var{buffer} with @var{length} random bytes using a random quality
3559 as defined by @var{level}.
3562 @deftypefun void * gcry_random_bytes (size_t @var{nbytes}, enum gcry_random_level @var{level})
3564 Allocate a memory block consisting of @var{nbytes} fresh random bytes
3565 using a random quality as defined by @var{level}.
3568 @deftypefun void * gcry_random_bytes_secure (size_t @var{nbytes}, enum gcry_random_level @var{level})
3570 Allocate a memory block consisting of @var{nbytes} fresh random bytes
3571 using a random quality as defined by @var{level}. This function
3572 differs from @code{gcry_random_bytes} in that the returned buffer is
3573 allocated in a ``secure'' area of the memory.
3576 @deftypefun void gcry_create_nonce (unsigned char *@var{buffer}, size_t @var{length})
3578 Fill @var{buffer} with @var{length} unpredictable bytes. This is
3579 commonly called a nonce and may also be used for initialization
3580 vectors and padding. This is an extra function nearly independent of
3581 the other random function for 3 reasons: It better protects the
3582 regular random generator's internal state, provides better performance
3583 and does not drain the precious entropy pool.
3589 @c **********************************************************
3590 @c ******************* S-Expressions ***********************
3591 @c **********************************************************
3593 @chapter S-expressions
3595 S-expressions are used by the public key functions to pass complex data
3596 structures around. These LISP like objects are used by some
3597 cryptographic protocols (cf. RFC-2692) and Libgcrypt provides functions
3598 to parse and construct them. For detailed information, see
3599 @cite{Ron Rivest, code and description of S-expressions,
3600 @uref{http://theory.lcs.mit.edu/~rivest/sexp.html}}.
3603 * Data types for S-expressions:: Data types related with S-expressions.
3604 * Working with S-expressions:: How to work with S-expressions.
3607 @node Data types for S-expressions
3608 @section Data types for S-expressions
3610 @deftp {Data type} gcry_sexp_t
3611 The @code{gcry_sexp_t} type describes an object with the Libgcrypt internal
3612 representation of an S-expression.
3615 @node Working with S-expressions
3616 @section Working with S-expressions
3619 There are several functions to create an Libgcrypt S-expression object
3620 from its external representation or from a string template. There is
3621 also a function to convert the internal representation back into one of
3622 the external formats:
3625 @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}})
3627 This is the generic function to create an new S-expression object from
3628 its external representation in @var{buffer} of @var{length} bytes. On
3629 success the result is stored at the address given by @var{r_sexp}.
3630 With @var{autodetect} set to 0, the data in @var{buffer} is expected to
3631 be in canonized format, with @var{autodetect} set to 1 the parses any of
3632 the defined external formats. If @var{buffer} does not hold a valid
3633 S-expression an error code is returned and @var{r_sexp} set to
3635 Note that the caller is responsible for releasing the newly allocated
3636 S-expression using @code{gcry_sexp_release}.
3639 @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*)})
3641 This function is identical to @code{gcry_sexp_new} but has an extra
3642 argument @var{freefnc}, which, when not set to @code{NULL}, is expected
3643 to be a function to release the @var{buffer}; most likely the standard
3644 @code{free} function is used for this argument. This has the effect of
3645 transferring the ownership of @var{buffer} to the created object in
3646 @var{r_sexp}. The advantage of using this function is that Libgcrypt
3647 might decide to directly use the provided buffer and thus avoid extra
3651 @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}})
3653 This is another variant of the above functions. It behaves nearly
3654 identical but provides an @var{erroff} argument which will receive the
3655 offset into the buffer where the parsing stopped on error.
3658 @deftypefun gcry_error_t gcry_sexp_build (@w{gcry_sexp_t *@var{r_sexp}}, @w{size_t *@var{erroff}}, @w{const char *@var{format}, ...})
3660 This function creates an internal S-expression from the string template
3661 @var{format} and stores it at the address of @var{r_sexp}. If there is a
3662 parsing error, the function returns an appropriate error code and stores
3663 the offset into @var{format} where the parsing stopped in @var{erroff}.
3664 The function supports a couple of printf-like formatting characters and
3665 expects arguments for some of these escape sequences right after
3666 @var{format}. The following format characters are defined:
3670 The next argument is expected to be of type @code{gcry_mpi_t} and a copy of
3671 its value is inserted into the resulting S-expression.
3673 The next argument is expected to be of type @code{char *} and that
3674 string is inserted into the resulting S-expression.
3676 The next argument is expected to be of type @code{int} and its value is
3677 inserted into the resulting S-expression.
3679 The next argument is expected to be of type @code{int} directly
3680 followed by an argument of type @code{char *}. This represents a
3681 buffer of given length to be inserted into the resulting regular
3686 No other format characters are defined and would return an error. Note
3687 that the format character @samp{%%} does not exists, because a percent
3688 sign is not a valid character in an S-expression.
3691 @deftypefun void gcry_sexp_release (@w{gcry_sexp_t @var{sexp}})
3693 Release the S-expression object @var{sexp}.
3698 The next 2 functions are used to convert the internal representation
3699 back into a regular external S-expression format and to show the
3700 structure for debugging.
3702 @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}})
3704 Copies the S-expression object @var{sexp} into @var{buffer} using the
3705 format specified in @var{mode}. @var{maxlength} must be set to the
3706 allocated length of @var{buffer}. The function returns the actual
3707 length of valid bytes put into @var{buffer} or 0 if the provided buffer
3708 is too short. Passing @code{NULL} for @var{buffer} returns the required
3709 length for @var{buffer}. For convenience reasons an extra byte with
3710 value 0 is appended to the buffer.
3713 The following formats are supported:
3716 @item GCRYSEXP_FMT_DEFAULT
3717 Returns a convenient external S-expression representation.
3719 @item GCRYSEXP_FMT_CANON
3720 Return the S-expression in canonical format.
3722 @item GCRYSEXP_FMT_BASE64
3723 Not currently supported.
3725 @item GCRYSEXP_FMT_ADVANCED
3726 Returns the S-expression in advanced format.
3730 @deftypefun void gcry_sexp_dump (@w{gcry_sexp_t @var{sexp}})
3732 Dumps @var{sexp} in a format suitable for debugging to Libgcrypt's
3737 Often canonical encoding is used in the external representation. The
3738 following function can be used to check for valid encoding and to learn
3739 the length of the S-expression"
3741 @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}})
3743 Scan the canonical encoded @var{buffer} with implicit length values and
3744 return the actual length this S-expression uses. For a valid S-expression
3745 it should never return 0. If @var{length} is not 0, the maximum
3746 length to scan is given; this can be used for syntax checks of
3747 data passed from outside. @var{errcode} and @var{erroff} may both be
3748 passed as @code{NULL}.
3754 There are a couple of functions to parse S-expressions and retrieve
3757 @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}})
3759 Scan the S-expression for a sublist with a type (the car of the list)
3760 matching the string @var{token}. If @var{toklen} is not 0, the token is
3761 assumed to be raw memory of this length. The function returns a newly
3762 allocated S-expression consisting of the found sublist or @code{NULL}
3767 @deftypefun int gcry_sexp_length (@w{const gcry_sexp_t @var{list}})
3769 Return the length of the @var{list}. For a valid S-expression this
3770 should be at least 1.
3774 @deftypefun gcry_sexp_t gcry_sexp_nth (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}})
3776 Create and return a new S-expression from the element with index @var{number} in
3777 @var{list}. Note that the first element has the index 0. If there is
3778 no such element, @code{NULL} is returned.
3781 @deftypefun gcry_sexp_t gcry_sexp_car (@w{const gcry_sexp_t @var{list}})
3783 Create and return a new S-expression from the first element in
3784 @var{list}; this called the "type" and should always exist and be a
3785 string. @code{NULL} is returned in case of a problem.
3788 @deftypefun gcry_sexp_t gcry_sexp_cdr (@w{const gcry_sexp_t @var{list}})
3790 Create and return a new list form all elements except for the first one.
3791 Note that this function may return an invalid S-expression because it
3792 is not guaranteed, that the type exists and is a string. However, for
3793 parsing a complex S-expression it might be useful for intermediate
3794 lists. Returns @code{NULL} on error.
3798 @deftypefun {const char *} gcry_sexp_nth_data (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{size_t *@var{datalen}})
3800 This function is used to get data from a @var{list}. A pointer to the
3801 actual data with index @var{number} is returned and the length of this
3802 data will be stored to @var{datalen}. If there is no data at the given
3803 index or the index represents another list, @code{NULL} is returned.
3804 @strong{Caution:} The returned pointer is valid as long as @var{list} is
3805 not modified or released.
3808 Here is an example on how to extract and print the surname (Meier) from
3809 the S-expression @samp{(Name Otto Meier (address Burgplatz 3))}:
3815 name = gcry_sexp_nth_data (list, 2, &len);
3816 printf ("my name is %.*s\n", (int)len, name);
3820 @deftypefun char *gcry_sexp_nth_string (@w{gcry_sexp_t @var{list}}, @w{int @var{number}})
3822 This function is used to get and convert data from a @var{list}. The
3823 data is assumed to be a Nul terminated string. The caller must
3824 release this returned value using @code{gcry_free}. If there is
3825 no data at the given index, the index represents a list or the value
3826 can't be converted to a string, @code{NULL} is returned.
3829 @deftypefun gcry_mpi_t gcry_sexp_nth_mpi (@w{gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{int @var{mpifmt}})
3831 This function is used to get and convert data from a @var{list}. This
3832 data is assumed to be an MPI stored in the format described by
3833 @var{mpifmt} and returned as a standard Libgcrypt MPI. The caller must
3834 release this returned value using @code{gcry_mpi_release}. If there is
3835 no data at the given index, the index represents a list or the value
3836 can't be converted to an MPI, @code{NULL} is returned.
3840 @c **********************************************************
3841 @c ******************* MPIs ******** ***********************
3842 @c **********************************************************
3844 @chapter MPI library
3847 * Data types:: MPI related data types.
3848 * Basic functions:: First steps with MPI numbers.
3849 * MPI formats:: External representation of MPIs.
3850 * Calculations:: Performing MPI calculations.
3851 * Comparisons:: How to compare MPI values.
3852 * Bit manipulations:: How to access single bits of MPI values.
3853 * Miscellaneous:: Miscellaneous MPI functions.
3856 Public key cryptography is based on mathematics with large numbers. To
3857 implement the public key functions, a library for handling these large
3858 numbers is required. Because of the general usefulness of such a
3859 library, its interface is exposed by Libgcrypt. The implementation is
3860 based on an old release of GNU Multi-Precision Library (GMP) but in the
3861 meantime heavily modified and stripped down to what is required for
3862 cryptography. For a lot of CPUs, high performance assembler
3863 implementations of some very low level functions are used to gain much
3864 better performance than with the standard C implementation.
3867 In the context of Libgcrypt and in most other applications, these large
3868 numbers are called MPIs (multi-precision-integers).
3873 @deftp {Data type} gcry_mpi_t
3874 The @code{gcry_mpi_t} type represents an object to hold an MPI.
3877 @node Basic functions
3878 @section Basic functions
3881 To work with MPIs, storage must be allocated and released for the
3882 numbers. This can be done with one of these functions:
3884 @deftypefun gcry_mpi_t gcry_mpi_new (@w{unsigned int @var{nbits}})
3886 Allocate a new MPI object, initialize it to 0 and initially allocate
3887 enough memory for a number of at least @var{nbits}. This pre-allocation is
3888 only a small performance issue and not actually necessary because
3889 Libgcrypt automatically re-allocates the required memory.
3892 @deftypefun gcry_mpi_t gcry_mpi_snew (@w{unsigned int @var{nbits}})
3894 This is identical to @code{gcry_mpi_new} but allocates the MPI in the so
3895 called "secure memory" which in turn will take care that all derived
3896 values will also be stored in this "secure memory". Use this for highly
3897 confidential data like private key parameters.
3900 @deftypefun gcry_mpi_t gcry_mpi_copy (@w{const gcry_mpi_t @var{a}})
3902 Create a new MPI as the exact copy of @var{a}.
3906 @deftypefun void gcry_mpi_release (@w{gcry_mpi_t @var{a}})
3908 Release the MPI @var{a} and free all associated resources. Passing
3909 @code{NULL} is allowed and ignored. When a MPI stored in the "secure
3910 memory" is released, that memory gets wiped out immediately.
3914 The simplest operations are used to assign a new value to an MPI:
3916 @deftypefun gcry_mpi_t gcry_mpi_set (@w{gcry_mpi_t @var{w}}, @w{const gcry_mpi_t @var{u}})
3918 Assign the value of @var{u} to @var{w} and return @var{w}. If
3919 @code{NULL} is passed for @var{w}, a new MPI is allocated, set to the
3920 value of @var{u} and returned.
3923 @deftypefun gcry_mpi_t gcry_mpi_set_ui (@w{gcry_mpi_t @var{w}}, @w{unsigned long @var{u}})
3925 Assign the value of @var{u} to @var{w} and return @var{w}. If
3926 @code{NULL} is passed for @var{w}, a new MPI is allocated, set to the
3927 value of @var{u} and returned. This function takes an @code{unsigned
3928 int} as type for @var{u} and thus it is only possible to set @var{w} to
3929 small values (usually up to the word size of the CPU).
3932 @deftypefun void gcry_mpi_swap (@w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}})
3934 Swap the values of @var{a} and @var{b}.
3938 @section MPI formats
3941 The following functions are used to convert between an external
3942 representation of an MPI and the internal one of Libgcrypt.
3944 @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}})
3946 Convert the external representation of an integer stored in @var{buffer}
3947 with a length of @var{buflen} into a newly created MPI returned which
3948 will be stored at the address of @var{r_mpi}. For certain formats the
3949 length argument is not required and may be passed as @code{0}. After a
3950 successful operation the variable @var{nscanned} receives the number of
3951 bytes actually scanned unless @var{nscanned} was given as
3952 @code{NULL}. @var{format} describes the format of the MPI as stored in
3956 @item GCRYMPI_FMT_STD
3957 2-complement stored without a length header.
3959 @item GCRYMPI_FMT_PGP
3960 As used by OpenPGP (only defined as unsigned). This is basically
3961 @code{GCRYMPI_FMT_STD} with a 2 byte big endian length header.
3963 @item GCRYMPI_FMT_SSH
3964 As used in the Secure Shell protocol. This is @code{GCRYMPI_FMT_STD}
3965 with a 4 byte big endian header.
3967 @item GCRYMPI_FMT_HEX
3968 Stored as a C style string with each byte of the MPI encoded as 2 hex
3969 digits. When using this format, @var{buflen} must be zero.
3971 @item GCRYMPI_FMT_USG
3972 Simple unsigned integer.
3976 Note that all of the above formats store the integer in big-endian
3981 @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}})
3983 Convert the MPI @var{a} into an external representation described by
3984 @var{format} (see above) and store it in the provided @var{buffer}
3985 which has a usable length of at least the @var{buflen} bytes. If
3986 @var{nwritten} is not NULL, it will receive the number of bytes
3987 actually stored in @var{buffer} after a successful operation.
3990 @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}})
3992 Convert the MPI @var{a} into an external representation described by
3993 @var{format} (see above) and store it in a newly allocated buffer which
3994 address will be stored in the variable @var{buffer} points to. The
3995 number of bytes stored in this buffer will be stored in the variable
3996 @var{nbytes} points to, unless @var{nbytes} is @code{NULL}.
3999 @deftypefun void gcry_mpi_dump (@w{const gcry_mpi_t @var{a}})
4001 Dump the value of @var{a} in a format suitable for debugging to
4002 Libgcrypt's logging stream. Note that one leading space but no trailing
4003 space or linefeed will be printed. It is okay to pass @code{NULL} for
4009 @section Calculations
4012 Basic arithmetic operations:
4014 @deftypefun void gcry_mpi_add (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
4016 @math{@var{w} = @var{u} + @var{v}}.
4020 @deftypefun void gcry_mpi_add_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4022 @math{@var{w} = @var{u} + @var{v}}. Note that @var{v} is an unsigned integer.
4026 @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}})
4028 @math{@var{w} = @var{u} + @var{v} \bmod @var{m}}.
4031 @deftypefun void gcry_mpi_sub (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
4033 @math{@var{w} = @var{u} - @var{v}}.
4036 @deftypefun void gcry_mpi_sub_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4038 @math{@var{w} = @var{u} - @var{v}}. @var{v} is an unsigned integer.
4041 @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}})
4043 @math{@var{w} = @var{u} - @var{v} \bmod @var{m}}.
4046 @deftypefun void gcry_mpi_mul (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
4048 @math{@var{w} = @var{u} * @var{v}}.
4051 @deftypefun void gcry_mpi_mul_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4053 @math{@var{w} = @var{u} * @var{v}}. @var{v} is an unsigned integer.
4056 @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}})
4058 @math{@var{w} = @var{u} * @var{v} \bmod @var{m}}.
4061 @deftypefun void gcry_mpi_mul_2exp (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{e}})
4063 @c FIXME: I am in need for a real TeX{info} guru:
4064 @c I don't know why TeX can grok @var{e} here.
4065 @math{@var{w} = @var{u} * 2^e}.
4068 @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}})
4070 @math{@var{q} = @var{dividend} / @var{divisor}}, @math{@var{r} =
4071 @var{dividend} \bmod @var{divisor}}. @var{q} and @var{r} may be passed
4072 as @code{NULL}. @var{round} should be negative or 0.
4075 @deftypefun void gcry_mpi_mod (@w{gcry_mpi_t @var{r}}, @w{gcry_mpi_t @var{dividend}}, @w{gcry_mpi_t @var{divisor}})
4077 @math{@var{r} = @var{dividend} \bmod @var{divisor}}.
4080 @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}})
4082 @c I don't know why TeX can grok @var{e} here.
4083 @math{@var{w} = @var{b}^e \bmod @var{m}}.
4086 @deftypefun int gcry_mpi_gcd (@w{gcry_mpi_t @var{g}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}})
4088 Set @var{g} to the greatest common divisor of @var{a} and @var{b}.
4089 Return true if the @var{g} is 1.
4092 @deftypefun int gcry_mpi_invm (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{m}})
4094 Set @var{x} to the multiplicative inverse of @math{@var{a} \bmod @var{m}}.
4095 Return true if the inverse exists.
4100 @section Comparisons
4103 The next 2 functions are used to compare MPIs:
4106 @deftypefun int gcry_mpi_cmp (@w{const gcry_mpi_t @var{u}}, @w{const gcry_mpi_t @var{v}})
4108 Compare the big integer number @var{u} and @var{v} returning 0 for
4109 equality, a positive value for @var{u} > @var{v} and a negative for
4113 @deftypefun int gcry_mpi_cmp_ui (@w{const gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4115 Compare the big integer number @var{u} with the unsigned integer @var{v}
4116 returning 0 for equality, a positive value for @var{u} > @var{v} and a
4117 negative for @var{u} < @var{v}.
4121 @node Bit manipulations
4122 @section Bit manipulations
4125 There are a couple of functions to get information on arbitrary bits
4126 in an MPI and to set or clear them:
4128 @deftypefun {unsigned int} gcry_mpi_get_nbits (@w{gcry_mpi_t @var{a}})
4130 Return the number of bits required to represent @var{a}.
4133 @deftypefun int gcry_mpi_test_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4135 Return true if bit number @var{n} (counting from 0) is set in @var{a}.
4138 @deftypefun void gcry_mpi_set_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4140 Set bit number @var{n} in @var{a}.
4143 @deftypefun void gcry_mpi_clear_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4145 Clear bit number @var{n} in @var{a}.
4148 @deftypefun void gcry_mpi_set_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4150 Set bit number @var{n} in @var{a} and clear all bits greater than @var{n}.
4153 @deftypefun void gcry_mpi_clear_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4155 Clear bit number @var{n} in @var{a} and all bits greater than @var{n}.
4158 @deftypefun void gcry_mpi_rshift (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4160 Shift the value of @var{a} by @var{n} bits to the right and store the
4165 @section Miscellaneous
4167 @deftypefun gcry_mpi_t gcry_mpi_set_opaque (@w{gcry_mpi_t @var{a}}, @w{void *@var{p}}, @w{unsigned int @var{nbits}})
4169 Store @var{nbits} of the value @var{p} points to in @var{a} and mark
4170 @var{a} as an opaque value (i.e. an value that can't be used for any
4171 math calculation and is only used to store an arbitrary bit pattern in
4174 WARNING: Never use an opaque MPI for actual math operations. The only
4175 valid functions are gcry_mpi_get_opaque and gcry_mpi_release. Use
4176 gcry_mpi_scan to convert a string of arbitrary bytes into an MPI.
4180 @deftypefun {void *} gcry_mpi_get_opaque (@w{gcry_mpi_t @var{a}}, @w{unsigned int *@var{nbits}})
4182 Return a pointer to an opaque value stored in @var{a} and return its
4183 size in @var{nbits}. Note that the returned pointer is still owned by
4184 @var{a} and that the function should never be used for an non-opaque
4188 @deftypefun void gcry_mpi_set_flag (@w{gcry_mpi_t @var{a}}, @w{enum gcry_mpi_flag @var{flag}})
4190 Set the @var{flag} for the MPI @var{a}. Currently only the flag
4191 @code{GCRYMPI_FLAG_SECURE} is allowed to convert @var{a} into an MPI
4192 stored in "secure memory".
4195 @deftypefun void gcry_mpi_clear_flag (@w{gcry_mpi_t @var{a}}, @w{enum gcry_mpi_flag @var{flag}})
4197 Clear @var{flag} for the big integer @var{a}. Note that this function is
4198 currently useless as no flags are allowed.
4201 @deftypefun int gcry_mpi_get_flag (@w{gcry_mpi_t @var{a}}, @w{enum gcry_mpi_flag @var{flag}})
4203 Return true when the @var{flag} is set for @var{a}.
4206 @deftypefun void gcry_mpi_randomize (@w{gcry_mpi_t @var{w}}, @w{unsigned int @var{nbits}}, @w{enum gcry_random_level @var{level}})
4208 Set the big integer @var{w} to a random value of @var{nbits}, using
4209 random data quality of level @var{level}. In case @var{nbits} is not
4210 a multiple of a byte, @var{nbits} is rounded up to the next byte
4214 @c **********************************************************
4215 @c ******************** Prime numbers ***********************
4216 @c **********************************************************
4218 @chapter Prime numbers
4221 * Generation:: Generation of new prime numbers.
4222 * Checking:: Checking if a given number is prime.
4228 @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})
4230 Generate a new prime number of @var{prime_bits} bits and store it in
4231 @var{prime}. If @var{factor_bits} is non-zero, one of the prime factors
4232 of (@var{prime} - 1) / 2 must be @var{factor_bits} bits long. If
4233 @var{factors} is non-zero, allocate a new, @code{NULL}-terminated array
4234 holding the prime factors and store it in @var{factors}. @var{flags}
4235 might be used to influence the prime number generation process.
4238 @deftypefun gcry_prime_group_generator (gcry_mpi_t *@var{r_g},
4239 gcry_mpi_t @var{prime}, gcry_mpi_t *@var{factors}, gcry_mpi_t @var{start_g})
4241 Find a generator for @var{prime} where the factorization of
4242 (@var{prime}-1) is in the @code{NULL} terminated array @var{factors}.
4243 Return the generator as a newly allocated MPI in @var{r_g}. If
4244 @var{start_g} is not NULL, use this as the start for the search.
4247 @deftypefun void gcry_prime_release_factors (gcry_mpi_t *@var{factors})
4249 Convenience function to release the @var{factors} array.
4255 @deftypefun gcry_error_t gcry_prime_check (gcry_mpi_t @var{p}, unsigned int @var{flags})
4257 Check wether the number @var{p} is prime. Returns zero in case @var{p}
4258 is indeed a prime, returns @code{GPG_ERR_NO_PRIME} in case @var{p} is
4259 not a prime and a different error code in case something went horribly
4263 @c **********************************************************
4264 @c ******************** Utilities ***************************
4265 @c **********************************************************
4270 * Memory allocation:: Functions related with memory allocation.
4273 @node Memory allocation
4274 @section Memory allocation
4276 @deftypefun void *gcry_malloc (size_t @var{n})
4278 This function tries to allocate @var{n} bytes of memory. On success
4279 it returns a pointer to the memory area, in an out-of-core condition,
4283 @deftypefun void *gcry_malloc_secure (size_t @var{n})
4284 Like @code{gcry_malloc}, but uses secure memory.
4287 @deftypefun void *gcry_calloc (size_t @var{n})
4289 This function tries to allocate @var{n} bytes of cleared memory
4290 (i.e. memory that is initialized with zero bytes). On success it
4291 returns a pointer to the memory area, in an out-of-core condition, it
4295 @deftypefun void *gcry_calloc_secure (size_t @var{n})
4296 Like @code{gcry_calloc}, but uses secure memory.
4299 @deftypefun void *gcry_realloc (void *@var{p}, size_t @var{n})
4301 This function tries to resize the memory area pointed to by @var{p} to
4302 @var{n} bytes. On success it returns a pointer to the new memory
4303 area, in an out-of-core condition, it returns NULL. Depending on
4304 whether the memory pointed to by @var{p} is secure memory or not,
4305 gcry_realloc tries to use secure memory as well.
4308 @deftypefun void gcry_free (void *@var{p})
4309 Release the memory area pointed to by @var{p}.
4312 @c **********************************************************
4313 @c ******************* Appendices *************************
4314 @c **********************************************************
4321 @unnumbered Concept Index
4325 @node Function and Data Index
4326 @unnumbered Function and Data Index
4332 /* Version check should be the very first gcry call because it
4333 makes sure that constructor functions are run. */
4334 if (!gcry_check_version (GCRYPT_VERSION))
4335 die ("version mismatch\n");
4336 /* Many applications don't require secure memory, so they should
4337 disable it right away. There won't be a problem unless one makes
4338 use of a feature which requires secure memory - in that case the
4339 process would abort because the secmem is not initialized. */
4340 gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
4342 /* .. add whatever initialization you want, but better don't make calls
4343 to libgcrypt from more than one thread ... */
4345 /* Tell Libgcrypt that initialization has completed. */
4346 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
4349 If you require secure memory, this code should be used:
4351 if (!gcry_check_version (GCRYPT_VERSION))