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, 2008 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 * Public Key cryptography:: How to use public key cryptography.
70 * Hashing:: How to use hash and MAC algorithms.
71 * Random Numbers:: How to work with random numbers.
72 * S-expressions:: How to manage S-expressions.
73 * MPI library:: How to work with multi-precision-integers.
74 * Prime numbers:: How to use the Prime number related functions.
75 * Utilities:: Utility functions.
76 * Architecture:: How Libgcrypt works internally.
80 * FIPS Restrictions:: Restrictions in FIPS mode.
81 * Library Copying:: The GNU Lesser General Public License
82 says how you can copy and share Libgcrypt.
83 * Copying:: The GNU General Public License says how you
84 can copy and share some parts of Libgcrypt.
88 * Concept Index:: Index of concepts and programs.
89 * Function and Data Index:: Index of functions, variables and data types.
100 @c **********************************************************
101 @c ******************* Introduction ***********************
102 @c **********************************************************
104 @chapter Introduction
106 Libgcrypt is a library providing cryptographic building blocks.
109 * Getting Started:: How to use this manual.
110 * Features:: A glance at Libgcrypt's features.
111 * Overview:: Overview about the library.
114 @node Getting Started
115 @section Getting Started
117 This manual documents the Libgcrypt library application programming
118 interface (API). All functions and data types provided by the library
122 The reader is assumed to possess basic knowledge about applied
125 This manual can be used in several ways. If read from the beginning
126 to the end, it gives a good introduction into the library and how it
127 can be used in an application. Forward references are included where
128 necessary. Later on, the manual can be used as a reference manual to
129 get just the information needed about any particular interface of the
130 library. Experienced programmers might want to start looking at the
131 examples at the end of the manual, and then only read up those parts
132 of the interface which are unclear.
138 Libgcrypt might have a couple of advantages over other libraries doing
142 @item It's Free Software
143 Anybody can use, modify, and redistribute it under the terms of the GNU
144 Lesser General Public License (@pxref{Library Copying}). Note, that
145 some parts (which are in general not needed by applications) are subject
146 to the terms of the GNU General Public License (@pxref{Copying}); please
147 see the README file of the distribution for of list of these parts.
149 @item It encapsulates the low level cryptography
150 Libgcrypt provides a high level interface to cryptographic
151 building blocks using an extensible and flexible API.
159 The Libgcrypt library is fully thread-safe, where it makes
160 sense to be thread-safe. Not thread-safe are some cryptographic
161 functions that modify a certain context stored in handles. If the
162 user really intents to use such functions from different threads on
163 the same handle, he has to take care of the serialization of such
164 functions himself. If not described otherwise, every function is
167 Libgcrypt depends on the library `libgpg-error', which
168 contains common error handling related code for GnuPG components.
170 @c **********************************************************
171 @c ******************* Preparation ************************
172 @c **********************************************************
176 To use Libgcrypt, you have to perform some changes to your
177 sources and the build system. The necessary changes are small and
178 explained in the following sections. At the end of this chapter, it
179 is described how the library is initialized, and how the requirements
180 of the library are verified.
183 * Header:: What header file you need to include.
184 * Building sources:: How to build sources using the library.
185 * Building sources using Automake:: How to build sources with the help of Automake.
186 * Initializing the library:: How to initialize the library.
187 * Multi-Threading:: How Libgcrypt can be used in a MT environment.
188 * FIPS mode:: How to enable the FIPS mode.
195 All interfaces (data types and functions) of the library are defined
196 in the header file @file{gcrypt.h}. You must include this in all source
197 files using the library, either directly or through some other header
204 The name space of Libgcrypt is @code{gcry_*} for function
205 and type names and @code{GCRY*} for other symbols. In addition the
206 same name prefixes with one prepended underscore are reserved for
207 internal use and should never be used by an application. Note that
208 Libgcrypt uses libgpg-error, which uses @code{gpg_*} as
209 name space for function and type names and @code{GPG_*} for other
210 symbols, including all the error codes.
213 Certain parts of gcrypt.h may be excluded by defining these macros:
216 @item GCRYPT_NO_MPI_MACROS
217 Do not define the shorthand macros @code{mpi_*} for @code{gcry_mpi_*}.
219 @item GCRYPT_NO_DEPRECATED
220 Do not include defintions for deprecated features. This is useful to
221 make sure that no deprecated features are used.
224 @node Building sources
225 @section Building sources
227 If you want to compile a source file including the `gcrypt.h' header
228 file, you must make sure that the compiler can find it in the
229 directory hierarchy. This is accomplished by adding the path to the
230 directory in which the header file is located to the compilers include
231 file search path (via the @option{-I} option).
233 However, the path to the include file is determined at the time the
234 source is configured. To solve this problem, Libgcrypt ships with a small
235 helper program @command{libgcrypt-config} that knows the path to the
236 include file and other configuration options. The options that need
237 to be added to the compiler invocation at compile time are output by
238 the @option{--cflags} option to @command{libgcrypt-config}. The following
239 example shows how it can be used at the command line:
242 gcc -c foo.c `libgcrypt-config --cflags`
245 Adding the output of @samp{libgcrypt-config --cflags} to the compilers
246 command line will ensure that the compiler can find the Libgcrypt header
249 A similar problem occurs when linking the program with the library.
250 Again, the compiler has to find the library files. For this to work,
251 the path to the library files has to be added to the library search path
252 (via the @option{-L} option). For this, the option @option{--libs} to
253 @command{libgcrypt-config} can be used. For convenience, this option
254 also outputs all other options that are required to link the program
255 with the Libgcrypt libraries (in particular, the @samp{-lgcrypt}
256 option). The example shows how to link @file{foo.o} with the Libgcrypt
257 library to a program @command{foo}.
260 gcc -o foo foo.o `libgcrypt-config --libs`
263 Of course you can also combine both examples to a single command by
264 specifying both options to @command{libgcrypt-config}:
267 gcc -o foo foo.c `libgcrypt-config --cflags --libs`
270 @node Building sources using Automake
271 @section Building sources using Automake
273 It is much easier if you use GNU Automake instead of writing your own
274 Makefiles. If you do that, you do not have to worry about finding and
275 invoking the @command{libgcrypt-config} script at all.
276 Libgcrypt provides an extension to Automake that does all
279 @c A simple macro for optional variables.
281 @r{[}@var{\varname\}@r{]}
283 @defmac AM_PATH_LIBGCRYPT (@ovar{minimum-version}, @ovar{action-if-found}, @ovar{action-if-not-found})
284 Check whether Libgcrypt (at least version
285 @var{minimum-version}, if given) exists on the host system. If it is
286 found, execute @var{action-if-found}, otherwise do
287 @var{action-if-not-found}, if given.
289 Additionally, the function defines @code{LIBGCRYPT_CFLAGS} to the
290 flags needed for compilation of the program to find the
291 @file{gcrypt.h} header file, and @code{LIBGCRYPT_LIBS} to the linker
292 flags needed to link the program to the Libgcrypt library.
295 You can use the defined Autoconf variables like this in your
299 AM_CPPFLAGS = $(LIBGCRYPT_CFLAGS)
300 LDADD = $(LIBGCRYPT_LIBS)
303 @node Initializing the library
304 @section Initializing the library
306 Before the library can be used, it must initialize itself. This is
307 achieved by invoking the function @code{gcry_check_version} described
310 Also, it is often desirable to check that the version of
311 Libgcrypt used is indeed one which fits all requirements.
312 Even with binary compatibility, new features may have been introduced,
313 but due to problem with the dynamic linker an old version may actually
314 be used. So you may want to check that the version is okay right
315 after program startup.
317 @deftypefun const char *gcry_check_version (const char *@var{req_version})
319 The function @code{gcry_check_version} initializes some subsystems used
320 by Libgcrypt and must be invoked before any other function in the
321 library, with the exception of the @code{GCRYCTL_SET_THREAD_CBS} command
322 (called via the @code{gcry_control} function).
323 @xref{Multi-Threading}.
325 Furthermore, this function returns the version number of the library.
326 It can also verify that the version number is higher than a certain
327 required version number @var{req_version}, if this value is not a null
331 Libgcrypt uses a concept known as secure memory, which is a region of
332 memory set aside for storing sensitive data. Because such memory is a
333 scare resource, it needs to be setup in advanced to a fixed size.
334 Further, most operating systems have special requirements on how that
335 secure memory can be used. For example, it might be required to install
336 an application as ``setuid(root)'' to allow allocating such memory.
337 Libgcrypt requires a sequence of initialization steps to make sure that
338 this works correctly. The following examples show the necessary steps.
340 If you don't have a need for secure memory, for example if your
341 application does not use secret keys or other confidential data or it
342 runs in a controlled environment where key material floating around in
343 memory is not a problem, you should initialize Libgcrypt this way:
346 /* Version check should be the very first call because it
347 makes sure that important subsystems are intialized. */
348 if (!gcry_check_version (GCRYPT_VERSION))
350 fputs ("libgcrypt version mismatch\n", stderr);
354 /* Disable secure memory. */
355 gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
357 /* ... If required, other initialization goes here. */
359 /* Tell Libgcrypt that initialization has completed. */
360 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
364 If you have to protect your keys or other information in memory against
365 being swapped out to disk and to enable an automatic overwrite of used
366 and freed memory, you need to initialize Libgcrypt this way:
369 /* Version check should be the very first call because it
370 makes sure that important subsystems are intialized. */
371 if (!gcry_check_version (GCRYPT_VERSION))
373 fputs ("libgcrypt version mismatch\n", stderr);
377 @anchor{sample-use-suspend-secmem}
378 /* We don't want to see any warnings, e.g. because we have not yet
379 parsed program options which might be used to suppress such
381 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
383 /* ... If required, other initialization goes here. Note that the
384 process might still be running with increased privileges and that
385 the secure memory has not been intialized. */
387 /* Allocate a pool of 16k secure memory. This make the secure memory
388 available and also drops privileges where needed. */
389 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
391 @anchor{sample-use-resume-secmem}
392 /* It is now okay to let Libgcrypt complain when there was/is a problem
393 with the secure memory. */
394 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
396 /* ... If required, other initialization goes here. */
398 /* Tell Libgcrypt that initialization has completed. */
399 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
402 It is important that these initialization steps are not done by a
403 library but by the actual application. A library using Libgcrypt might
404 want to check for finished initialization using:
407 if (!gcry_control (GCRYCTL_INITIALIZATION_FINISHED_P))
409 fputs ("libgcrypt has not been initialized\n", stderr);
414 Instead of terminating the process, the library may instead print a
415 warning and try to initialize Libgcrypt itself. See also the section on
416 multi-threading below for more pitfalls.
420 @node Multi-Threading
421 @section Multi-Threading
423 As mentioned earlier, the Libgcrypt library is
424 thread-safe if you adhere to the following requirements:
428 If your application is multi-threaded, you must set the thread support
429 callbacks with the @code{GCRYCTL_SET_THREAD_CBS} command
430 @strong{before} any other function in the library.
432 This is easy enough if you are indeed writing an application using
433 Libgcrypt. It is rather problematic if you are writing a library
434 instead. Here are some tips what to do if you are writing a library:
436 If your library requires a certain thread package, just initialize
437 Libgcrypt to use this thread package. If your library supports multiple
438 thread packages, but needs to be configured, you will have to
439 implement a way to determine which thread package the application
440 wants to use with your library anyway. Then configure Libgcrypt to use
443 If your library is fully reentrant without any special support by a
444 thread package, then you are lucky indeed. Unfortunately, this does
445 not relieve you from doing either of the two above, or use a third
446 option. The third option is to let the application initialize Libgcrypt
447 for you. Then you are not using Libgcrypt transparently, though.
449 As if this was not difficult enough, a conflict may arise if two
450 libraries try to initialize Libgcrypt independently of each others, and
451 both such libraries are then linked into the same application. To
452 make it a bit simpler for you, this will probably work, but only if
453 both libraries have the same requirement for the thread package. This
454 is currently only supported for the non-threaded case, GNU Pth and
455 pthread. Support for more thread packages is easy to add, so contact
456 us if you require it.
459 The function @code{gcry_check_version} must be called before any other
460 function in the library, except the @code{GCRYCTL_SET_THREAD_CBS}
461 command (called via the @code{gcry_control} function), because it
462 initializes the thread support subsystem in Libgcrypt. To
463 achieve this in multi-threaded programs, you must synchronize the
464 memory with respect to other threads that also want to use
465 Libgcrypt. For this, it is sufficient to call
466 @code{gcry_check_version} before creating the other threads using
467 Libgcrypt@footnote{At least this is true for POSIX threads,
468 as @code{pthread_create} is a function that synchronizes memory with
469 respects to other threads. There are many functions which have this
470 property, a complete list can be found in POSIX, IEEE Std 1003.1-2003,
471 Base Definitions, Issue 6, in the definition of the term ``Memory
472 Synchronization''. For other thread packages, more relaxed or more
473 strict rules may apply.}.
477 Just like the function @code{gpg_strerror}, the function
478 @code{gcry_strerror} is not thread safe. You have to use
479 @code{gpg_strerror_r} instead.
483 Libgcrypt contains convenient macros, which define the
484 necessary thread callbacks for PThread and for GNU Pth:
487 @item GCRY_THREAD_OPTION_PTH_IMPL
489 This macro defines the following (static) symbols: gcry_pth_init,
490 gcry_pth_mutex_init, gcry_pth_mutex_destroy, gcry_pth_mutex_lock,
491 gcry_pth_mutex_unlock, gcry_pth_read, gcry_pth_write, gcry_pth_select,
492 gcry_pth_waitpid, gcry_pth_accept, gcry_pth_connect, gcry_threads_pth.
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_pth''.
498 @item GCRY_THREAD_OPTION_PTHREAD_IMPL
500 This macro defines the following (static) symbols:
501 gcry_pthread_mutex_init, gcry_pthread_mutex_destroy, gcry_mutex_lock,
502 gcry_mutex_unlock, gcry_threads_pthread.
504 After including this macro, gcry_control() shall be used with a
505 command of GCRYCTL_SET_THREAD_CBS in order to register the thread
506 callback structure named ``gcry_threads_pthread''.
509 Note that these macros need to be terminated with a semicolon. Keep
510 in mind that these are convenient macros for C programmers; C++
511 programmers might have to wrap these macros in an ``extern C'' body.
518 Libgcrypt may be used in a FIPS 140 mode. Note, that this does not
519 necessary mean that Libcgrypt is n appoved FIPS 140-2 module. Check the
520 NIST database at @url{http://csrc.nist.gov/groups/STM/cmvp/} to see what
521 versions of Libgcrypt are approved.
523 Because FIPS 140 has certain restrictions on the use of cryptography
524 which are not always wanted, Libgcrypt needs to be put into FIPS mode
525 explicitly. Three alternative mechanisms are provided to switch
526 Libgcrypt into this mode:
530 If the file @file{/proc/fips140} exists and contains the string value
531 @code{1}, Libgcrypt is put into FIPS mode at initialization time.
532 Obviously this works only on systems with a @code{proc} file system
536 If the file @file{/etc/gcrypt/fips140.force} exists, Libgcrypt is put
537 into FIPS mode at initialization time. Note that this filename is
538 hardwired and does not depend on any configuration options.
541 If the applications requests FIPS mode using the control command
542 @code{GCRYCTL_FORCE_FIPS_MODE}. This may be done at any time.
546 Note that once Libgcrypt has been put into FIPS mode, it is not possible
547 to switch back to standard mode without terminating the process first.
552 @c **********************************************************
553 @c ******************* General ****************************
554 @c **********************************************************
556 @chapter Generalities
559 * Controlling the library:: Controlling Libgcrypt's behavior.
560 * Modules:: Description of extension modules.
561 * Error Handling:: Error codes and such.
564 @node Controlling the library
565 @section Controlling the library
567 @deftypefun gcry_error_t gcry_control (enum gcry_ctl_cmds @var{cmd}, ...)
569 This function can be used to influence the general behavior of
570 Libgcrypt in several ways. Depending on @var{cmd}, more
571 arguments can or have to be provided.
574 @item GCRYCTL_ENABLE_M_GUARD; Arguments: none
575 This command enables the built-in memory guard. It must not be used to
576 activate the memory guard after the memory management has already been
577 used; therefore it can ONLY be used at initialization time. Note that
578 the memory guard is NOT used when the user of the library has set his
579 own memory management callbacks.
581 @item GCRYCTL_ENABLE_QUICK_RANDOM; Arguments: none
582 This command inhibits the use the very secure random quality level
583 (@code{GCRY_VERY_STRONG_RANDOM}) and degrades all request down to
584 @code{GCRY_STRONG_RANDOM}. In general this is not recommened. However,
585 for some applications the extra quality random Libgcrypt tries to create
586 is not justified and this option may help to get better performace.
587 Please check with a crypto expert whether this option can be used for
590 This option can only be used at initialization time.
593 @item GCRYCTL_DUMP_RANDOM_STATS; Arguments: none
594 This command dumps randum number generator related statistics to the
595 library's logging stream.
597 @item GCRYCTL_DUMP_MEMORY_STATS; Arguments: none
598 This command dumps memory managment related statistics to the library's
601 @item GCRYCTL_DUMP_SECMEM_STATS; Arguments: none
602 This command dumps secure memory manamgent related statistics to the
603 library's logging stream.
605 @item GCRYCTL_DROP_PRIVS; Arguments: none
606 This command disables the use of secure memory and drops the priviliges
607 of the current process. This command has not much use; the suggested way
608 to disable secure memory is to use @code{GCRYCTL_DISABLE_SECMEM} right
609 after initialization.
611 @item GCRYCTL_DISABLE_SECMEM; Arguments: none
612 This command disables the use of secure memory.
614 Many applications do not require secure memory, so they should disable
615 it right away. There won't be a problem if not disabling it unless one
616 makes use of a feature which requires secure memory - in that case the
617 process will abort because the secmem is not initialized. This command
618 should be executed right after @code{gcry_check_version}.
620 @item GCRYCTL_INIT_SECMEM; Arguments: int nbytes
621 This command is used to allocate a pool of secure memory and thus
622 enabling the use of secure memory. It also drops all extra privileges
623 the process has (i.e. if it is run as setuid (root)). If the argument
624 @var{nbytes} is 0, secure memory will be disabled. The minimum amount
625 of secure memory allocated is currently 16384 bytes; you may thus use a
626 value of 1 to request that default size.
628 @item GCRYCTL_TERM_SECMEM; Arguments: none
629 This command zeroises the secure memory and destroys the handler. The
630 secure memory pool may not be used anymore after running this command.
631 If the secure memory pool as already been destroyed, this command has no
632 effect. Applications might want to run this command from their exit
633 handler to make sure that the secure memory gets properly destroyed.
634 This command is not necessary thread-safe but that should not be needed
635 in cleanup code. It may be called from a signal handler.
637 @item GCRYCTL_DISABLE_SECMEM_WARN; Arguments: none
638 Disable warning messages about problems with the secure memory
639 subsystem. This command should be run right after
640 @code{gcry_check_version}.
642 @item GCRYCTL_SUSPEND_SECMEM_WARN; Arguments: none
643 Postpone warning messages from the secure memory subsystem.
644 @xref{sample-use-suspend-secmem,,the initialization example}, on how to
647 @item GCRYCTL_RESUME_SECMEM_WARN; Arguments: none
648 Resume warning messages from the secure memory subsystem.
649 @xref{sample-use-resume-secmem,,the initialization example}, on how to
652 @item GCRYCTL_USE_SECURE_RNDPOOL; Arguments: none
653 This command tells the PRNG to store random numbers in secure memory.
654 This command should be run right after @code{gcry_check_version} and not
655 later than the command GCRYCTL_INIT_SECMEM. Note that in FIPS mode the
656 secure memory is always used.
658 @item GCRYCTL_SET_RANDOM_SEED_FILE; Arguments: const char *filename
659 This command specifies the file, which is to be used as seed file for
660 the PRNG. If the seed file is registered prior to initialization of the
661 PRNG, the seed file's content (if it exists and seems to be valid) is
662 fed into the PRNG pool. After the seed file has been registered, the
663 PRNG can be signalled to write out the PRNG pool's content into the seed
664 file with the following command.
667 @item GCRYCTL_UPDATE_RANDOM_SEED_FILE; Arguments: none
668 Write out the PRNG pool's content into the registered seed file.
670 Multiple instances of the applications sharing the same random seed file
671 can be started in parallel, in which case they will read out the same
672 pool and then race for updating it (the last update overwrites earlier
673 updates). They will differentiate only by the weak entropy that is
674 added in read_seed_file based on the PID and clock, and up to 16 bytes
675 of weak random non-blockingly. The consequence is that the output of
676 these different instances is correlated to some extent. In a perfect
677 attack scenario, the attacker can control (or at least guess) the PID
678 and clock of the application, and drain the system's entropy pool to
679 reduce the "up to 16 bytes" above to 0. Then the dependencies of the
680 inital states of the pools are completely known. Note that this is not
681 an issue if random of @code{GCRY_VERY_STRONG_RANDOM} quality is
682 requested as in this case enough extra entropy gets mixed. It is also
683 not an issue when using Linux (rndlinux driver), because this one
684 guarantees to read full 16 bytes from /dev/urandom and thus there is no
685 way for an attacker without kernel access to conrol these 16 bytes.
687 @item GCRYCTL_SET_VERBOSITY; Arguments: int level
688 This command sets the verbosity of the logging. A level of 0 disables
689 all extra logging whereas positive numbers enable more verbose logging.
690 The level may be changed at any time but be aware that no memory
691 syncronization is done so the effect of this command might not
692 immediately show up in other threads.
694 @item GCRYCTL_SET_DEBUG_FLAGS; Arguments: unsigned int flags
695 Set the debug flag bits as given by the argument. Be aware that that no
696 memory syncronization is done so the effect of this command might not
697 immediately show up in other threads. The debug flags are not
698 considered part of the API and thus may change without notice. As of
699 now bit 0 enables debugging of cipher functions and bit 1 debugging of
700 multi-precision-integers.
702 @item GCRYCTL_CLEAR_DEBUG_FLAGS; Arguments: unsigned int flags
703 Set the debug flag bits as given by the argument. Be aware that that no
704 memory syncronization is done so the effect of this command might not
705 immediately show up in other threads.
707 @item GCRYCTL_DISABLE_INTERNAL_LOCKING; Arguments: none
708 This command does nothing. It exists only for backward compatibility.
710 @item GCRYCTL_ANY_INITIALIZATION_P; Arguments: none
711 This command returns true if the library has been basically initialized.
712 Such a basic initialization happens implicitly with many commands to get
713 certain internal subsystems running. The common and suggested way to
714 do this basic intialization is by calling gcry_check_version.
716 @item GCRYCTL_INITIALIZATION_FINISHED; Arguments: none
717 This command tells the libray that the application has finished the
720 @item GCRYCTL_INITIALIZATION_FINISHED_P; Arguments: none
721 This command returns true if the command@*
722 GCRYCTL_INITIALIZATION_FINISHED has already been run.
724 @item GCRYCTL_SET_THREAD_CBS; Arguments: struct ath_ops *ath_ops
725 This command registers a thread-callback structure.
726 @xref{Multi-Threading}.
728 @item GCRYCTL_FAST_POLL; Arguments: none
729 Run a fast random poll.
731 @item GCRYCTL_SET_RNDEGD_SOCKET; Arguments: const char *filename
732 This command may be used to override the default name of the EGD socket
733 to connect to. It may be used only during initialization as it is not
734 thread safe. Changing the socket name again is not supported. The
735 function may return an error if the given filename is too long for a
738 EGD is an alternative random gatherer, used only on systems lacking a
739 proper random device.
741 @item GCRYCTL_PRINT_CONFIG; Arguments: FILE *stream
742 This command dumps information pertaining to the configuration of the
743 library to the given stream. If NULL is given for @var{stream}, the log
744 system is used. This command may be used before the intialization has
745 been finished but not before a gcry_version_check.
747 @item GCRYCTL_OPERATIONAL_P; Arguments: none
748 This command returns true if the library is in an operational state.
749 This information makes only sense in FIPS mode. In contrast to other
750 functions, this is a pure test function and won't put the library into
751 FIPS mode or change the internal state. This command may be used before
752 the intialization has been finished but not before a gcry_version_check.
754 @item GCRYCTL_FIPS_MODE_P; Arguments: none
755 This command returns true if the library is in FIPS mode. Note, that
756 this is no indication about the current state of the library. This
757 command may be used before the intialization has been finished but not
758 before a gcry_version_check.
760 @item GCRYCTL_FORCE_FIPS_MODE; Arguments: none
761 Running this command puts the library into FIPS mode. If the library
762 has already been initialized or is already in FIPS mode, a selftest is
763 triggered and thus the library will be put into operational state. This
764 command may even be used before a call to gcry_check_version and that is
765 actually the recommended way to let an application switch the library
776 Libgcrypt supports the use of `extension modules', which
777 implement algorithms in addition to those already built into the library
780 @deftp {Data type} gcry_module_t
781 This data type represents a `module'.
784 Functions registering modules provided by the user take a `module
785 specification structure' as input and return a value of
786 @code{gcry_module_t} and an ID that is unique in the modules'
787 category. This ID can be used to reference the newly registered
788 module. After registering a module successfully, the new functionality
789 should be able to be used through the normal functions provided by
790 Libgcrypt until it is unregistered again.
792 @c **********************************************************
793 @c ******************* Errors ****************************
794 @c **********************************************************
796 @section Error Handling
798 Many functions in Libgcrypt can return an error if they
799 fail. For this reason, the application should always catch the error
800 condition and take appropriate measures, for example by releasing the
801 resources and passing the error up to the caller, or by displaying a
802 descriptive message to the user and cancelling the operation.
804 Some error values do not indicate a system error or an error in the
805 operation, but the result of an operation that failed properly. For
806 example, if you try to decrypt a tempered message, the decryption will
807 fail. Another error value actually means that the end of a data
808 buffer or list has been reached. The following descriptions explain
809 for many error codes what they mean usually. Some error values have
810 specific meanings if returned by a certain functions. Such cases are
811 described in the documentation of those functions.
813 Libgcrypt uses the @code{libgpg-error} library. This allows to share
814 the error codes with other components of the GnuPG system, and to pass
815 error values transparently from the crypto engine, or some helper
816 application of the crypto engine, to the user. This way no
817 information is lost. As a consequence, Libgcrypt does not use its own
818 identifiers for error codes, but uses those provided by
819 @code{libgpg-error}. They usually start with @code{GPG_ERR_}.
821 However, Libgcrypt does provide aliases for the functions
822 defined in libgpg-error, which might be preferred for name space
826 Most functions in Libgcrypt return an error code in the case
827 of failure. For this reason, the application should always catch the
828 error condition and take appropriate measures, for example by
829 releasing the resources and passing the error up to the caller, or by
830 displaying a descriptive message to the user and canceling the
833 Some error values do not indicate a system error or an error in the
834 operation, but the result of an operation that failed properly.
836 GnuPG components, including Libgcrypt, use an extra library named
837 libgpg-error to provide a common error handling scheme. For more
838 information on libgpg-error, see the according manual.
841 * Error Values:: The error value and what it means.
842 * Error Sources:: A list of important error sources.
843 * Error Codes:: A list of important error codes.
844 * Error Strings:: How to get a descriptive string from a value.
849 @subsection Error Values
852 @cindex error sources
854 @deftp {Data type} {gcry_err_code_t}
855 The @code{gcry_err_code_t} type is an alias for the
856 @code{libgpg-error} type @code{gpg_err_code_t}. The error code
857 indicates the type of an error, or the reason why an operation failed.
859 A list of important error codes can be found in the next section.
862 @deftp {Data type} {gcry_err_source_t}
863 The @code{gcry_err_source_t} type is an alias for the
864 @code{libgpg-error} type @code{gpg_err_source_t}. The error source
865 has not a precisely defined meaning. Sometimes it is the place where
866 the error happened, sometimes it is the place where an error was
867 encoded into an error value. Usually the error source will give an
868 indication to where to look for the problem. This is not always true,
869 but it is attempted to achieve this goal.
871 A list of important error sources can be found in the next section.
874 @deftp {Data type} {gcry_error_t}
875 The @code{gcry_error_t} type is an alias for the @code{libgpg-error}
876 type @code{gpg_error_t}. An error value like this has always two
877 components, an error code and an error source. Both together form the
880 Thus, the error value can not be directly compared against an error
881 code, but the accessor functions described below must be used.
882 However, it is guaranteed that only 0 is used to indicate success
883 (@code{GPG_ERR_NO_ERROR}), and that in this case all other parts of
884 the error value are set to 0, too.
886 Note that in Libgcrypt, the error source is used purely for
887 diagnostic purposes. Only the error code should be checked to test
888 for a certain outcome of a function. The manual only documents the
889 error code part of an error value. The error source is left
890 unspecified and might be anything.
893 @deftypefun {gcry_err_code_t} gcry_err_code (@w{gcry_error_t @var{err}})
894 The static inline function @code{gcry_err_code} returns the
895 @code{gcry_err_code_t} component of the error value @var{err}. This
896 function must be used to extract the error code from an error value in
897 order to compare it with the @code{GPG_ERR_*} error code macros.
900 @deftypefun {gcry_err_source_t} gcry_err_source (@w{gcry_error_t @var{err}})
901 The static inline function @code{gcry_err_source} returns the
902 @code{gcry_err_source_t} component of the error value @var{err}. This
903 function must be used to extract the error source from an error value in
904 order to compare it with the @code{GPG_ERR_SOURCE_*} error source macros.
907 @deftypefun {gcry_error_t} gcry_err_make (@w{gcry_err_source_t @var{source}}, @w{gcry_err_code_t @var{code}})
908 The static inline function @code{gcry_err_make} returns the error
909 value consisting of the error source @var{source} and the error code
912 This function can be used in callback functions to construct an error
913 value to return it to the library.
916 @deftypefun {gcry_error_t} gcry_error (@w{gcry_err_code_t @var{code}})
917 The static inline function @code{gcry_error} returns the error value
918 consisting of the default error source and the error code @var{code}.
920 For @acronym{GCRY} applications, the default error source is
921 @code{GPG_ERR_SOURCE_USER_1}. You can define
922 @code{GCRY_ERR_SOURCE_DEFAULT} before including @file{gcrypt.h} to
925 This function can be used in callback functions to construct an error
926 value to return it to the library.
929 The @code{libgpg-error} library provides error codes for all system
930 error numbers it knows about. If @var{err} is an unknown error
931 number, the error code @code{GPG_ERR_UNKNOWN_ERRNO} is used. The
932 following functions can be used to construct error values from system
935 @deftypefun {gcry_error_t} gcry_err_make_from_errno (@w{gcry_err_source_t @var{source}}, @w{int @var{err}})
936 The function @code{gcry_err_make_from_errno} is like
937 @code{gcry_err_make}, but it takes a system error like @code{errno}
938 instead of a @code{gcry_err_code_t} error code.
941 @deftypefun {gcry_error_t} gcry_error_from_errno (@w{int @var{err}})
942 The function @code{gcry_error_from_errno} is like @code{gcry_error},
943 but it takes a system error like @code{errno} instead of a
944 @code{gcry_err_code_t} error code.
947 Sometimes you might want to map system error numbers to error codes
948 directly, or map an error code representing a system error back to the
949 system error number. The following functions can be used to do that.
951 @deftypefun {gcry_err_code_t} gcry_err_code_from_errno (@w{int @var{err}})
952 The function @code{gcry_err_code_from_errno} returns the error code
953 for the system error @var{err}. If @var{err} is not a known system
954 error, the function returns @code{GPG_ERR_UNKNOWN_ERRNO}.
957 @deftypefun {int} gcry_err_code_to_errno (@w{gcry_err_code_t @var{err}})
958 The function @code{gcry_err_code_to_errno} returns the system error
959 for the error code @var{err}. If @var{err} is not an error code
960 representing a system error, or if this system error is not defined on
961 this system, the function returns @code{0}.
966 @subsection Error Sources
967 @cindex error codes, list of
969 The library @code{libgpg-error} defines an error source for every
970 component of the GnuPG system. The error source part of an error
971 value is not well defined. As such it is mainly useful to improve the
972 diagnostic error message for the user.
974 If the error code part of an error value is @code{0}, the whole error
975 value will be @code{0}. In this case the error source part is of
976 course @code{GPG_ERR_SOURCE_UNKNOWN}.
978 The list of error sources that might occur in applications using
979 @acronym{Libgcrypt} is:
982 @item GPG_ERR_SOURCE_UNKNOWN
983 The error source is not known. The value of this error source is
986 @item GPG_ERR_SOURCE_GPGME
987 The error source is @acronym{GPGME} itself.
989 @item GPG_ERR_SOURCE_GPG
990 The error source is GnuPG, which is the crypto engine used for the
993 @item GPG_ERR_SOURCE_GPGSM
994 The error source is GPGSM, which is the crypto engine used for the
997 @item GPG_ERR_SOURCE_GCRYPT
998 The error source is @code{libgcrypt}, which is used by crypto engines
999 to perform cryptographic operations.
1001 @item GPG_ERR_SOURCE_GPGAGENT
1002 The error source is @command{gpg-agent}, which is used by crypto
1003 engines to perform operations with the secret key.
1005 @item GPG_ERR_SOURCE_PINENTRY
1006 The error source is @command{pinentry}, which is used by
1007 @command{gpg-agent} to query the passphrase to unlock a secret key.
1009 @item GPG_ERR_SOURCE_SCD
1010 The error source is the SmartCard Daemon, which is used by
1011 @command{gpg-agent} to delegate operations with the secret key to a
1014 @item GPG_ERR_SOURCE_KEYBOX
1015 The error source is @code{libkbx}, a library used by the crypto
1016 engines to manage local keyrings.
1018 @item GPG_ERR_SOURCE_USER_1
1019 @item GPG_ERR_SOURCE_USER_2
1020 @item GPG_ERR_SOURCE_USER_3
1021 @item GPG_ERR_SOURCE_USER_4
1022 These error sources are not used by any GnuPG component and can be
1023 used by other software. For example, applications using
1024 Libgcrypt can use them to mark error values coming from callback
1025 handlers. Thus @code{GPG_ERR_SOURCE_USER_1} is the default for errors
1026 created with @code{gcry_error} and @code{gcry_error_from_errno},
1027 unless you define @code{GCRY_ERR_SOURCE_DEFAULT} before including
1033 @subsection Error Codes
1034 @cindex error codes, list of
1036 The library @code{libgpg-error} defines many error values. The
1037 following list includes the most important error codes.
1041 This value indicates the end of a list, buffer or file.
1043 @item GPG_ERR_NO_ERROR
1044 This value indicates success. The value of this error code is
1045 @code{0}. Also, it is guaranteed that an error value made from the
1046 error code @code{0} will be @code{0} itself (as a whole). This means
1047 that the error source information is lost for this error code,
1048 however, as this error code indicates that no error occurred, this is
1049 generally not a problem.
1051 @item GPG_ERR_GENERAL
1052 This value means that something went wrong, but either there is not
1053 enough information about the problem to return a more useful error
1054 value, or there is no separate error value for this type of problem.
1056 @item GPG_ERR_ENOMEM
1057 This value means that an out-of-memory condition occurred.
1060 System errors are mapped to GPG_ERR_EFOO where FOO is the symbol for
1063 @item GPG_ERR_INV_VALUE
1064 This value means that some user provided data was out of range.
1066 @item GPG_ERR_UNUSABLE_PUBKEY
1067 This value means that some recipients for a message were invalid.
1069 @item GPG_ERR_UNUSABLE_SECKEY
1070 This value means that some signers were invalid.
1072 @item GPG_ERR_NO_DATA
1073 This value means that data was expected where no data was found.
1075 @item GPG_ERR_CONFLICT
1076 This value means that a conflict of some sort occurred.
1078 @item GPG_ERR_NOT_IMPLEMENTED
1079 This value indicates that the specific function (or operation) is not
1080 implemented. This error should never happen. It can only occur if
1081 you use certain values or configuration options which do not work,
1082 but for which we think that they should work at some later time.
1084 @item GPG_ERR_DECRYPT_FAILED
1085 This value indicates that a decryption operation was unsuccessful.
1087 @item GPG_ERR_WRONG_KEY_USAGE
1088 This value indicates that a key is not used appropriately.
1090 @item GPG_ERR_NO_SECKEY
1091 This value indicates that no secret key for the user ID is available.
1093 @item GPG_ERR_UNSUPPORTED_ALGORITHM
1094 This value means a verification failed because the cryptographic
1095 algorithm is not supported by the crypto backend.
1097 @item GPG_ERR_BAD_SIGNATURE
1098 This value means a verification failed because the signature is bad.
1100 @item GPG_ERR_NO_PUBKEY
1101 This value means a verification failed because the public key is not
1104 @item GPG_ERR_NOT_OPERATIONAL
1105 This value means that the library is not yet in state which allows to
1106 use this function. This error code is in particular returned if
1107 Libgcrypt is operated in FIPS mode and the internal state of the
1108 library does not yet or not anymore allow the use of a service.
1110 This error code is only available with newer libgpg-error versions, thus
1111 you might see ``invalid error code'' when passing this to
1112 @code{gpg_strerror}. The numeric value of this error code is 176.
1114 @item GPG_ERR_USER_1
1115 @item GPG_ERR_USER_2
1117 @item GPG_ERR_USER_16
1118 These error codes are not used by any GnuPG component and can be
1119 freely used by other software. Applications using Libgcrypt
1120 might use them to mark specific errors returned by callback handlers
1121 if no suitable error codes (including the system errors) for these
1122 errors exist already.
1127 @subsection Error Strings
1128 @cindex error values, printing of
1129 @cindex error codes, printing of
1130 @cindex error sources, printing of
1131 @cindex error strings
1133 @deftypefun {const char *} gcry_strerror (@w{gcry_error_t @var{err}})
1134 The function @code{gcry_strerror} returns a pointer to a statically
1135 allocated string containing a description of the error code contained
1136 in the error value @var{err}. This string can be used to output a
1137 diagnostic message to the user.
1141 @deftypefun {const char *} gcry_strsource (@w{gcry_error_t @var{err}})
1142 The function @code{gcry_strerror} returns a pointer to a statically
1143 allocated string containing a description of the error source
1144 contained in the error value @var{err}. This string can be used to
1145 output a diagnostic message to the user.
1148 The following example illustrates the use of the functions described
1153 gcry_cipher_hd_t handle;
1154 gcry_error_t err = 0;
1156 err = gcry_cipher_open (&handle, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, 0);
1159 fprintf (stderr, "Failure: %s/%s\n",
1160 gcry_strsource (err),
1161 gcry_strerror (err));
1166 @c **********************************************************
1167 @c ******************* General ****************************
1168 @c **********************************************************
1169 @node Handler Functions
1170 @chapter Handler Functions
1172 Libgcrypt makes it possible to install so called `handler functions',
1173 which get called by Libgcrypt in case of certain events.
1176 * Progress handler:: Using a progress handler function.
1177 * Allocation handler:: Using special memory allocation functions.
1178 * Error handler:: Using error handler functions.
1179 * Logging handler:: Using a special logging function.
1182 @node Progress handler
1183 @section Progress handler
1185 It is often useful to retrieve some feedback while long running
1186 operations are performed.
1188 @deftp {Data type} gcry_handler_progress_t
1189 Progress handler functions have to be of the type
1190 @code{gcry_handler_progress_t}, which is defined as:
1192 @code{void (*gcry_handler_progress_t) (void *, const char *, int, int, int)}
1195 The following function may be used to register a handler function for
1198 @deftypefun void gcry_set_progress_handler (gcry_handler_progress_t @var{cb}, void *@var{cb_data})
1200 This function installs @var{cb} as the `Progress handler' function.
1201 @var{cb} must be defined as follows:
1205 my_progress_handler (void *@var{cb_data}, const char *@var{what},
1206 int @var{printchar}, int @var{current}, int @var{total})
1212 A description of the arguments of the progress handler function follows.
1216 The argument provided in the call to @code{gcry_set_progress_handler}.
1218 A string identifying the type of the progress output. The following
1219 values for @var{what} are defined:
1223 Not enough entropy is available. @var{total} holds the number of
1227 Values for @var{printchar}:
1232 Need to refresh the pool of prime numbers.
1234 Number of bits adjusted.
1236 Searching for a generator.
1238 Fermat test on 10 candidates failed.
1240 Restart with a new random value.
1242 Rabin Miller test passed.
1250 @node Allocation handler
1251 @section Allocation handler
1253 It is possible to make Libgcrypt use special memory
1254 allocation functions instead of the built-in ones.
1256 Memory allocation functions are of the following types:
1257 @deftp {Data type} gcry_handler_alloc_t
1258 This type is defined as: @code{void *(*gcry_handler_alloc_t) (size_t n)}.
1260 @deftp {Data type} gcry_handler_secure_check_t
1261 This type is defined as: @code{int *(*gcry_handler_secure_check_t) (const void *)}.
1263 @deftp {Data type} gcry_handler_realloc_t
1264 This type is defined as: @code{void *(*gcry_handler_realloc_t) (void *p, size_t n)}.
1266 @deftp {Data type} gcry_handler_free_t
1267 This type is defined as: @code{void *(*gcry_handler_free_t) (void *)}.
1270 Special memory allocation functions can be installed with the
1273 @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})
1274 Install the provided functions and use them instead of the built-in
1275 functions for doing memory allocation.
1279 @section Error handler
1281 The following functions may be used to register handler functions that
1282 are called by Libgcrypt in case certain error conditions
1285 @deftp {Data type} gcry_handler_no_mem_t
1286 This type is defined as: @code{void (*gcry_handler_no_mem_t) (void *, size_t, unsigned int)}
1288 @deftypefun void gcry_set_outofcore_handler (gcry_handler_no_mem_t @var{func_no_mem}, void *@var{cb_data})
1289 This function registers @var{func_no_mem} as `out-of-core handler',
1290 which means that it will be called in the case of not having enough
1294 @deftp {Data type} gcry_handler_error_t
1295 This type is defined as: @code{void (*gcry_handler_error_t) (void *, int, const char *)}
1298 @deftypefun void gcry_set_fatalerror_handler (gcry_handler_error_t @var{func_error}, void *@var{cb_data})
1299 This function registers @var{func_error} as `error handler',
1300 which means that it will be called in error conditions.
1303 @node Logging handler
1304 @section Logging handler
1306 @deftp {Data type} gcry_handler_log_t
1307 This type is defined as: @code{void (*gcry_handler_log_t) (void *, int, const char *, va_list)}
1310 @deftypefun void gcry_set_log_handler (gcry_handler_log_t @var{func_log}, void *@var{cb_data})
1311 This function registers @var{func_log} as `logging handler', which
1312 means that it will be called in case Libgcrypt wants to log
1316 @c **********************************************************
1317 @c ******************* Ciphers ****************************
1318 @c **********************************************************
1319 @c @include cipher-ref.texi
1320 @node Symmetric cryptography
1321 @chapter Symmetric cryptography
1323 The cipher functions are used for symmetrical cryptography,
1324 i.e. cryptography using a shared key. The programming model follows
1325 an open/process/close paradigm and is in that similar to other
1326 building blocks provided by Libgcrypt.
1329 * Available ciphers:: List of ciphers supported by the library.
1330 * Cipher modules:: How to work with cipher modules.
1331 * Available cipher modes:: List of cipher modes supported by the library.
1332 * Working with cipher handles:: How to perform operations related to cipher handles.
1333 * General cipher functions:: General cipher functions independent of cipher handles.
1336 @node Available ciphers
1337 @section Available ciphers
1340 @item GCRY_CIPHER_NONE
1341 This is not a real algorithm but used by some functions as error return.
1342 The value always evaluates to false.
1344 @item GCRY_CIPHER_IDEA
1345 This is the IDEA algorithm. The constant is provided but there is
1346 currently no implementation for it because the algorithm is patented.
1348 @item GCRY_CIPHER_3DES
1349 Triple-DES with 3 Keys as EDE. The key size of this algorithm is 168 but
1350 you have to pass 192 bits because the most significant bits of each byte
1353 @item GCRY_CIPHER_CAST5
1354 CAST128-5 block cipher algorithm. The key size is 128 bits.
1356 @item GCRY_CIPHER_BLOWFISH
1357 The blowfish algorithm. The current implementation allows only for a key
1360 @item GCRY_CIPHER_SAFER_SK128
1361 Reserved and not currently implemented.
1363 @item GCRY_CIPHER_DES_SK
1364 Reserved and not currently implemented.
1366 @item GCRY_CIPHER_AES
1367 @itemx GCRY_CIPHER_AES128
1368 @itemx GCRY_CIPHER_RIJNDAEL
1369 @itemx GCRY_CIPHER_RIJNDAEL128
1370 AES (Rijndael) with a 128 bit key.
1372 @item GCRY_CIPHER_AES192
1373 @itemx GCRY_CIPHER_RIJNDAEL192
1374 AES (Rijndael) with a 192 bit key.
1376 @item GCRY_CIPHER_AES256
1377 @itemx GCRY_CIPHER_RIJNDAEL256
1378 AES (Rijndael) with a 256 bit key.
1380 @item GCRY_CIPHER_TWOFISH
1381 The Twofish algorithm with a 256 bit key.
1383 @item GCRY_CIPHER_TWOFISH128
1384 The Twofish algorithm with a 128 bit key.
1386 @item GCRY_CIPHER_ARCFOUR
1387 An algorithm which is 100% compatible with RSA Inc.'s RC4 algorithm.
1388 Note that this is a stream cipher and must be used very carefully to
1389 avoid a couple of weaknesses.
1391 @item GCRY_CIPHER_DES
1392 Standard DES with a 56 bit key. You need to pass 64 bit but the high
1393 bits of each byte are ignored. Note, that this is a weak algorithm
1394 which can be broken in reasonable time using a brute force approach.
1396 @item GCRY_CIPHER_SERPENT128
1397 @itemx GCRY_CIPHER_SERPENT192
1398 @itemx GCRY_CIPHER_SERPENT256
1399 The Serpent cipher from the AES contest.
1401 @item GCRY_CIPHER_RFC2268_40
1402 @itemx GCRY_CIPHER_RFC2268_128
1403 Ron's Cipher 2 in the 40 and 128 bit variants. Note, that we currently
1404 only support the 40 bit variant. The identifier for 128 is reserved for
1407 @item GCRY_CIPHER_SEED
1408 A 128 bit cipher as described by RFC4269.
1410 @item GCRY_CIPHER_CAMELLIA128
1411 @itemx GCRY_CIPHER_CAMELLIA192
1412 @itemx GCRY_CIPHER_CAMELLIA256
1413 The Camellia cipher by NTT. See
1414 @uref{http://info.isl.ntt.co.jp/@/crypt/@/eng/@/camellia/@/specifications.html}.
1418 @node Cipher modules
1419 @section Cipher modules
1421 Libgcrypt makes it possible to load additional `cipher modules'; these
1422 ciphers can be used just like the cipher algorithms that are built
1423 into the library directly. For an introduction into extension
1424 modules, see @xref{Modules}.
1426 @deftp {Data type} gcry_cipher_spec_t
1427 This is the `module specification structure' needed for registering
1428 cipher modules, which has to be filled in by the user before it can be
1429 used to register a module. It contains the following members:
1432 @item const char *name
1433 The primary name of the algorithm.
1434 @item const char **aliases
1435 A list of strings that are `aliases' for the algorithm. The list must
1436 be terminated with a NULL element.
1437 @item gcry_cipher_oid_spec_t *oids
1438 A list of OIDs that are to be associated with the algorithm. The
1439 list's last element must have it's `oid' member set to NULL. See
1440 below for an explanation of this type.
1441 @item size_t blocksize
1442 The block size of the algorithm, in bytes.
1444 The length of the key, in bits.
1445 @item size_t contextsize
1446 The size of the algorithm-specific `context', that should be allocated
1448 @item gcry_cipher_setkey_t setkey
1449 The function responsible for initializing a handle with a provided
1450 key. See below for a description of this type.
1451 @item gcry_cipher_encrypt_t encrypt
1452 The function responsible for encrypting a single block. See below for
1453 a description of this type.
1454 @item gcry_cipher_decrypt_t decrypt
1455 The function responsible for decrypting a single block. See below for
1456 a description of this type.
1457 @item gcry_cipher_stencrypt_t stencrypt
1458 Like `encrypt', for stream ciphers. See below for a description of
1460 @item gcry_cipher_stdecrypt_t stdecrypt
1461 Like `decrypt', for stream ciphers. See below for a description of
1466 @deftp {Data type} gcry_cipher_oid_spec_t
1467 This type is used for associating a user-provided algorithm
1468 implementation with certain OIDs. It contains the following members:
1470 @item const char *oid
1471 Textual representation of the OID.
1473 Cipher mode for which this OID is valid.
1477 @deftp {Data type} gcry_cipher_setkey_t
1478 Type for the `setkey' function, defined as: gcry_err_code_t
1479 (*gcry_cipher_setkey_t) (void *c, const unsigned char *key, unsigned
1483 @deftp {Data type} gcry_cipher_encrypt_t
1484 Type for the `encrypt' function, defined as: gcry_err_code_t
1485 (*gcry_cipher_encrypt_t) (void *c, const unsigned char *outbuf, const
1486 unsigned char *inbuf)
1489 @deftp {Data type} gcry_cipher_decrypt_t
1490 Type for the `decrypt' function, defined as: gcry_err_code_t
1491 (*gcry_cipher_decrypt_t) (void *c, const unsigned char *outbuf, const
1492 unsigned char *inbuf)
1495 @deftp {Data type} gcry_cipher_stencrypt_t
1496 Type for the `stencrypt' function, defined as: gcry_err_code_t
1497 (*gcry_cipher_stencrypt_t) (void *c, const unsigned char *outbuf, const
1498 unsigned char *, unsigned int n)
1501 @deftp {Data type} gcry_cipher_stdecrypt_t
1502 Type for the `stdecrypt' function, defined as: gcry_err_code_t
1503 (*gcry_cipher_stdecrypt_t) (void *c, const unsigned char *outbuf, const
1504 unsigned char *, unsigned int n)
1507 @deftypefun gcry_error_t gcry_cipher_register (gcry_cipher_spec_t *@var{cipher}, unsigned int *algorithm_id, gcry_module_t *@var{module})
1509 Register a new cipher module whose specification can be found in
1510 @var{cipher}. On success, a new algorithm ID is stored in
1511 @var{algorithm_id} and a pointer representing this module is stored
1515 @deftypefun void gcry_cipher_unregister (gcry_module_t @var{module})
1516 Unregister the cipher identified by @var{module}, which must have been
1517 registered with gcry_cipher_register.
1520 @deftypefun gcry_error_t gcry_cipher_list (int *@var{list}, int *@var{list_length})
1521 Get a list consisting of the IDs of the loaded cipher modules. If
1522 @var{list} is zero, write the number of loaded cipher modules to
1523 @var{list_length} and return. If @var{list} is non-zero, the first
1524 *@var{list_length} algorithm IDs are stored in @var{list}, which must
1525 be of according size. In case there are less cipher modules than
1526 *@var{list_length}, *@var{list_length} is updated to the correct
1530 @node Available cipher modes
1531 @section Available cipher modes
1534 @item GCRY_CIPHER_MODE_NONE
1535 No mode specified, may be set later using other functions. The value
1536 of this constant is always 0.
1538 @item GCRY_CIPHER_MODE_ECB
1539 Electronic Codebook mode.
1541 @item GCRY_CIPHER_MODE_CFB
1542 Cipher Feedback mode.
1544 @item GCRY_CIPHER_MODE_CBC
1545 Cipher Block Chaining mode.
1547 @item GCRY_CIPHER_MODE_STREAM
1548 Stream mode, only to be used with stream cipher algorithms.
1550 @item GCRY_CIPHER_MODE_OFB
1551 Output Feedback mode.
1553 @item GCRY_CIPHER_MODE_CTR
1558 @node Working with cipher handles
1559 @section Working with cipher handles
1561 To use a cipher algorithm, you must first allocate an according
1562 handle. This is to be done using the open function:
1564 @deftypefun gcry_error_t gcry_cipher_open (gcry_cipher_hd_t *@var{hd}, int @var{algo}, int @var{mode}, unsigned int @var{flags})
1566 This function creates the context handle required for most of the
1567 other cipher functions and returns a handle to it in `hd'. In case of
1568 an error, an according error code is returned.
1570 The ID of algorithm to use must be specified via @var{algo}. See
1571 @xref{Available ciphers}, for a list of supported ciphers and the
1572 according constants.
1574 Besides using the constants directly, the function
1575 @code{gcry_cipher_map_name} may be used to convert the textual name of
1576 an algorithm into the according numeric ID.
1578 The cipher mode to use must be specified via @var{mode}. See
1579 @xref{Available cipher modes}, for a list of supported cipher modes
1580 and the according constants. Note that some modes are incompatible
1581 with some algorithms - in particular, stream mode
1582 (GCRY_CIPHER_MODE_STREAM) only works with stream ciphers. Any block
1583 cipher mode (GCRY_CIPHER_MODE_ECB, GCRY_CIPHER_MODE_CBC,
1584 GCRY_CIPHER_MODE_CFB, GCRY_CIPHER_MODE_OFB or GCRY_CIPHER_MODE_CTR)
1585 will work with any block cipher algorithm.
1587 The third argument @var{flags} can either be passed as @code{0} or as
1588 the bit-wise OR of the following constants.
1591 @item GCRY_CIPHER_SECURE
1592 Make sure that all operations are allocated in secure memory. This is
1593 useful when the key material is highly confidential.
1594 @item GCRY_CIPHER_ENABLE_SYNC
1595 This flag enables the CFB sync mode, which is a special feature of
1596 Libgcrypt's CFB mode implementation to allow for OpenPGP's CFB variant.
1597 See @code{gcry_cipher_sync}.
1598 @item GCRY_CIPHER_CBC_CTS
1599 Enable cipher text stealing (CTS) for the CBC mode. Cannot be used
1600 simultaneous as GCRY_CIPHER_CBC_MAC. CTS mode makes it possible to
1601 transform data of almost arbitrary size (only limitation is that it
1602 must be greater than the algorithm's block size).
1603 @item GCRY_CIPHER_CBC_MAC
1604 Compute CBC-MAC keyed checksums. This is the same as CBC mode, but
1605 only output the last block. Cannot be used simultaneous as
1606 GCRY_CIPHER_CBC_CTS.
1610 Use the following function to release an existing handle:
1612 @deftypefun void gcry_cipher_close (gcry_cipher_hd_t @var{h})
1614 This function releases the context created by @code{gcry_cipher_open}.
1617 In order to use a handle for performing cryptographic operations, a
1618 `key' has to be set first:
1620 @deftypefun gcry_error_t gcry_cipher_setkey (gcry_cipher_hd_t @var{h}, const void *@var{k}, size_t @var{l})
1622 Set the key @var{k} used for encryption or decryption in the context
1623 denoted by the handle @var{h}. The length @var{l} of the key @var{k}
1624 must match the required length of the algorithm set for this context or
1625 be in the allowed range for algorithms with variable key size. The
1626 function checks this and returns an error if there is a problem. A
1627 caller should always check for an error.
1631 Most crypto modes requires an initialization vector (IV), which
1632 usually is a non-secret random string acting as a kind of salt value.
1633 The CTR mode requires a counter, which is also similar to a salt
1634 value. To set the IV or CTR, use these functions:
1636 @deftypefun gcry_error_t gcry_cipher_setiv (gcry_cipher_hd_t @var{h}, const void *@var{k}, size_t @var{l})
1638 Set the initialization vector used for encryption or decryption. The
1639 vector is passed as the buffer @var{K} of length @var{l} and copied to
1640 internal data structures. The function checks that the IV matches the
1641 requirement of the selected algorithm and mode.
1644 @deftypefun gcry_error_t gcry_cipher_setctr (gcry_cipher_hd_t @var{h}, const void *@var{c}, size_t @var{l})
1646 Set the counter vector used for encryption or decryption. The counter
1647 is passed as the buffer @var{c} of length @var{l} and copied to
1648 internal data structures. The function checks that the counter
1649 matches the requirement of the selected algorithm (i.e., it must be
1650 the same size as the block size).
1653 @deftypefun gcry_error_t gcry_cipher_reset (gcry_cipher_hd_t @var{h})
1655 Set the given handle's context back to the state it had after the last
1656 call to gcry_cipher_setkey and clear the initialization vector.
1658 Note that gcry_cipher_reset is implemented as a macro.
1661 The actual encryption and decryption is done by using one of the
1662 following functions. They may be used as often as required to process
1665 @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})
1667 @code{gcry_cipher_encrypt} is used to encrypt the data. This function
1668 can either work in place or with two buffers. It uses the cipher
1669 context already setup and described by the handle @var{h}. There are 2
1670 ways to use the function: If @var{in} is passed as @code{NULL} and
1671 @var{inlen} is @code{0}, in-place encryption of the data in @var{out} or
1672 length @var{outsize} takes place. With @var{in} being not @code{NULL},
1673 @var{inlen} bytes are encrypted to the buffer @var{out} which must have
1674 at least a size of @var{inlen}. @var{outsize} must be set to the
1675 allocated size of @var{out}, so that the function can check that there
1676 is sufficient space. Note that overlapping buffers are not allowed.
1678 Depending on the selected algorithms and encryption mode, the length of
1679 the buffers must be a multiple of the block size.
1681 The function returns @code{0} on success or an error code.
1685 @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})
1687 @code{gcry_cipher_decrypt} is used to decrypt the data. This function
1688 can either work in place or with two buffers. It uses the cipher
1689 context already setup and described by the handle @var{h}. There are 2
1690 ways to use the function: If @var{in} is passed as @code{NULL} and
1691 @var{inlen} is @code{0}, in-place decryption of the data in @var{out} or
1692 length @var{outsize} takes place. With @var{in} being not @code{NULL},
1693 @var{inlen} bytes are decrypted to the buffer @var{out} which must have
1694 at least a size of @var{inlen}. @var{outsize} must be set to the
1695 allocated size of @var{out}, so that the function can check that there
1696 is sufficient space. Note that overlapping buffers are not allowed.
1698 Depending on the selected algorithms and encryption mode, the length of
1699 the buffers must be a multiple of the block size.
1701 The function returns @code{0} on success or an error code.
1705 OpenPGP (as defined in RFC-2440) requires a special sync operation in
1706 some places. The following function is used for this:
1708 @deftypefun gcry_error_t gcry_cipher_sync (gcry_cipher_hd_t @var{h})
1710 Perform the OpenPGP sync operation on context @var{h}. Note that this
1711 is a no-op unless the context was created with the flag
1712 @code{GCRY_CIPHER_ENABLE_SYNC}
1715 Some of the described functions are implemented as macros utilizing a
1716 catch-all control function. This control function is rarely used
1717 directly but there is nothing which would inhibit it:
1719 @deftypefun gcry_error_t gcry_cipher_ctl (gcry_cipher_hd_t @var{h}, int @var{cmd}, void *@var{buffer}, size_t @var{buflen})
1721 @code{gcry_cipher_ctl} controls various aspects of the cipher module and
1722 specific cipher contexts. Usually some more specialized functions or
1723 macros are used for this purpose. The semantics of the function and its
1724 parameters depends on the the command @var{cmd} and the passed context
1725 handle @var{h}. Please see the comments in the source code
1726 (@code{src/global.c}) for details.
1729 @deftypefun gcry_error_t gcry_cipher_info (gcry_cipher_hd_t @var{h}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes})
1731 @code{gcry_cipher_info} is used to retrieve various
1732 information about a cipher context or the cipher module in general.
1734 Currently no information is available.
1737 @node General cipher functions
1738 @section General cipher functions
1740 To work with the algorithms, several functions are available to map
1741 algorithm names to the internal identifiers, as well as ways to
1742 retrieve information about an algorithm or the current cipher context.
1744 @deftypefun gcry_error_t gcry_cipher_algo_info (int @var{algo}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes})
1746 This function is used to retrieve information on a specific algorithm.
1747 You pass the cipher algorithm ID as @var{algo} and the type of
1748 information requested as @var{what}. The result is either returned as
1749 the return code of the function or copied to the provided @var{buffer}
1750 whose allocated length must be available in an integer variable with the
1751 address passed in @var{nbytes}. This variable will also receive the
1752 actual used length of the buffer.
1754 Here is a list of supported codes for @var{what}:
1756 @c begin constants for gcry_cipher_algo_info
1758 @item GCRYCTL_GET_KEYLEN:
1759 Return the length of the key. If the algorithm supports multiple key
1760 lengths, the maximum supported value is returned. The length is
1761 returned as number of octets (bytes) and not as number of bits in
1762 @var{nbytes}; @var{buffer} must be zero.
1764 @item GCRYCTL_GET_BLKLEN:
1765 Return the block length of the algorithm. The length is returned as a
1766 number of octets in @var{nbytes}; @var{buffer} must be zero.
1768 @item GCRYCTL_TEST_ALGO:
1769 Returns @code{0} when the specified algorithm is available for use.
1770 @var{buffer} and @var{nbytes} must be zero.
1773 @c end constants for gcry_cipher_algo_info
1776 @c end gcry_cipher_algo_info
1778 @deftypefun const char *gcry_cipher_algo_name (int @var{algo})
1780 @code{gcry_cipher_algo_name} returns a string with the name of the
1781 cipher algorithm @var{algo}. If the algorithm is not known or another
1782 error occurred, the string @code{"?"} is returned. This function should
1783 not be used to test for the availability of an algorithm.
1786 @deftypefun int gcry_cipher_map_name (const char *@var{name})
1788 @code{gcry_cipher_map_name} returns the algorithm identifier for the
1789 cipher algorithm described by the string @var{name}. If this algorithm
1790 is not available @code{0} is returned.
1793 @deftypefun int gcry_cipher_mode_from_oid (const char *@var{string})
1795 Return the cipher mode associated with an @acronym{ASN.1} object
1796 identifier. The object identifier is expected to be in the
1797 @acronym{IETF}-style dotted decimal notation. The function returns
1798 @code{0} for an unknown object identifier or when no mode is associated
1803 @c **********************************************************
1804 @c ******************* Public Key *************************
1805 @c **********************************************************
1806 @node Public Key cryptography
1807 @chapter Public Key cryptography
1809 Public key cryptography, also known as asymmetric cryptography, is an
1810 easy way for key management and to provide digital signatures.
1811 Libgcrypt provides two completely different interfaces to
1812 public key cryptography, this chapter explains the one based on
1816 * Available algorithms:: Algorithms supported by the library.
1817 * Used S-expressions:: Introduction into the used S-expression.
1818 * Public key modules:: How to work with public key modules.
1819 * Cryptographic Functions:: Functions for performing the cryptographic actions.
1820 * General public-key related Functions:: General functions, not implementing any cryptography.
1822 * AC Interface:: Alternative interface to public key functions.
1825 @node Available algorithms
1826 @section Available algorithms
1828 Libgcrypt supports the RSA (Rivest-Shamir-Adleman) algorithms as well
1829 as DSA (Digital Signature Algorithm) and Elgamal. The versatile
1830 interface allows to add more algorithms in the future.
1832 @node Used S-expressions
1833 @section Used S-expressions
1835 Libgcrypt's API for asymmetric cryptography is based on data structures
1836 called S-expressions (see
1837 @uref{http://people.csail.mit.edu/@/rivest/@/sexp.html}) and does not work
1838 with contexts as most of the other building blocks of Libgcrypt do.
1840 The following information are stored in S-expressions:
1845 @item plain text data
1847 @item encrypted data
1854 To describe how Libgcrypt expect keys, we use examples. Note that
1862 indicate parameters whereas lowercase words are literals.
1864 Note that all MPI (multi-precision-integers) values are expected to be in
1865 @code{GCRYMPI_FMT_USG} format. An easy way to create S-expressions is
1866 by using @code{gcry_sexp_build} which allows to pass a string with
1867 printf-like escapes to insert MPI values.
1870 * RSA key parameters:: Parameters used with an RSA key.
1871 * DSA key parameters:: Parameters used with a DSA key.
1872 * ECC key parameters:: Parameters used with ECC keys.
1875 @node RSA key parameters
1876 @subsection RSA key parameters
1879 An RSA private key is described by this S-expression:
1893 An RSA public key is described by this S-expression:
1905 RSA public modulus @math{n}.
1907 RSA public exponent @math{e}.
1909 RSA secret exponent @math{d = e^{-1} \bmod (p-1)(q-1)}.
1911 RSA secret prime @math{p}.
1913 RSA secret prime @math{q} with @math{p < q}.
1915 Multiplicative inverse @math{u = p^{-1} \bmod q}.
1918 For signing and decryption the parameters @math{(p, q, u)} are optional
1919 but greatly improve the performance. Either all of these optional
1920 parameters must be given or none of them. They are mandatory for
1923 Note that OpenSSL uses slighly different parameters: @math{q < p} and
1924 @math{u = q^{-1} \bmod p}. To use these parameters you will need to
1925 swap the values and recompute @math{u}. Here is example code to do this:
1928 if (gcry_mpi_cmp (p, q) > 0)
1930 gcry_mpi_swap (p, q);
1931 gcry_mpi_invm (u, p, q);
1938 @node DSA key parameters
1939 @subsection DSA key parameters
1942 A DSA private key is described by this S-expression:
1958 DSA group order @math{q} (which is a prime divisor of @math{p-1}).
1960 DSA group generator @math{g}.
1962 DSA public key value @math{y = g^x \bmod p}.
1964 DSA secret exponent x.
1967 The public key is similar with "private-key" replaced by "public-key"
1971 @node ECC key parameters
1972 @subsection ECC key parameters
1975 An ECC private key is described by this S-expression:
1991 Prime specifying the field @math{GF(p)}.
1994 The two coefficients of the Weierstrass equation @math{y^2 = x^3 + ax + b}
1996 Base point @math{g}.
2000 The point representing the public key @math{Q = dP}.
2002 The private key @math{d}
2005 All point values are encoded in standard format; Libgcrypt does
2006 currently only support uncompressed points, thus the first byte needs to
2009 The public key is similar with "private-key" replaced by "public-key"
2012 If the domain parameters are well-known, the name of this curve may be
2018 (curve "NIST P-192")
2023 The @code{curve} parameter may be given in any case and is used to replace
2027 Currently implemented curves are:
2030 @itemx 1.2.840.10045.3.1.1
2033 The NIST 192 bit curve, its OID, X9.62 and SECP aliases.
2037 The NIST 224 bit curve and its SECP alias.
2040 @itemx 1.2.840.10045.3.1.7
2043 The NIST 256 bit curve, its OID, X9.62 and SECP aliases.
2047 The NIST 384 bit curve and its SECP alias.
2051 The NIST 521 bit curve and its SECP alias.
2054 As usual the OIDs may optionally be prefixed with the string @code{OID.}
2059 @node Public key modules
2060 @section Public key modules
2062 Libgcrypt makes it possible to load additional `public key
2063 modules'; these public key algorithms can be used just like the
2064 algorithms that are built into the library directly. For an
2065 introduction into extension modules, see @xref{Modules}.
2067 @deftp {Data type} gcry_pk_spec_t
2068 This is the `module specification structure' needed for registering
2069 public key modules, which has to be filled in by the user before it
2070 can be used to register a module. It contains the following members:
2073 @item const char *name
2074 The primary name of this algorithm.
2075 @item char **aliases
2076 A list of strings that are `aliases' for the algorithm. The list
2077 must be terminated with a NULL element.
2078 @item const char *elements_pkey
2079 String containing the one-letter names of the MPI values contained in
2081 @item const char *element_skey
2082 String containing the one-letter names of the MPI values contained in
2084 @item const char *elements_enc
2085 String containing the one-letter names of the MPI values that are the
2086 result of an encryption operation using this algorithm.
2087 @item const char *elements_sig
2088 String containing the one-letter names of the MPI values that are the
2089 result of a sign operation using this algorithm.
2090 @item const char *elements_grip
2091 String containing the one-letter names of the MPI values that are to
2092 be included in the `key grip'.
2094 The bitwise-OR of the following flags, depending on the abilities of
2097 @item GCRY_PK_USAGE_SIGN
2098 The algorithm supports signing and verifying of data.
2099 @item GCRY_PK_USAGE_ENCR
2100 The algorithm supports the encryption and decryption of data.
2102 @item gcry_pk_generate_t generate
2103 The function responsible for generating a new key pair. See below for
2104 a description of this type.
2105 @item gcry_pk_check_secret_key_t check_secret_key
2106 The function responsible for checking the sanity of a provided secret
2107 key. See below for a description of this type.
2108 @item gcry_pk_encrypt_t encrypt
2109 The function responsible for encrypting data. See below for a
2110 description of this type.
2111 @item gcry_pk_decrypt_t decrypt
2112 The function responsible for decrypting data. See below for a
2113 description of this type.
2114 @item gcry_pk_sign_t sign
2115 The function responsible for signing data. See below for a description
2117 @item gcry_pk_verify_t verify
2118 The function responsible for verifying that the provided signature
2119 matches the provided data. See below for a description of this type.
2120 @item gcry_pk_get_nbits_t get_nbits
2121 The function responsible for returning the number of bits of a provided
2122 key. See below for a description of this type.
2126 @deftp {Data type} gcry_pk_generate_t
2127 Type for the `generate' function, defined as: gcry_err_code_t
2128 (*gcry_pk_generate_t) (int algo, unsigned int nbits, unsigned long
2129 use_e, gcry_mpi_t *skey, gcry_mpi_t **retfactors)
2132 @deftp {Data type} gcry_pk_check_secret_key_t
2133 Type for the `check_secret_key' function, defined as: gcry_err_code_t
2134 (*gcry_pk_check_secret_key_t) (int algo, gcry_mpi_t *skey)
2137 @deftp {Data type} gcry_pk_encrypt_t
2138 Type for the `encrypt' function, defined as: gcry_err_code_t
2139 (*gcry_pk_encrypt_t) (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
2140 gcry_mpi_t *pkey, int flags)
2143 @deftp {Data type} gcry_pk_decrypt_t
2144 Type for the `decrypt' function, defined as: gcry_err_code_t
2145 (*gcry_pk_decrypt_t) (int algo, gcry_mpi_t *result, gcry_mpi_t *data,
2146 gcry_mpi_t *skey, int flags)
2149 @deftp {Data type} gcry_pk_sign_t
2150 Type for the `sign' function, defined as: gcry_err_code_t
2151 (*gcry_pk_sign_t) (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
2155 @deftp {Data type} gcry_pk_verify_t
2156 Type for the `verify' function, defined as: gcry_err_code_t
2157 (*gcry_pk_verify_t) (int algo, gcry_mpi_t hash, gcry_mpi_t *data,
2158 gcry_mpi_t *pkey, int (*cmp) (void *, gcry_mpi_t), void *opaquev)
2161 @deftp {Data type} gcry_pk_get_nbits_t
2162 Type for the `get_nbits' function, defined as: unsigned
2163 (*gcry_pk_get_nbits_t) (int algo, gcry_mpi_t *pkey)
2166 @deftypefun gcry_error_t gcry_pk_register (gcry_pk_spec_t *@var{pubkey}, unsigned int *algorithm_id, gcry_module_t *@var{module})
2168 Register a new public key module whose specification can be found in
2169 @var{pubkey}. On success, a new algorithm ID is stored in
2170 @var{algorithm_id} and a pointer representing this module is stored
2174 @deftypefun void gcry_pk_unregister (gcry_module_t @var{module})
2175 Unregister the public key module identified by @var{module}, which
2176 must have been registered with gcry_pk_register.
2179 @deftypefun gcry_error_t gcry_pk_list (int *@var{list}, int *@var{list_length})
2180 Get a list consisting of the IDs of the loaded pubkey modules. If
2181 @var{list} is zero, write the number of loaded pubkey modules to
2182 @var{list_length} and return. If @var{list} is non-zero, the first
2183 *@var{list_length} algorithm IDs are stored in @var{list}, which must
2184 be of according size. In case there are less pubkey modules than
2185 *@var{list_length}, *@var{list_length} is updated to the correct
2189 @node Cryptographic Functions
2190 @section Cryptographic Functions
2193 Note that we will in future allow to use keys without p,q and u
2194 specified and may also support other parameters for performance
2199 Some functions operating on S-expressions support `flags', that
2200 influence the operation. These flags have to be listed in a
2201 sub-S-expression named `flags'; the following flags are known:
2205 Use PKCS#1 block type 2 padding.
2207 Do not use a technique called `blinding', which is used by default in
2208 order to prevent leaking of secret information. Blinding is only
2209 implemented by RSA, but it might be implemented by other algorithms in
2210 the future as well, when necessary.
2214 Now that we know the key basics, we can carry on and explain how to
2215 encrypt and decrypt data. In almost all cases the data is a random
2216 session key which is in turn used for the actual encryption of the real
2217 data. There are 2 functions to do this:
2219 @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}})
2221 Obviously a public key must be provided for encryption. It is
2222 expected as an appropriate S-expression (see above) in @var{pkey}.
2223 The data to be encrypted can either be in the simple old format, which
2224 is a very simple S-expression consisting only of one MPI, or it may be
2225 a more complex S-expression which also allows to specify flags for
2226 operation, like e.g. padding rules.
2229 If you don't want to let Libgcrypt handle the padding, you must pass an
2230 appropriate MPI using this expression for @var{data}:
2239 This has the same semantics as the old style MPI only way. @var{MPI} is
2240 the actual data, already padded appropriate for your protocol. Most
2241 systems however use PKCS#1 padding and so you can use this S-expression
2247 (value @var{block}))
2251 Here, the "flags" list has the "pkcs1" flag which let the function know
2252 that it should provide PKCS#1 block type 2 padding. The actual data to
2253 be encrypted is passed as a string of octets in @var{block}. The
2254 function checks that this data actually can be used with the given key,
2255 does the padding and encrypts it.
2257 If the function could successfully perform the encryption, the return
2258 value will be 0 and a a new S-expression with the encrypted result is
2259 allocated and assigned to the variable at the address of @var{r_ciph}.
2260 The caller is responsible to release this value using
2261 @code{gcry_sexp_release}. In case of an error, an error code is
2262 returned and @var{r_ciph} will be set to @code{NULL}.
2265 The returned S-expression has this format when used with RSA:
2274 Where @var{a-mpi} is an MPI with the result of the RSA operation. When
2275 using the Elgamal algorithm, the return value will have this format:
2285 Where @var{a-mpi} and @var{b-mpi} are MPIs with the result of the
2286 Elgamal encryption operation.
2288 @c end gcry_pk_encrypt
2290 @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}})
2292 Obviously a private key must be provided for decryption. It is expected
2293 as an appropriate S-expression (see above) in @var{skey}. The data to
2294 be decrypted must match the format of the result as returned by
2295 @code{gcry_pk_encrypt}, but should be enlarged with a @code{flags}
2307 Note that this function currently does not know of any padding
2308 methods and the caller must do any un-padding on his own.
2311 The function returns 0 on success or an error code. The variable at the
2312 address of @var{r_plain} will be set to NULL on error or receive the
2313 decrypted value on success. The format of @var{r_plain} is a
2314 simple S-expression part (i.e. not a valid one) with just one MPI if
2315 there was no @code{flags} element in @var{data}; if at least an empty
2316 @code{flags} is passed in @var{data}, the format is:
2319 (value @var{plaintext})
2322 @c end gcry_pk_decrypt
2325 Another operation commonly performed using public key cryptography is
2326 signing data. In some sense this is even more important than
2327 encryption because digital signatures are an important instrument for
2328 key management. Libgcrypt supports digital signatures using
2329 2 functions, similar to the encryption functions:
2331 @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}})
2333 This function creates a digital signature for @var{data} using the
2334 private key @var{skey} and place it into the variable at the address of
2335 @var{r_sig}. @var{data} may either be the simple old style S-expression
2336 with just one MPI or a modern and more versatile S-expression which
2337 allows to let Libgcrypt handle padding:
2342 (hash @var{hash-algo} @var{block}))
2346 This example requests to sign the data in @var{block} after applying
2347 PKCS#1 block type 1 style padding. @var{hash-algo} is a string with the
2348 hash algorithm to be encoded into the signature, this may be any hash
2349 algorithm name as supported by Libgcrypt. Most likely, this will be
2350 "sha1", "rmd160" or "md5". It is obvious that the length of @var{block}
2351 must match the size of that message digests; the function checks that
2352 this and other constraints are valid.
2355 If PKCS#1 padding is not required (because the caller does already
2356 provide a padded value), either the old format or better the following
2357 format should be used:
2366 Here, the data to be signed is directly given as an @var{MPI}.
2369 The signature is returned as a newly allocated S-expression in
2370 @var{r_sig} using this format for RSA:
2378 Where @var{s-mpi} is the result of the RSA sign operation. For DSA the
2379 S-expression returned is:
2388 Where @var{r-mpi} and @var{s-mpi} are the result of the DSA sign
2389 operation. For Elgamal signing (which is slow, yields large numbers
2390 and probably is not as secure as the other algorithms), the same format is
2391 used with "elg" replacing "dsa".
2396 The operation most commonly used is definitely the verification of a
2397 signature. Libgcrypt provides this function:
2399 @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}})
2401 This is used to check whether the signature @var{sig} matches the
2402 @var{data}. The public key @var{pkey} must be provided to perform this
2403 verification. This function is similar in its parameters to
2404 @code{gcry_pk_sign} with the exceptions that the public key is used
2405 instead of the private key and that no signature is created but a
2406 signature, in a format as created by @code{gcry_pk_sign}, is passed to
2407 the function in @var{sig}.
2410 The result is 0 for success (i.e. the data matches the signature), or an
2411 error code where the most relevant code is @code{GCRYERR_BAD_SIGNATURE}
2412 to indicate that the signature does not match the provided data.
2415 @c end gcry_pk_verify
2417 @node General public-key related Functions
2418 @section General public-key related Functions
2421 A couple of utility functions are available to retrieve the length of
2422 the key, map algorithm identifiers and perform sanity checks:
2424 @deftypefun {const char *} gcry_pk_algo_name (int @var{algo})
2426 Map the public key algorithm id @var{algo} to a string representation of
2427 the algorithm name. For unknown algorithms this functions returns the
2428 string @code{"?"}. This function should not be used to test for the
2429 availability of an algorithm.
2432 @deftypefun int gcry_pk_map_name (const char *@var{name})
2434 Map the algorithm @var{name} to a public key algorithm Id. Returns 0 if
2435 the algorithm name is not known.
2438 @deftypefun int gcry_pk_test_algo (int @var{algo})
2440 Return 0 if the public key algorithm @var{algo} is available for use.
2441 Note that this is implemented as a macro.
2445 @deftypefun {unsigned int} gcry_pk_get_nbits (gcry_sexp_t @var{key})
2447 Return what is commonly referred as the key length for the given
2448 public or private in @var{key}.
2451 @deftypefun {unsigned char *} gcry_pk_get_keygrip (@w{gcry_sexp_t @var{key}}, @w{unsigned char *@var{array}})
2453 Return the so called "keygrip" which is the SHA-1 hash of the public key
2454 parameters expressed in a way depended on the algorithm. @var{array}
2455 must either provide space for 20 bytes or be @code{NULL}. In the latter
2456 case a newly allocated array of that size is returned. On success a
2457 pointer to the newly allocated space or to @var{array} is returned.
2458 @code{NULL} is returned to indicate an error which is most likely an
2459 unknown algorithm or one where a "keygrip" has not yet been defined.
2460 The function accepts public or secret keys in @var{key}.
2463 @deftypefun gcry_error_t gcry_pk_testkey (gcry_sexp_t @var{key})
2465 Return zero if the private key @var{key} is `sane', an error code otherwise.
2466 Note that it is not possible to check the `saneness' of a public key.
2471 @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}})
2473 Depending on the value of @var{what} return various information about
2474 the public key algorithm with the id @var{algo}. Note that the
2475 function returns @code{-1} on error and the actual error code must be
2476 retrieved using the function @code{gcry_errno}. The currently defined
2477 values for @var{what} are:
2480 @item GCRYCTL_TEST_ALGO:
2481 Return 0 if the specified algorithm is available for use.
2482 @var{buffer} must be @code{NULL}, @var{nbytes} may be passed as
2483 @code{NULL} or point to a variable with the required usage of the
2484 algorithm. This may be 0 for "don't care" or the bit-wise OR of these
2488 @item GCRY_PK_USAGE_SIGN
2489 Algorithm is usable for signing.
2490 @item GCRY_PK_USAGE_ENCR
2491 Algorithm is usable for encryption.
2494 Unless you need to test for the allowed usage, it is in general better
2495 to use the macro gcry_pk_test_algo instead.
2497 @item GCRYCTL_GET_ALGO_USAGE:
2498 Return the usage flags for the given algorithm. An invalid algorithm
2499 return 0. Disabled algorithms are ignored here because we
2500 want to know whether the algorithm is at all capable of a certain usage.
2502 @item GCRYCTL_GET_ALGO_NPKEY
2503 Return the number of elements the public key for algorithm @var{algo}
2504 consist of. Return 0 for an unknown algorithm.
2506 @item GCRYCTL_GET_ALGO_NSKEY
2507 Return the number of elements the private key for algorithm @var{algo}
2508 consist of. Note that this value is always larger than that of the
2509 public key. Return 0 for an unknown algorithm.
2511 @item GCRYCTL_GET_ALGO_NSIGN
2512 Return the number of elements a signature created with the algorithm
2513 @var{algo} consists of. Return 0 for an unknown algorithm or for an
2514 algorithm not capable of creating signatures.
2516 @item GCRYCTL_GET_ALGO_NENC
2517 Return the number of elements a encrypted message created with the algorithm
2518 @var{algo} consists of. Return 0 for an unknown algorithm or for an
2519 algorithm not capable of encryption.
2523 Please note that parameters not required should be passed as @code{NULL}.
2525 @c end gcry_pk_algo_info
2528 @deftypefun gcry_error_t gcry_pk_ctl (@w{int @var{cmd}}, @w{void *@var{buffer}}, @w{size_t @var{buflen}})
2530 This is a general purpose function to perform certain control
2531 operations. @var{cmd} controls what is to be done. The return value is
2532 0 for success or an error code. Currently supported values for
2536 @item GCRYCTL_DISABLE_ALGO
2537 Disable the algorithm given as an algorithm id in @var{buffer}.
2538 @var{buffer} must point to an @code{int} variable with the algorithm id
2539 and @var{buflen} must have the value @code{sizeof (int)}.
2546 Libgcrypt also provides a function for generating public key
2549 @deftypefun gcry_error_t gcry_pk_genkey (@w{gcry_sexp_t *@var{r_key}}, @w{gcry_sexp_t @var{parms}})
2551 This function create a new public key pair using information given in
2552 the S-expression @var{parms} and stores the private and the public key
2553 in one new S-expression at the address given by @var{r_key}. In case of
2554 an error, @var{r_key} is set to @code{NULL}. The return code is 0 for
2555 success or an error code otherwise.
2558 Here is an example for @var{parms} for creating a 1024 bit RSA key:
2567 To create an Elgamal key, substitute "elg" for "rsa" and to create a DSA
2568 key use "dsa". Valid ranges for the key length depend on the
2569 algorithms; all commonly used key lengths are supported. Currently
2570 supported parameters are:
2574 This is always required to specify the length of the key. The argument
2575 is a string with a number in C-notation. The value should be a multiple
2578 @item curve @var{name}
2579 For ECC a named curve may be used instead of giving the number of
2580 requested bits. This allows to request a specific curve to override a
2581 default selection Libgcrypt would have taken if @code{nbits} has been
2582 given. The available names are listed with the description of the ECC
2583 public key parameters.
2586 This is only used with RSA to give a hint for the public exponent. The
2587 value will be used as a base to test for a usable exponent. Some values
2592 Use a secure and fast value. This is currently the number 41.
2594 Use a secure value as required by some specification. This is currently
2601 If this parameter is not used, Libgcrypt uses for historic reasons
2605 This is only meanigful for DSA keys. If it is given the DSA key is
2606 generated with a Q parameyer of this size. If it is not given or zero
2607 Q is deduced from NBITS in this way:
2609 @item 512 <= N <= 1024
2620 Note that in this case only the values for N, as given in the table,
2621 are allowed. When specifying Q all values of N in the range 512 to
2622 15680 are valid as long as they are multiples of 8.
2625 @c end table of parameters
2628 The key pair is returned in a format depending on the algorithm. Both
2629 private and public keys are returned in one container and may be
2630 accompanied by some miscellaneous information.
2633 As an example, here is what the Elgamal key generation returns:
2649 (pm1-factors @var{n1 n2 ... nn})))
2653 As you can see, some of the information is duplicated, but this provides
2654 an easy way to extract either the public or the private key. Note that
2655 the order of the elements is not defined, e.g. the private key may be
2656 stored before the public key. @var{n1 n2 ... nn} is a list of prime
2657 numbers used to composite @var{p-mpi}; this is in general not a very
2660 @c end gcry_pk_genkey
2663 @section Alternative Public Key Interface
2665 This section documents the alternative interface to asymmetric
2666 cryptography (ac) that is not based on S-expressions, but on native C
2667 data structures. As opposed to the pk interface described in the
2668 former chapter, this one follows an open/use/close paradigm like other
2669 building blocks of the library.
2671 @strong{This interface has a few known problems; most noteworthy an
2672 inherent tendency to leak memory. It might not be available in
2673 forthcoming versions Libgcrypt.}
2677 * Available asymmetric algorithms:: List of algorithms supported by the library.
2678 * Working with sets of data:: How to work with sets of data.
2679 * Working with IO objects:: How to work with IO objects.
2680 * Working with handles:: How to use handles.
2681 * Working with keys:: How to work with keys.
2682 * Using cryptographic functions:: How to perform cryptographic operations.
2683 * Handle-independent functions:: General functions independent of handles.
2686 @node Available asymmetric algorithms
2687 @subsection Available asymmetric algorithms
2689 Libgcrypt supports the RSA (Rivest-Shamir-Adleman)
2690 algorithms as well as DSA (Digital Signature Algorithm) and Elgamal.
2691 The versatile interface allows to add more algorithms in the future.
2693 @deftp {Data type} gcry_ac_id_t
2695 The following constants are defined for this type:
2699 Rivest-Shamir-Adleman
2701 Digital Signature Algorithm
2705 Elgamal, encryption only.
2709 @node Working with sets of data
2710 @subsection Working with sets of data
2712 In the context of this interface the term `data set' refers to a list
2713 of `named MPI values' that is used by functions performing
2714 cryptographic operations; a named MPI value is a an MPI value,
2715 associated with a label.
2717 Such data sets are used for representing keys, since keys simply
2718 consist of a variable amount of numbers. Furthermore some functions
2719 return data sets to the caller that are to be provided to other
2722 This section documents the data types, symbols and functions that are
2723 relevant for working with data sets.
2725 @deftp {Data type} gcry_ac_data_t
2729 The following flags are supported:
2732 @item GCRY_AC_FLAG_DEALLOC
2733 Used for storing data in a data set. If given, the data will be
2734 released by the library. Note that whenever one of the ac functions
2735 is about to release objects because of this flag, the objects are
2736 expected to be stored in memory allocated through the Libgcrypt memory
2737 management. In other words: gcry_free() is used instead of free().
2739 @item GCRY_AC_FLAG_COPY
2740 Used for storing/retrieving data in/from a data set. If given, the
2741 library will create copies of the provided/contained data, which will
2742 then be given to the user/associated with the data set.
2745 @deftypefun gcry_error_t gcry_ac_data_new (gcry_ac_data_t *@var{data})
2746 Creates a new, empty data set and stores it in @var{data}.
2749 @deftypefun void gcry_ac_data_destroy (gcry_ac_data_t @var{data})
2750 Destroys the data set @var{data}.
2753 @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})
2754 Add the value @var{mpi} to @var{data} with the label @var{name}. If
2755 @var{flags} contains GCRY_AC_FLAG_COPY, the data set will contain
2756 copies of @var{name} and @var{mpi}. If @var{flags} contains
2757 GCRY_AC_FLAG_DEALLOC or GCRY_AC_FLAG_COPY, the values
2758 contained in the data set will be deallocated when they are to be
2759 removed from the data set.
2762 @deftypefun gcry_error_t gcry_ac_data_copy (gcry_ac_data_t *@var{data_cp}, gcry_ac_data_t @var{data})
2763 Create a copy of the data set @var{data} and store it in
2764 @var{data_cp}. FIXME: exact semantics undefined.
2767 @deftypefun unsigned int gcry_ac_data_length (gcry_ac_data_t @var{data})
2768 Returns the number of named MPI values inside of the data set
2772 @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})
2773 Store the value labelled with @var{name} found in @var{data} in
2774 @var{mpi}. If @var{flags} contains GCRY_AC_FLAG_COPY, store a copy of
2775 the @var{mpi} value contained in the data set. @var{mpi} may be NULL
2776 (this might be useful for checking the existence of an MPI with
2780 @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})
2781 Stores in @var{name} and @var{mpi} the named @var{mpi} value contained
2782 in the data set @var{data} with the index @var{idx}. If @var{flags}
2783 contains GCRY_AC_FLAG_COPY, store copies of the values contained in
2784 the data set. @var{name} or @var{mpi} may be NULL.
2787 @deftypefun void gcry_ac_data_clear (gcry_ac_data_t @var{data})
2788 Destroys any values contained in the data set @var{data}.
2791 @deftypefun gcry_error_t gcry_ac_data_to_sexp (gcry_ac_data_t @var{data}, gcry_sexp_t *@var{sexp}, const char **@var{identifiers})
2792 This function converts the data set @var{data} into a newly created
2793 S-Expression, which is to be stored in @var{sexp}; @var{identifiers}
2794 is a NULL terminated list of C strings, which specifies the structure
2795 of the S-Expression.
2799 If @var{identifiers} is a list of pointers to the strings ``foo'' and
2800 ``bar'' and if @var{data} is a data set containing the values ``val1 =
2801 0x01'' and ``val2 = 0x02'', then the resulting S-Expression will look
2802 like this: (foo (bar ((val1 0x01) (val2 0x02))).
2805 @deftypefun gcry_error gcry_ac_data_from_sexp (gcry_ac_data_t *@var{data}, gcry_sexp_t @var{sexp}, const char **@var{identifiers})
2806 This function converts the S-Expression @var{sexp} into a newly
2807 created data set, which is to be stored in @var{data};
2808 @var{identifiers} is a NULL terminated list of C strings, which
2809 specifies the structure of the S-Expression. If the list of
2810 identifiers does not match the structure of the S-Expression, the
2814 @node Working with IO objects
2815 @subsection Working with IO objects
2817 Note: IO objects are currently only used in the context of message
2818 encoding/decoding and encryption/signature schemes.
2820 @deftp {Data type} {gcry_ac_io_t}
2821 @code{gcry_ac_io_t} is the type to be used for IO objects.
2824 IO objects provide an uniform IO layer on top of different underlying
2825 IO mechanisms; either they can be used for providing data to the
2826 library (mode is GCRY_AC_IO_READABLE) or they can be used for
2827 retrieving data from the library (mode is GCRY_AC_IO_WRITABLE).
2829 IO object need to be initialized by calling on of the following
2832 @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}, ...);
2833 Initialize @var{ac_io} according to @var{mode}, @var{type} and the
2834 variable list of arguments. The list of variable arguments to specify
2835 depends on the given @var{type}.
2838 @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});
2839 Initialize @var{ac_io} according to @var{mode}, @var{type} and the
2840 variable list of arguments @var{ap}. The list of variable arguments
2841 to specify depends on the given @var{type}.
2844 The following types of IO objects exist:
2847 @item GCRY_AC_IO_STRING
2848 In case of GCRY_AC_IO_READABLE the IO object will provide data from a
2849 memory string. Arguments to specify at initialization time:
2851 @item unsigned char *
2852 Pointer to the beginning of the memory string
2854 Size of the memory string
2856 In case of GCRY_AC_IO_WRITABLE the object will store retrieved data in
2857 a newly allocated memory string. Arguments to specify at
2858 initialization time:
2860 @item unsigned char **
2861 Pointer to address, at which the pointer to the newly created memory
2862 string is to be stored
2864 Pointer to address, at which the size of the newly created memory
2865 string is to be stored
2868 @item GCRY_AC_IO_CALLBACK
2869 In case of GCRY_AC_IO_READABLE the object will forward read requests
2870 to a provided callback function. Arguments to specify at
2871 initialization time:
2873 @item gcry_ac_data_read_cb_t
2874 Callback function to use
2876 Opaque argument to provide to the callback function
2878 In case of GCRY_AC_IO_WRITABLE the object will forward write requests
2879 to a provided callback function. Arguments to specify at
2880 initialization time:
2882 @item gcry_ac_data_write_cb_t
2883 Callback function to use
2885 Opaque argument to provide to the callback function
2889 @node Working with handles
2890 @subsection Working with handles
2892 In order to use an algorithm, an according handle must be created.
2893 This is done using the following function:
2895 @deftypefun gcry_error_t gcry_ac_open (gcry_ac_handle_t *@var{handle}, int @var{algorithm}, int @var{flags})
2897 Creates a new handle for the algorithm @var{algorithm} and stores it
2898 in @var{handle}. @var{flags} is not used currently.
2900 @var{algorithm} must be a valid algorithm ID, see @xref{Available
2901 asymmetric algorithms}, for a list of supported algorithms and the
2902 according constants. Besides using the listed constants directly, the
2903 functions @code{gcry_pk_name_to_id} may be used to convert the textual
2904 name of an algorithm into the according numeric ID.
2907 @deftypefun void gcry_ac_close (gcry_ac_handle_t @var{handle})
2908 Destroys the handle @var{handle}.
2911 @node Working with keys
2912 @subsection Working with keys
2914 @deftp {Data type} gcry_ac_key_type_t
2918 @item GCRY_AC_KEY_SECRET
2919 Specifies a secret key.
2920 @item GCRY_AC_KEY_PUBLIC
2921 Specifies a public key.
2925 @deftp {Data type} gcry_ac_key_t
2926 This type represents a single `key', either a secret one or a public
2930 @deftp {Data type} gcry_ac_key_pair_t
2931 This type represents a `key pair' containing a secret and a public key.
2934 Key data structures can be created in two different ways; a new key
2935 pair can be generated, resulting in ready-to-use key. Alternatively a
2936 key can be initialized from a given data set.
2938 @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})
2939 Creates a new key of type @var{type}, consisting of the MPI values
2940 contained in the data set @var{data} and stores it in @var{key}.
2943 @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})
2945 Generates a new key pair via the handle @var{handle} of @var{NBITS}
2946 bits and stores it in @var{key_pair}.
2948 In case non-standard settings are wanted, a pointer to a structure of
2949 type @code{gcry_ac_key_spec_<algorithm>_t}, matching the selected
2950 algorithm, can be given as @var{key_spec}. @var{misc_data} is not
2951 used yet. Such a structure does only exist for RSA. A description
2952 of the members of the supported structures follows.
2955 @item gcry_ac_key_spec_rsa_t
2958 Generate the key pair using a special @code{e}. The value of @code{e}
2959 has the following meanings:
2962 Let Libgcrypt decide what exponent should be used.
2964 Request the use of a ``secure'' exponent; this is required by some
2965 specification to be 65537.
2967 Try starting at this value until a working exponent is found. Note
2968 that the current implementation leaks some information about the
2969 private key because the incrementation used is not randomized. Thus,
2970 this function will be changed in the future to return a random
2971 exponent of the given size.
2979 gcry_ac_key_pair_t key_pair;
2980 gcry_ac_key_spec_rsa_t rsa_spec;
2982 rsa_spec.e = gcry_mpi_new (0);
2983 gcry_mpi_set_ui (rsa_spec.e, 1);
2985 err = gcry_ac_open (&handle, GCRY_AC_RSA, 0);
2988 err = gcry_ac_key_pair_generate (handle, 1024, &rsa_spec, &key_pair, NULL);
2995 @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})
2996 Returns the key of type @var{which} out of the key pair
3000 @deftypefun void gcry_ac_key_destroy (gcry_ac_key_t @var{key})
3001 Destroys the key @var{key}.
3004 @deftypefun void gcry_ac_key_pair_destroy (gcry_ac_key_pair_t @var{key_pair})
3005 Destroys the key pair @var{key_pair}.
3008 @deftypefun gcry_ac_data_t gcry_ac_key_data_get (gcry_ac_key_t @var{key})
3009 Returns the data set contained in the key @var{key}.
3012 @deftypefun gcry_error_t gcry_ac_key_test (gcry_ac_handle_t @var{handle}, gcry_ac_key_t @var{key})
3013 Verifies that the private key @var{key} is sane via @var{handle}.
3016 @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})
3017 Stores the number of bits of the key @var{key} in @var{nbits} via @var{handle}.
3020 @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})
3021 Writes the 20 byte long key grip of the key @var{key} to
3022 @var{key_grip} via @var{handle}.
3025 @node Using cryptographic functions
3026 @subsection Using cryptographic functions
3028 The following flags might be relevant:
3031 @item GCRY_AC_FLAG_NO_BLINDING
3032 Disable any blinding, which might be supported by the chosen
3033 algorithm; blinding is the default.
3036 There exist two kinds of cryptographic functions available through the
3037 ac interface: primitives, and high-level functions.
3039 Primitives deal with MPIs (data sets) directly; what they provide is
3040 direct access to the cryptographic operations provided by an algorithm
3043 High-level functions deal with octet strings, according to a specified
3044 ``scheme''. Schemes make use of ``encoding methods'', which are
3045 responsible for converting the provided octet strings into MPIs, which
3046 are then forwared to the cryptographic primitives. Since schemes are
3047 to be used for a special purpose in order to achieve a particular
3048 security goal, there exist ``encryption schemes'' and ``signature
3049 schemes''. Encoding methods can be used seperately or implicitly
3052 What follows is a description of the cryptographic primitives.
3054 @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})
3055 Encrypts the plain text MPI value @var{data_plain} with the key public
3056 @var{key} under the control of the flags @var{flags} and stores the
3057 resulting data set into @var{data_encrypted}.
3060 @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})
3061 Decrypts the encrypted data contained in the data set
3062 @var{data_encrypted} with the secret key KEY under the control of the
3063 flags @var{flags} and stores the resulting plain text MPI value in
3067 @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})
3068 Signs the data contained in @var{data} with the secret key @var{key}
3069 and stores the resulting signature in the data set
3070 @var{data_signature}.
3073 @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})
3074 Verifies that the signature contained in the data set
3075 @var{data_signature} is indeed the result of signing the data
3076 contained in @var{data} with the secret key belonging to the public
3080 What follows is a description of the high-level functions.
3082 The type ``gcry_ac_em_t'' is used for specifying encoding methods; the
3083 following methods are supported:
3086 @item GCRY_AC_EME_PKCS_V1_5
3087 PKCS-V1_5 Encoding Method for Encryption. Options must be provided
3088 through a pointer to a correctly initialized object of type
3089 gcry_ac_eme_pkcs_v1_5_t.
3091 @item GCRY_AC_EMSA_PKCS_V1_5
3092 PKCS-V1_5 Encoding Method for Signatures with Appendix. Options must
3093 be provided through a pointer to a correctly initialized object of
3094 type gcry_ac_emsa_pkcs_v1_5_t.
3097 Option structure types:
3100 @item gcry_ac_eme_pkcs_v1_5_t
3102 @item gcry_ac_key_t key
3103 @item gcry_ac_handle_t handle
3105 @item gcry_ac_emsa_pkcs_v1_5_t
3107 @item gcry_md_algo_t md
3112 Encoding methods can be used directly through the following functions:
3114 @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})
3115 Encodes the message contained in @var{m} of size @var{m_n} according
3116 to @var{method}, @var{flags} and @var{options}. The newly created
3117 encoded message is stored in @var{em} and @var{em_n}.
3120 @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})
3121 Decodes the message contained in @var{em} of size @var{em_n} according
3122 to @var{method}, @var{flags} and @var{options}. The newly created
3123 decoded message is stored in @var{m} and @var{m_n}.
3126 The type ``gcry_ac_scheme_t'' is used for specifying schemes; the
3127 following schemes are supported:
3130 @item GCRY_AC_ES_PKCS_V1_5
3131 PKCS-V1_5 Encryption Scheme. No options can be provided.
3132 @item GCRY_AC_SSA_PKCS_V1_5
3133 PKCS-V1_5 Signature Scheme (with Appendix). Options can be provided
3134 through a pointer to a correctly initialized object of type
3135 gcry_ac_ssa_pkcs_v1_5_t.
3138 Option structure types:
3141 @item gcry_ac_ssa_pkcs_v1_5_t
3143 @item gcry_md_algo_t md
3147 The functions implementing schemes:
3149 @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})
3150 Encrypts the plain text readable from @var{io_message} through
3151 @var{handle} with the public key @var{key} according to @var{scheme},
3152 @var{flags} and @var{opts}. If @var{opts} is not NULL, it has to be a
3153 pointer to a structure specific to the chosen scheme (gcry_ac_es_*_t).
3154 The encrypted message is written to @var{io_cipher}.
3157 @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})
3158 Decrypts the cipher text readable from @var{io_cipher} through
3159 @var{handle} with the secret key @var{key} according to @var{scheme},
3160 @var{flags} and @var{opts}. If @var{opts} is not NULL, it has to be a
3161 pointer to a structure specific to the chosen scheme (gcry_ac_es_*_t).
3162 The decrypted message is written to @var{io_message}.
3165 @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})
3166 Signs the message readable from @var{io_message} through @var{handle}
3167 with the secret key @var{key} according to @var{scheme}, @var{flags}
3168 and @var{opts}. If @var{opts} is not NULL, it has to be a pointer to
3169 a structure specific to the chosen scheme (gcry_ac_ssa_*_t). The
3170 signature is written to @var{io_signature}.
3173 @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})
3174 Verifies through @var{handle} that the signature readable from
3175 @var{io_signature} is indeed the result of signing the message
3176 readable from @var{io_message} with the secret key belonging to the
3177 public key @var{key} according to @var{scheme} and @var{opts}. If
3178 @var{opts} is not NULL, it has to be an anonymous structure
3179 (gcry_ac_ssa_*_t) specific to the chosen scheme.
3182 @node Handle-independent functions
3183 @subsection Handle-independent functions
3185 These two functions are deprecated; do not use them for new code.
3187 @deftypefun gcry_error_t gcry_ac_id_to_name (gcry_ac_id_t @var{algorithm}, const char **@var{name})
3188 Stores the textual representation of the algorithm whose id is given
3189 in @var{algorithm} in @var{name}. Deprecated; use @code{gcry_pk_algo_name}.
3192 @deftypefun gcry_error_t gcry_ac_name_to_id (const char *@var{name}, gcry_ac_id_t *@var{algorithm})
3193 Stores the numeric ID of the algorithm whose textual representation is
3194 contained in @var{name} in @var{algorithm}. Deprecated; use
3195 @code{gcry_pk_map_name}.
3198 @c **********************************************************
3199 @c ******************* Hash Functions *********************
3200 @c **********************************************************
3204 Libgcrypt provides an easy and consistent to use interface for hashing.
3205 Hashing is buffered and several hash algorithms can be updated at once.
3206 It is possible to compute a MAC using the same routines. The
3207 programming model follows an open/process/close paradigm and is in that
3208 similar to other building blocks provided by Libgcrypt.
3210 For convenience reasons, a few cyclic redundancy check value operations
3214 * Available hash algorithms:: List of hash algorithms supported by the library.
3215 * Hash algorithm modules:: How to work with hash algorithm modules.
3216 * Working with hash algorithms:: List of functions related to hashing.
3219 @node Available hash algorithms
3220 @section Available hash algorithms
3222 @c begin table of hash algorithms
3225 This is not a real algorithm but used by some functions as an error
3226 return value. This constant is guaranteed to have the value @code{0}.
3229 This is the SHA-1 algorithm which yields a message digest of 20 bytes.
3231 @item GCRY_MD_RMD160
3232 This is the 160 bit version of the RIPE message digest (RIPE-MD-160).
3233 Like SHA-1 it also yields a digest of 20 bytes.
3236 This is the well known MD5 algorithm, which yields a message digest of
3240 This is the MD4 algorithm, which yields a message digest of 16 bytes.
3243 This is an reserved identifier for MD-2; there is no implementation yet.
3246 This is the TIGER/192 algorithm which yields a message digest of 24 bytes.
3249 This is an reserved for the HAVAL algorithm with 5 passes and 160
3250 bit. It yields a message digest of 20 bytes. Note that there is no
3251 implementation yet available.
3253 @item GCRY_MD_SHA224
3254 This is the SHA-224 algorithm which yields a message digest of 28 bytes.
3255 See Change Notice 1 for FIPS 180-2 for the specification.
3257 @item GCRY_MD_SHA256
3258 This is the SHA-256 algorithm which yields a message digest of 32 bytes.
3259 See FIPS 180-2 for the specification.
3261 @item GCRY_MD_SHA384
3262 This is the SHA-384 algorithm which yields a message digest of 48 bytes.
3263 See FIPS 180-2 for the specification.
3265 @item GCRY_MD_SHA512
3266 This is the SHA-384 algorithm which yields a message digest of 64 bytes.
3267 See FIPS 180-2 for the specification.
3270 This is the ISO 3309 and ITU-T V.42 cyclic redundancy check. It
3271 yields an output of 4 bytes.
3273 @item GCRY_MD_CRC32_RFC1510
3274 This is the above cyclic redundancy check function, as modified by RFC
3275 1510. It yields an output of 4 bytes.
3277 @item GCRY_MD_CRC24_RFC2440
3278 This is the OpenPGP cyclic redundancy check function. It yields an
3281 @item GCRY_MD_WHIRLPOOL
3282 This is the Whirlpool algorithm which yields a message digest of 64
3286 @c end table of hash algorithms
3288 @node Hash algorithm modules
3289 @section Hash algorithm modules
3291 Libgcrypt makes it possible to load additional `message
3292 digest modules'; these digests can be used just like the message digest
3293 algorithms that are built into the library directly. For an
3294 introduction into extension modules, see @xref{Modules}.
3296 @deftp {Data type} gcry_md_spec_t
3297 This is the `module specification structure' needed for registering
3298 message digest modules, which has to be filled in by the user before
3299 it can be used to register a module. It contains the following
3303 @item const char *name
3304 The primary name of this algorithm.
3305 @item unsigned char *asnoid
3306 Array of bytes that form the ASN OID.
3308 Length of bytes in `asnoid'.
3309 @item gcry_md_oid_spec_t *oids
3310 A list of OIDs that are to be associated with the algorithm. The
3311 list's last element must have it's `oid' member set to NULL. See
3312 below for an explanation of this type. See below for an explanation
3315 Length of the message digest algorithm. See below for an explanation
3317 @item gcry_md_init_t init
3318 The function responsible for initializing a handle. See below for an
3319 explanation of this type.
3320 @item gcry_md_write_t write
3321 The function responsible for writing data into a message digest
3322 context. See below for an explanation of this type.
3323 @item gcry_md_final_t final
3324 The function responsible for `finalizing' a message digest context.
3325 See below for an explanation of this type.
3326 @item gcry_md_read_t read
3327 The function responsible for reading out a message digest result. See
3328 below for an explanation of this type.
3329 @item size_t contextsize
3330 The size of the algorithm-specific `context', that should be
3331 allocated for each handle.
3335 @deftp {Data type} gcry_md_oid_spec_t
3336 This type is used for associating a user-provided algorithm
3337 implementation with certain OIDs. It contains the following members:
3340 @item const char *oidstring
3341 Textual representation of the OID.
3345 @deftp {Data type} gcry_md_init_t
3346 Type for the `init' function, defined as: void (*gcry_md_init_t) (void
3350 @deftp {Data type} gcry_md_write_t
3351 Type for the `write' function, defined as: void (*gcry_md_write_t)
3352 (void *c, unsigned char *buf, size_t nbytes)
3355 @deftp {Data type} gcry_md_final_t
3356 Type for the `final' function, defined as: void (*gcry_md_final_t)
3360 @deftp {Data type} gcry_md_read_t
3361 Type for the `read' function, defined as: unsigned char
3362 *(*gcry_md_read_t) (void *c)
3365 @deftypefun gcry_error_t gcry_md_register (gcry_md_spec_t *@var{digest}, unsigned int *algorithm_id, gcry_module_t *@var{module})
3367 Register a new digest module whose specification can be found in
3368 @var{digest}. On success, a new algorithm ID is stored in
3369 @var{algorithm_id} and a pointer representing this module is stored
3373 @deftypefun void gcry_md_unregister (gcry_module_t @var{module})
3374 Unregister the digest identified by @var{module}, which must have been
3375 registered with gcry_md_register.
3378 @deftypefun gcry_error_t gcry_md_list (int *@var{list}, int *@var{list_length})
3379 Get a list consisting of the IDs of the loaded message digest modules.
3380 If @var{list} is zero, write the number of loaded message digest
3381 modules to @var{list_length} and return. If @var{list} is non-zero,
3382 the first *@var{list_length} algorithm IDs are stored in @var{list},
3383 which must be of according size. In case there are less message
3384 digests modules than *@var{list_length}, *@var{list_length} is updated
3385 to the correct number.
3388 @node Working with hash algorithms
3389 @section Working with hash algorithms
3391 To use most of these function it is necessary to create a context;
3394 @deftypefun gcry_error_t gcry_md_open (gcry_md_hd_t *@var{hd}, int @var{algo}, unsigned int @var{flags})
3396 Create a message digest object for algorithm @var{algo}. @var{flags}
3397 may be given as an bitwise OR of constants described below. @var{algo}
3398 may be given as @code{0} if the algorithms to use are later set using
3399 @code{gcry_md_enable}. @var{hd} is guaranteed to either receive a valid
3402 For a list of supported algorithms, see @xref{Available hash
3405 The flags allowed for @var{mode} are:
3407 @c begin table of hash flags
3409 @item GCRY_MD_FLAG_SECURE
3410 Allocate all buffers and the resulting digest in "secure memory". Use
3411 this is the hashed data is highly confidential.
3413 @item GCRY_MD_FLAG_HMAC
3414 Turn the algorithm into a HMAC message authentication algorithm. This
3415 only works if just one algorithm is enabled for the handle. Note that the function
3416 @code{gcry_md_setkey} must be used to set the MAC key. If you want CBC
3417 message authentication codes based on a cipher, see @xref{Working with
3421 @c begin table of hash flags
3423 You may use the function @code{gcry_md_is_enabled} to later check
3424 whether an algorithm has been enabled.
3427 @c end function gcry_md_open
3429 If you want to calculate several hash algorithms at the same time, you
3430 have to use the following function right after the @code{gcry_md_open}:
3432 @deftypefun gcry_error_t gcry_md_enable (gcry_md_hd_t @var{h}, int @var{algo})
3434 Add the message digest algorithm @var{algo} to the digest object
3435 described by handle @var{h}. Duplicated enabling of algorithms is
3436 detected and ignored.
3439 If the flag @code{GCRY_MD_FLAG_HMAC} was used, the key for the MAC must
3440 be set using the function:
3442 @deftypefun gcry_error_t gcry_md_setkey (gcry_md_hd_t @var{h}, const void *@var{key}, size_t @var{keylen})
3444 For use with the HMAC feature, set the MAC key to the value of @var{key}
3445 of length @var{keylen}.
3449 After you are done with the hash calculation, you should release the
3452 @deftypefun void gcry_md_close (gcry_md_hd_t @var{h})
3454 Release all resources of hash context @var{h}. @var{h} should not be
3455 used after a call to this function. A @code{NULL} passed as @var{h} is
3460 Often you have to do several hash operations using the same algorithm.
3461 To avoid the overhead of creating and releasing context, a reset function
3464 @deftypefun void gcry_md_reset (gcry_md_hd_t @var{h})
3466 Reset the current context to its initial state. This is effectively
3467 identical to a close followed by an open and enabling all currently
3472 Often it is necessary to start hashing some data and then continue to
3473 hash different data. To avoid hashing the same data several times (which
3474 might not even be possible if the data is received from a pipe), a
3475 snapshot of the current hash context can be taken and turned into a new
3478 @deftypefun gcry_error_t gcry_md_copy (gcry_md_hd_t *@var{handle_dst}, gcry_md_hd_t @var{handle_src})
3480 Create a new digest object as an exact copy of the object described by
3481 handle @var{handle_src} and store it in @var{handle_dst}. The context
3482 is not reset and you can continue to hash data using this context and
3483 independently using the original context.
3487 Now that we have prepared everything to calculate hashes, it is time to
3488 see how it is actually done. There are two ways for this, one to
3489 update the hash with a block of memory and one macro to update the hash
3490 by just one character. Both methods can be used on the same hash context.
3492 @deftypefun void gcry_md_write (gcry_md_hd_t @var{h}, const void *@var{buffer}, size_t @var{length})
3494 Pass @var{length} bytes of the data in @var{buffer} to the digest object
3495 with handle @var{h} to update the digest values. This
3496 function should be used for large blocks of data.
3499 @deftypefun void gcry_md_putc (gcry_md_hd_t @var{h}, int @var{c})
3501 Pass the byte in @var{c} to the digest object with handle @var{h} to
3502 update the digest value. This is an efficient function, implemented as
3503 a macro to buffer the data before an actual update.
3506 The semantics of the hash functions do not provide for reading out intermediate
3507 message digests because the calculation must be finalized first. This
3508 finalization may for example include the number of bytes hashed in the
3509 message digest or some padding.
3511 @deftypefun void gcry_md_final (gcry_md_hd_t @var{h})
3513 Finalize the message digest calculation. This is not really needed
3514 because @code{gcry_md_read} does this implicitly. After this has been
3515 done no further updates (by means of @code{gcry_md_write} or
3516 @code{gcry_md_putc} are allowed. Only the first call to this function
3517 has an effect. It is implemented as a macro.
3520 The way to read out the calculated message digest is by using the
3523 @deftypefun unsigned char *gcry_md_read (gcry_md_hd_t @var{h}, int @var{algo})
3525 @code{gcry_md_read} returns the message digest after finalizing the
3526 calculation. This function may be used as often as required but it will
3527 always return the same value for one handle. The returned message digest
3528 is allocated within the message context and therefore valid until the
3529 handle is released or reseted (using @code{gcry_md_close} or
3530 @code{gcry_md_reset}. @var{algo} may be given as 0 to return the only
3531 enabled message digest or it may specify one of the enabled algorithms.
3532 The function does return @code{NULL} if the requested algorithm has not
3536 Because it is often necessary to get the message digest of one block of
3537 memory, a fast convenience function is available for this task:
3539 @deftypefun void gcry_md_hash_buffer (int @var{algo}, void *@var{digest}, const void *@var{buffer}, size_t @var{length});
3541 @code{gcry_md_hash_buffer} is a shortcut function to calculate a message
3542 digest of a buffer. This function does not require a context and
3543 immediately returns the message digest of the @var{length} bytes at
3544 @var{buffer}. @var{digest} must be allocated by the caller, large
3545 enough to hold the message digest yielded by the the specified algorithm
3546 @var{algo}. This required size may be obtained by using the function
3547 @code{gcry_md_get_algo_dlen}.
3549 Note that this function will abort the process if an unavailable
3553 @c ***********************************
3554 @c ***** MD info functions ***********
3555 @c ***********************************
3557 Hash algorithms are identified by internal algorithm numbers (see
3558 @code{gcry_md_open} for a list). However, in most applications they are
3559 used by names, so two functions are available to map between string
3560 representations and hash algorithm identifiers.
3562 @deftypefun const char *gcry_md_algo_name (int @var{algo})
3564 Map the digest algorithm id @var{algo} to a string representation of the
3565 algorithm name. For unknown algorithms this function returns the
3566 string @code{"?"}. This function should not be used to test for the
3567 availability of an algorithm.
3570 @deftypefun int gcry_md_map_name (const char *@var{name})
3572 Map the algorithm with @var{name} to a digest algorithm identifier.
3573 Returns 0 if the algorithm name is not known. Names representing
3574 @acronym{ASN.1} object identifiers are recognized if the @acronym{IETF}
3575 dotted format is used and the OID is prefixed with either "@code{oid.}"
3576 or "@code{OID.}". For a list of supported OIDs, see the source code at
3577 @file{cipher/md.c}. This function should not be used to test for the
3578 availability of an algorithm.
3581 @deftypefun gcry_error_t gcry_md_get_asnoid (int @var{algo}, void *@var{buffer}, size_t *@var{length})
3583 Return an DER encoded ASN.1 OID for the algorithm @var{algo} in the
3584 user allocated @var{buffer}. @var{length} must point to variable with
3585 the available size of @var{buffer} and receives after return the
3586 actual size of the returned OID. The returned error code may be
3587 @code{GPG_ERR_TOO_SHORT} if the provided buffer is to short to receive
3588 the OID; it is possible to call the function with @code{NULL} for
3589 @var{buffer} to have it only return the required size. The function
3590 returns 0 on success.
3595 To test whether an algorithm is actually available for use, the
3596 following macro should be used:
3598 @deftypefun gcry_error_t gcry_md_test_algo (int @var{algo})
3600 The macro returns 0 if the algorithm @var{algo} is available for use.
3603 If the length of a message digest is not known, it can be retrieved
3604 using the following function:
3606 @deftypefun unsigned int gcry_md_get_algo_dlen (int @var{algo})
3608 Retrieve the length in bytes of the digest yielded by algorithm
3609 @var{algo}. This is often used prior to @code{gcry_md_read} to allocate
3610 sufficient memory for the digest.
3614 In some situations it might be hard to remember the algorithm used for
3615 the ongoing hashing. The following function might be used to get that
3618 @deftypefun int gcry_md_get_algo (gcry_md_hd_t @var{h})
3620 Retrieve the algorithm used with the handle @var{h}. Note that this
3621 does not work reliable if more than one algorithm is enabled in @var{h}.
3624 The following macro might also be useful:
3626 @deftypefun int gcry_md_is_secure (gcry_md_hd_t @var{h})
3628 This function returns true when the digest object @var{h} is allocated
3629 in "secure memory"; i.e. @var{h} was created with the
3630 @code{GCRY_MD_FLAG_SECURE}.
3633 @deftypefun int gcry_md_is_enabled (gcry_md_hd_t @var{h}, int @var{algo})
3635 This function returns true when the algorithm @var{algo} has been
3636 enabled for the digest object @var{h}.
3641 Tracking bugs related to hashing is often a cumbersome task which
3642 requires to add a lot of printf statements into the code.
3643 Libgcrypt provides an easy way to avoid this. The actual data
3644 hashed can be written to files on request.
3646 @deftypefun void gcry_md_debug (gcry_md_hd_t @var{h}, const char *@var{suffix})
3648 Enable debugging for the digest object with handle @var{h}. This
3649 creates create files named @file{dbgmd-<n>.<string>} while doing the
3650 actual hashing. @var{suffix} is the string part in the filename. The
3651 number is a counter incremented for each new hashing. The data in the
3652 file is the raw data as passed to @code{gcry_md_write} or
3653 @code{gcry_md_putc}. If @code{NULL} is used for @var{suffix}, the
3654 debugging is stopped and the file closed. This is only rarely required
3655 because @code{gcry_md_close} implicitly stops debugging.
3659 The following two deprecated macros are used for debugging by old code.
3660 They shopuld be replaced by @code{gcry_md_debug}.
3662 @deftypefun void gcry_md_start_debug (gcry_md_hd_t @var{h}, const char *@var{suffix})
3664 Enable debugging for the digest object with handle @var{h}. This
3665 creates create files named @file{dbgmd-<n>.<string>} while doing the
3666 actual hashing. @var{suffix} is the string part in the filename. The
3667 number is a counter incremented for each new hashing. The data in the
3668 file is the raw data as passed to @code{gcry_md_write} or
3669 @code{gcry_md_putc}.
3673 @deftypefun void gcry_md_stop_debug (gcry_md_hd_t @var{h}, int @var{reserved})
3675 Stop debugging on handle @var{h}. @var{reserved} should be specified as
3676 0. This function is usually not required because @code{gcry_md_close}
3677 does implicitly stop debugging.
3681 @c **********************************************************
3682 @c ******************* Random *****************************
3683 @c **********************************************************
3684 @node Random Numbers
3685 @chapter Random Numbers
3688 * Quality of random numbers:: Libgcrypt uses different quality levels.
3689 * Retrieving random numbers:: How to retrieve random numbers.
3692 @node Quality of random numbers
3693 @section Quality of random numbers
3695 @acronym{Libgcypt} offers random numbers of different quality levels:
3697 @deftp {Data type} enum gcry_random_level
3698 The constants for the random quality levels are of this type.
3702 @item GCRY_WEAK_RANDOM
3703 For all functions, except for @code{gcry_mpi_randomize}, this level maps
3704 to GCRY_STRONG_RANDOM. IF you do not want this, consider using
3705 @code{gcry_create_nonce}.
3706 @item GCRY_STRONG_RANDOM
3707 Use this level for e.g. session keys and similar purposes.
3708 @item GCRY_VERY_STRONG_RANDOM
3709 Use this level for e.g. key material.
3712 @node Retrieving random numbers
3713 @section Retrieving random numbers
3715 @deftypefun void gcry_randomize (unsigned char *@var{buffer}, size_t @var{length}, enum gcry_random_level @var{level})
3717 Fill @var{buffer} with @var{length} random bytes using a random quality
3718 as defined by @var{level}.
3721 @deftypefun void * gcry_random_bytes (size_t @var{nbytes}, enum gcry_random_level @var{level})
3723 Convenience function to allocate a memory block consisting of
3724 @var{nbytes} fresh random bytes using a random quality as defined by
3728 @deftypefun void * gcry_random_bytes_secure (size_t @var{nbytes}, enum gcry_random_level @var{level})
3730 Convenience function to allocate a memory block consisting of
3731 @var{nbytes} fresh random bytes using a random quality as defined by
3732 @var{level}. This function differs from @code{gcry_random_bytes} in
3733 that the returned buffer is allocated in a ``secure'' area of the
3737 @deftypefun void gcry_create_nonce (unsigned char *@var{buffer}, size_t @var{length})
3739 Fill @var{buffer} with @var{length} unpredictable bytes. This is
3740 commonly called a nonce and may also be used for initialization
3741 vectors and padding. This is an extra function nearly independent of
3742 the other random function for 3 reasons: It better protects the
3743 regular random generator's internal state, provides better performance
3744 and does not drain the precious entropy pool.
3750 @c **********************************************************
3751 @c ******************* S-Expressions ***********************
3752 @c **********************************************************
3754 @chapter S-expressions
3756 S-expressions are used by the public key functions to pass complex data
3757 structures around. These LISP like objects are used by some
3758 cryptographic protocols (cf. RFC-2692) and Libgcrypt provides functions
3759 to parse and construct them. For detailed information, see
3760 @cite{Ron Rivest, code and description of S-expressions,
3761 @uref{http://theory.lcs.mit.edu/~rivest/sexp.html}}.
3764 * Data types for S-expressions:: Data types related with S-expressions.
3765 * Working with S-expressions:: How to work with S-expressions.
3768 @node Data types for S-expressions
3769 @section Data types for S-expressions
3771 @deftp {Data type} gcry_sexp_t
3772 The @code{gcry_sexp_t} type describes an object with the Libgcrypt internal
3773 representation of an S-expression.
3776 @node Working with S-expressions
3777 @section Working with S-expressions
3780 There are several functions to create an Libgcrypt S-expression object
3781 from its external representation or from a string template. There is
3782 also a function to convert the internal representation back into one of
3783 the external formats:
3786 @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}})
3788 This is the generic function to create an new S-expression object from
3789 its external representation in @var{buffer} of @var{length} bytes. On
3790 success the result is stored at the address given by @var{r_sexp}.
3791 With @var{autodetect} set to 0, the data in @var{buffer} is expected to
3792 be in canonized format, with @var{autodetect} set to 1 the parses any of
3793 the defined external formats. If @var{buffer} does not hold a valid
3794 S-expression an error code is returned and @var{r_sexp} set to
3796 Note that the caller is responsible for releasing the newly allocated
3797 S-expression using @code{gcry_sexp_release}.
3800 @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*)})
3802 This function is identical to @code{gcry_sexp_new} but has an extra
3803 argument @var{freefnc}, which, when not set to @code{NULL}, is expected
3804 to be a function to release the @var{buffer}; most likely the standard
3805 @code{free} function is used for this argument. This has the effect of
3806 transferring the ownership of @var{buffer} to the created object in
3807 @var{r_sexp}. The advantage of using this function is that Libgcrypt
3808 might decide to directly use the provided buffer and thus avoid extra
3812 @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}})
3814 This is another variant of the above functions. It behaves nearly
3815 identical but provides an @var{erroff} argument which will receive the
3816 offset into the buffer where the parsing stopped on error.
3819 @deftypefun gcry_error_t gcry_sexp_build (@w{gcry_sexp_t *@var{r_sexp}}, @w{size_t *@var{erroff}}, @w{const char *@var{format}, ...})
3821 This function creates an internal S-expression from the string template
3822 @var{format} and stores it at the address of @var{r_sexp}. If there is a
3823 parsing error, the function returns an appropriate error code and stores
3824 the offset into @var{format} where the parsing stopped in @var{erroff}.
3825 The function supports a couple of printf-like formatting characters and
3826 expects arguments for some of these escape sequences right after
3827 @var{format}. The following format characters are defined:
3831 The next argument is expected to be of type @code{gcry_mpi_t} and a copy of
3832 its value is inserted into the resulting S-expression.
3834 The next argument is expected to be of type @code{char *} and that
3835 string is inserted into the resulting S-expression.
3837 The next argument is expected to be of type @code{int} and its value is
3838 inserted into the resulting S-expression.
3840 The next argument is expected to be of type @code{int} directly
3841 followed by an argument of type @code{char *}. This represents a
3842 buffer of given length to be inserted into the resulting regular
3847 No other format characters are defined and would return an error. Note
3848 that the format character @samp{%%} does not exists, because a percent
3849 sign is not a valid character in an S-expression.
3852 @deftypefun void gcry_sexp_release (@w{gcry_sexp_t @var{sexp}})
3854 Release the S-expression object @var{sexp}.
3859 The next 2 functions are used to convert the internal representation
3860 back into a regular external S-expression format and to show the
3861 structure for debugging.
3863 @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}})
3865 Copies the S-expression object @var{sexp} into @var{buffer} using the
3866 format specified in @var{mode}. @var{maxlength} must be set to the
3867 allocated length of @var{buffer}. The function returns the actual
3868 length of valid bytes put into @var{buffer} or 0 if the provided buffer
3869 is too short. Passing @code{NULL} for @var{buffer} returns the required
3870 length for @var{buffer}. For convenience reasons an extra byte with
3871 value 0 is appended to the buffer.
3874 The following formats are supported:
3877 @item GCRYSEXP_FMT_DEFAULT
3878 Returns a convenient external S-expression representation.
3880 @item GCRYSEXP_FMT_CANON
3881 Return the S-expression in canonical format.
3883 @item GCRYSEXP_FMT_BASE64
3884 Not currently supported.
3886 @item GCRYSEXP_FMT_ADVANCED
3887 Returns the S-expression in advanced format.
3891 @deftypefun void gcry_sexp_dump (@w{gcry_sexp_t @var{sexp}})
3893 Dumps @var{sexp} in a format suitable for debugging to Libgcrypt's
3898 Often canonical encoding is used in the external representation. The
3899 following function can be used to check for valid encoding and to learn
3900 the length of the S-expression"
3902 @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}})
3904 Scan the canonical encoded @var{buffer} with implicit length values and
3905 return the actual length this S-expression uses. For a valid S-expression
3906 it should never return 0. If @var{length} is not 0, the maximum
3907 length to scan is given; this can be used for syntax checks of
3908 data passed from outside. @var{errcode} and @var{erroff} may both be
3909 passed as @code{NULL}.
3915 There are a couple of functions to parse S-expressions and retrieve
3918 @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}})
3920 Scan the S-expression for a sublist with a type (the car of the list)
3921 matching the string @var{token}. If @var{toklen} is not 0, the token is
3922 assumed to be raw memory of this length. The function returns a newly
3923 allocated S-expression consisting of the found sublist or @code{NULL}
3928 @deftypefun int gcry_sexp_length (@w{const gcry_sexp_t @var{list}})
3930 Return the length of the @var{list}. For a valid S-expression this
3931 should be at least 1.
3935 @deftypefun gcry_sexp_t gcry_sexp_nth (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}})
3937 Create and return a new S-expression from the element with index @var{number} in
3938 @var{list}. Note that the first element has the index 0. If there is
3939 no such element, @code{NULL} is returned.
3942 @deftypefun gcry_sexp_t gcry_sexp_car (@w{const gcry_sexp_t @var{list}})
3944 Create and return a new S-expression from the first element in
3945 @var{list}; this called the "type" and should always exist and be a
3946 string. @code{NULL} is returned in case of a problem.
3949 @deftypefun gcry_sexp_t gcry_sexp_cdr (@w{const gcry_sexp_t @var{list}})
3951 Create and return a new list form all elements except for the first one.
3952 Note that this function may return an invalid S-expression because it
3953 is not guaranteed, that the type exists and is a string. However, for
3954 parsing a complex S-expression it might be useful for intermediate
3955 lists. Returns @code{NULL} on error.
3959 @deftypefun {const char *} gcry_sexp_nth_data (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{size_t *@var{datalen}})
3961 This function is used to get data from a @var{list}. A pointer to the
3962 actual data with index @var{number} is returned and the length of this
3963 data will be stored to @var{datalen}. If there is no data at the given
3964 index or the index represents another list, @code{NULL} is returned.
3965 @strong{Caution:} The returned pointer is valid as long as @var{list} is
3966 not modified or released.
3969 Here is an example on how to extract and print the surname (Meier) from
3970 the S-expression @samp{(Name Otto Meier (address Burgplatz 3))}:
3976 name = gcry_sexp_nth_data (list, 2, &len);
3977 printf ("my name is %.*s\n", (int)len, name);
3981 @deftypefun char *gcry_sexp_nth_string (@w{gcry_sexp_t @var{list}}, @w{int @var{number}})
3983 This function is used to get and convert data from a @var{list}. The
3984 data is assumed to be a Nul terminated string. The caller must
3985 release this returned value using @code{gcry_free}. If there is
3986 no data at the given index, the index represents a list or the value
3987 can't be converted to a string, @code{NULL} is returned.
3990 @deftypefun gcry_mpi_t gcry_sexp_nth_mpi (@w{gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{int @var{mpifmt}})
3992 This function is used to get and convert data from a @var{list}. This
3993 data is assumed to be an MPI stored in the format described by
3994 @var{mpifmt} and returned as a standard Libgcrypt MPI. The caller must
3995 release this returned value using @code{gcry_mpi_release}. If there is
3996 no data at the given index, the index represents a list or the value
3997 can't be converted to an MPI, @code{NULL} is returned.
4001 @c **********************************************************
4002 @c ******************* MPIs ******** ***********************
4003 @c **********************************************************
4005 @chapter MPI library
4008 * Data types:: MPI related data types.
4009 * Basic functions:: First steps with MPI numbers.
4010 * MPI formats:: External representation of MPIs.
4011 * Calculations:: Performing MPI calculations.
4012 * Comparisons:: How to compare MPI values.
4013 * Bit manipulations:: How to access single bits of MPI values.
4014 * Miscellaneous:: Miscellaneous MPI functions.
4017 Public key cryptography is based on mathematics with large numbers. To
4018 implement the public key functions, a library for handling these large
4019 numbers is required. Because of the general usefulness of such a
4020 library, its interface is exposed by Libgcrypt. The implementation is
4021 based on an old release of GNU Multi-Precision Library (GMP) but in the
4022 meantime heavily modified and stripped down to what is required for
4023 cryptography. For a lot of CPUs, high performance assembler
4024 implementations of some very low level functions are used to gain much
4025 better performance than with the standard C implementation.
4028 In the context of Libgcrypt and in most other applications, these large
4029 numbers are called MPIs (multi-precision-integers).
4034 @deftp {Data type} gcry_mpi_t
4035 The @code{gcry_mpi_t} type represents an object to hold an MPI.
4038 @node Basic functions
4039 @section Basic functions
4042 To work with MPIs, storage must be allocated and released for the
4043 numbers. This can be done with one of these functions:
4045 @deftypefun gcry_mpi_t gcry_mpi_new (@w{unsigned int @var{nbits}})
4047 Allocate a new MPI object, initialize it to 0 and initially allocate
4048 enough memory for a number of at least @var{nbits}. This pre-allocation is
4049 only a small performance issue and not actually necessary because
4050 Libgcrypt automatically re-allocates the required memory.
4053 @deftypefun gcry_mpi_t gcry_mpi_snew (@w{unsigned int @var{nbits}})
4055 This is identical to @code{gcry_mpi_new} but allocates the MPI in the so
4056 called "secure memory" which in turn will take care that all derived
4057 values will also be stored in this "secure memory". Use this for highly
4058 confidential data like private key parameters.
4061 @deftypefun gcry_mpi_t gcry_mpi_copy (@w{const gcry_mpi_t @var{a}})
4063 Create a new MPI as the exact copy of @var{a}.
4067 @deftypefun void gcry_mpi_release (@w{gcry_mpi_t @var{a}})
4069 Release the MPI @var{a} and free all associated resources. Passing
4070 @code{NULL} is allowed and ignored. When a MPI stored in the "secure
4071 memory" is released, that memory gets wiped out immediately.
4075 The simplest operations are used to assign a new value to an MPI:
4077 @deftypefun gcry_mpi_t gcry_mpi_set (@w{gcry_mpi_t @var{w}}, @w{const gcry_mpi_t @var{u}})
4079 Assign the value of @var{u} to @var{w} and return @var{w}. If
4080 @code{NULL} is passed for @var{w}, a new MPI is allocated, set to the
4081 value of @var{u} and returned.
4084 @deftypefun gcry_mpi_t gcry_mpi_set_ui (@w{gcry_mpi_t @var{w}}, @w{unsigned long @var{u}})
4086 Assign the value of @var{u} to @var{w} and return @var{w}. If
4087 @code{NULL} is passed for @var{w}, a new MPI is allocated, set to the
4088 value of @var{u} and returned. This function takes an @code{unsigned
4089 int} as type for @var{u} and thus it is only possible to set @var{w} to
4090 small values (usually up to the word size of the CPU).
4093 @deftypefun void gcry_mpi_swap (@w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}})
4095 Swap the values of @var{a} and @var{b}.
4099 @section MPI formats
4102 The following functions are used to convert between an external
4103 representation of an MPI and the internal one of Libgcrypt.
4105 @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}})
4107 Convert the external representation of an integer stored in @var{buffer}
4108 with a length of @var{buflen} into a newly created MPI returned which
4109 will be stored at the address of @var{r_mpi}. For certain formats the
4110 length argument is not required and should be passed as @code{0}. After a
4111 successful operation the variable @var{nscanned} receives the number of
4112 bytes actually scanned unless @var{nscanned} was given as
4113 @code{NULL}. @var{format} describes the format of the MPI as stored in
4117 @item GCRYMPI_FMT_STD
4118 2-complement stored without a length header.
4120 @item GCRYMPI_FMT_PGP
4121 As used by OpenPGP (only defined as unsigned). This is basically
4122 @code{GCRYMPI_FMT_STD} with a 2 byte big endian length header.
4124 @item GCRYMPI_FMT_SSH
4125 As used in the Secure Shell protocol. This is @code{GCRYMPI_FMT_STD}
4126 with a 4 byte big endian header.
4128 @item GCRYMPI_FMT_HEX
4129 Stored as a C style string with each byte of the MPI encoded as 2 hex
4130 digits. When using this format, @var{buflen} must be zero.
4132 @item GCRYMPI_FMT_USG
4133 Simple unsigned integer.
4137 Note that all of the above formats store the integer in big-endian
4142 @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}})
4144 Convert the MPI @var{a} into an external representation described by
4145 @var{format} (see above) and store it in the provided @var{buffer}
4146 which has a usable length of at least the @var{buflen} bytes. If
4147 @var{nwritten} is not NULL, it will receive the number of bytes
4148 actually stored in @var{buffer} after a successful operation.
4151 @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}})
4153 Convert the MPI @var{a} into an external representation described by
4154 @var{format} (see above) and store it in a newly allocated buffer which
4155 address will be stored in the variable @var{buffer} points to. The
4156 number of bytes stored in this buffer will be stored in the variable
4157 @var{nbytes} points to, unless @var{nbytes} is @code{NULL}.
4160 @deftypefun void gcry_mpi_dump (@w{const gcry_mpi_t @var{a}})
4162 Dump the value of @var{a} in a format suitable for debugging to
4163 Libgcrypt's logging stream. Note that one leading space but no trailing
4164 space or linefeed will be printed. It is okay to pass @code{NULL} for
4170 @section Calculations
4173 Basic arithmetic operations:
4175 @deftypefun void gcry_mpi_add (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
4177 @math{@var{w} = @var{u} + @var{v}}.
4181 @deftypefun void gcry_mpi_add_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4183 @math{@var{w} = @var{u} + @var{v}}. Note that @var{v} is an unsigned integer.
4187 @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}})
4189 @math{@var{w} = @var{u} + @var{v} \bmod @var{m}}.
4192 @deftypefun void gcry_mpi_sub (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
4194 @math{@var{w} = @var{u} - @var{v}}.
4197 @deftypefun void gcry_mpi_sub_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4199 @math{@var{w} = @var{u} - @var{v}}. @var{v} is an unsigned integer.
4202 @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}})
4204 @math{@var{w} = @var{u} - @var{v} \bmod @var{m}}.
4207 @deftypefun void gcry_mpi_mul (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
4209 @math{@var{w} = @var{u} * @var{v}}.
4212 @deftypefun void gcry_mpi_mul_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4214 @math{@var{w} = @var{u} * @var{v}}. @var{v} is an unsigned integer.
4217 @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}})
4219 @math{@var{w} = @var{u} * @var{v} \bmod @var{m}}.
4222 @deftypefun void gcry_mpi_mul_2exp (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{e}})
4224 @c FIXME: I am in need for a real TeX{info} guru:
4225 @c I don't know why TeX can grok @var{e} here.
4226 @math{@var{w} = @var{u} * 2^e}.
4229 @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}})
4231 @math{@var{q} = @var{dividend} / @var{divisor}}, @math{@var{r} =
4232 @var{dividend} \bmod @var{divisor}}. @var{q} and @var{r} may be passed
4233 as @code{NULL}. @var{round} should be negative or 0.
4236 @deftypefun void gcry_mpi_mod (@w{gcry_mpi_t @var{r}}, @w{gcry_mpi_t @var{dividend}}, @w{gcry_mpi_t @var{divisor}})
4238 @math{@var{r} = @var{dividend} \bmod @var{divisor}}.
4241 @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}})
4243 @c I don't know why TeX can grok @var{e} here.
4244 @math{@var{w} = @var{b}^e \bmod @var{m}}.
4247 @deftypefun int gcry_mpi_gcd (@w{gcry_mpi_t @var{g}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}})
4249 Set @var{g} to the greatest common divisor of @var{a} and @var{b}.
4250 Return true if the @var{g} is 1.
4253 @deftypefun int gcry_mpi_invm (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{m}})
4255 Set @var{x} to the multiplicative inverse of @math{@var{a} \bmod @var{m}}.
4256 Return true if the inverse exists.
4261 @section Comparisons
4264 The next 2 functions are used to compare MPIs:
4267 @deftypefun int gcry_mpi_cmp (@w{const gcry_mpi_t @var{u}}, @w{const gcry_mpi_t @var{v}})
4269 Compare the multi-precision-integers number @var{u} and @var{v}
4270 returning 0 for equality, a positive value for @var{u} > @var{v} and a
4271 negative for @var{u} < @var{v}.
4274 @deftypefun int gcry_mpi_cmp_ui (@w{const gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4276 Compare the multi-precision-integers number @var{u} with the unsigned
4277 integer @var{v} returning 0 for equality, a positive value for @var{u} >
4278 @var{v} and a negative for @var{u} < @var{v}.
4282 @node Bit manipulations
4283 @section Bit manipulations
4286 There are a couple of functions to get information on arbitrary bits
4287 in an MPI and to set or clear them:
4289 @deftypefun {unsigned int} gcry_mpi_get_nbits (@w{gcry_mpi_t @var{a}})
4291 Return the number of bits required to represent @var{a}.
4294 @deftypefun int gcry_mpi_test_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4296 Return true if bit number @var{n} (counting from 0) is set in @var{a}.
4299 @deftypefun void gcry_mpi_set_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4301 Set bit number @var{n} in @var{a}.
4304 @deftypefun void gcry_mpi_clear_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4306 Clear bit number @var{n} in @var{a}.
4309 @deftypefun void gcry_mpi_set_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4311 Set bit number @var{n} in @var{a} and clear all bits greater than @var{n}.
4314 @deftypefun void gcry_mpi_clear_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4316 Clear bit number @var{n} in @var{a} and all bits greater than @var{n}.
4319 @deftypefun void gcry_mpi_rshift (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4321 Shift the value of @var{a} by @var{n} bits to the right and store the
4326 @section Miscellaneous
4328 @deftypefun gcry_mpi_t gcry_mpi_set_opaque (@w{gcry_mpi_t @var{a}}, @w{void *@var{p}}, @w{unsigned int @var{nbits}})
4330 Store @var{nbits} of the value @var{p} points to in @var{a} and mark
4331 @var{a} as an opaque value (i.e. an value that can't be used for any
4332 math calculation and is only used to store an arbitrary bit pattern in
4335 WARNING: Never use an opaque MPI for actual math operations. The only
4336 valid functions are gcry_mpi_get_opaque and gcry_mpi_release. Use
4337 gcry_mpi_scan to convert a string of arbitrary bytes into an MPI.
4341 @deftypefun {void *} gcry_mpi_get_opaque (@w{gcry_mpi_t @var{a}}, @w{unsigned int *@var{nbits}})
4343 Return a pointer to an opaque value stored in @var{a} and return its