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 * FIPS Finite State Machine:: Description of the FIPS FSM.
82 * Library Copying:: The GNU Lesser General Public License
83 says how you can copy and share Libgcrypt.
84 * Copying:: The GNU General Public License says how you
85 can copy and share some parts of Libgcrypt.
89 * Figures and Tables:: Index of figures and tables.
90 * Concept Index:: Index of concepts and programs.
91 * Function and Data Index:: Index of functions, variables and data types.
102 @c **********************************************************
103 @c ******************* Introduction ***********************
104 @c **********************************************************
106 @chapter Introduction
108 Libgcrypt is a library providing cryptographic building blocks.
111 * Getting Started:: How to use this manual.
112 * Features:: A glance at Libgcrypt's features.
113 * Overview:: Overview about the library.
116 @node Getting Started
117 @section Getting Started
119 This manual documents the Libgcrypt library application programming
120 interface (API). All functions and data types provided by the library
124 The reader is assumed to possess basic knowledge about applied
127 This manual can be used in several ways. If read from the beginning
128 to the end, it gives a good introduction into the library and how it
129 can be used in an application. Forward references are included where
130 necessary. Later on, the manual can be used as a reference manual to
131 get just the information needed about any particular interface of the
132 library. Experienced programmers might want to start looking at the
133 examples at the end of the manual, and then only read up those parts
134 of the interface which are unclear.
140 Libgcrypt might have a couple of advantages over other libraries doing
144 @item It's Free Software
145 Anybody can use, modify, and redistribute it under the terms of the GNU
146 Lesser General Public License (@pxref{Library Copying}). Note, that
147 some parts (which are in general not needed by applications) are subject
148 to the terms of the GNU General Public License (@pxref{Copying}); please
149 see the README file of the distribution for of list of these parts.
151 @item It encapsulates the low level cryptography
152 Libgcrypt provides a high level interface to cryptographic
153 building blocks using an extensible and flexible API.
161 The Libgcrypt library is fully thread-safe, where it makes
162 sense to be thread-safe. Not thread-safe are some cryptographic
163 functions that modify a certain context stored in handles. If the
164 user really intents to use such functions from different threads on
165 the same handle, he has to take care of the serialization of such
166 functions himself. If not described otherwise, every function is
169 Libgcrypt depends on the library `libgpg-error', which
170 contains common error handling related code for GnuPG components.
172 @c **********************************************************
173 @c ******************* Preparation ************************
174 @c **********************************************************
178 To use Libgcrypt, you have to perform some changes to your
179 sources and the build system. The necessary changes are small and
180 explained in the following sections. At the end of this chapter, it
181 is described how the library is initialized, and how the requirements
182 of the library are verified.
185 * Header:: What header file you need to include.
186 * Building sources:: How to build sources using the library.
187 * Building sources using Automake:: How to build sources with the help of Automake.
188 * Initializing the library:: How to initialize the library.
189 * Multi-Threading:: How Libgcrypt can be used in a MT environment.
190 * FIPS mode:: How to enable the FIPS mode.
197 All interfaces (data types and functions) of the library are defined
198 in the header file @file{gcrypt.h}. You must include this in all source
199 files using the library, either directly or through some other header
206 The name space of Libgcrypt is @code{gcry_*} for function
207 and type names and @code{GCRY*} for other symbols. In addition the
208 same name prefixes with one prepended underscore are reserved for
209 internal use and should never be used by an application. Note that
210 Libgcrypt uses libgpg-error, which uses @code{gpg_*} as
211 name space for function and type names and @code{GPG_*} for other
212 symbols, including all the error codes.
215 Certain parts of gcrypt.h may be excluded by defining these macros:
218 @item GCRYPT_NO_MPI_MACROS
219 Do not define the shorthand macros @code{mpi_*} for @code{gcry_mpi_*}.
221 @item GCRYPT_NO_DEPRECATED
222 Do not include defintions for deprecated features. This is useful to
223 make sure that no deprecated features are used.
226 @node Building sources
227 @section Building sources
229 If you want to compile a source file including the `gcrypt.h' header
230 file, you must make sure that the compiler can find it in the
231 directory hierarchy. This is accomplished by adding the path to the
232 directory in which the header file is located to the compilers include
233 file search path (via the @option{-I} option).
235 However, the path to the include file is determined at the time the
236 source is configured. To solve this problem, Libgcrypt ships with a small
237 helper program @command{libgcrypt-config} that knows the path to the
238 include file and other configuration options. The options that need
239 to be added to the compiler invocation at compile time are output by
240 the @option{--cflags} option to @command{libgcrypt-config}. The following
241 example shows how it can be used at the command line:
244 gcc -c foo.c `libgcrypt-config --cflags`
247 Adding the output of @samp{libgcrypt-config --cflags} to the compilers
248 command line will ensure that the compiler can find the Libgcrypt header
251 A similar problem occurs when linking the program with the library.
252 Again, the compiler has to find the library files. For this to work,
253 the path to the library files has to be added to the library search path
254 (via the @option{-L} option). For this, the option @option{--libs} to
255 @command{libgcrypt-config} can be used. For convenience, this option
256 also outputs all other options that are required to link the program
257 with the Libgcrypt libraries (in particular, the @samp{-lgcrypt}
258 option). The example shows how to link @file{foo.o} with the Libgcrypt
259 library to a program @command{foo}.
262 gcc -o foo foo.o `libgcrypt-config --libs`
265 Of course you can also combine both examples to a single command by
266 specifying both options to @command{libgcrypt-config}:
269 gcc -o foo foo.c `libgcrypt-config --cflags --libs`
272 @node Building sources using Automake
273 @section Building sources using Automake
275 It is much easier if you use GNU Automake instead of writing your own
276 Makefiles. If you do that, you do not have to worry about finding and
277 invoking the @command{libgcrypt-config} script at all.
278 Libgcrypt provides an extension to Automake that does all
281 @c A simple macro for optional variables.
283 @r{[}@var{\varname\}@r{]}
285 @defmac AM_PATH_LIBGCRYPT (@ovar{minimum-version}, @ovar{action-if-found}, @ovar{action-if-not-found})
286 Check whether Libgcrypt (at least version
287 @var{minimum-version}, if given) exists on the host system. If it is
288 found, execute @var{action-if-found}, otherwise do
289 @var{action-if-not-found}, if given.
291 Additionally, the function defines @code{LIBGCRYPT_CFLAGS} to the
292 flags needed for compilation of the program to find the
293 @file{gcrypt.h} header file, and @code{LIBGCRYPT_LIBS} to the linker
294 flags needed to link the program to the Libgcrypt library.
297 You can use the defined Autoconf variables like this in your
301 AM_CPPFLAGS = $(LIBGCRYPT_CFLAGS)
302 LDADD = $(LIBGCRYPT_LIBS)
305 @node Initializing the library
306 @section Initializing the library
308 Before the library can be used, it must initialize itself. This is
309 achieved by invoking the function @code{gcry_check_version} described
312 Also, it is often desirable to check that the version of
313 Libgcrypt used is indeed one which fits all requirements.
314 Even with binary compatibility, new features may have been introduced,
315 but due to problem with the dynamic linker an old version may actually
316 be used. So you may want to check that the version is okay right
317 after program startup.
319 @deftypefun const char *gcry_check_version (const char *@var{req_version})
321 The function @code{gcry_check_version} initializes some subsystems used
322 by Libgcrypt and must be invoked before any other function in the
323 library, with the exception of the @code{GCRYCTL_SET_THREAD_CBS} command
324 (called via the @code{gcry_control} function).
325 @xref{Multi-Threading}.
327 Furthermore, this function returns the version number of the library.
328 It can also verify that the version number is higher than a certain
329 required version number @var{req_version}, if this value is not a null
333 Libgcrypt uses a concept known as secure memory, which is a region of
334 memory set aside for storing sensitive data. Because such memory is a
335 scare resource, it needs to be setup in advanced to a fixed size.
336 Further, most operating systems have special requirements on how that
337 secure memory can be used. For example, it might be required to install
338 an application as ``setuid(root)'' to allow allocating such memory.
339 Libgcrypt requires a sequence of initialization steps to make sure that
340 this works correctly. The following examples show the necessary steps.
342 If you don't have a need for secure memory, for example if your
343 application does not use secret keys or other confidential data or it
344 runs in a controlled environment where key material floating around in
345 memory is not a problem, you should initialize Libgcrypt this way:
348 /* Version check should be the very first call because it
349 makes sure that important subsystems are intialized. */
350 if (!gcry_check_version (GCRYPT_VERSION))
352 fputs ("libgcrypt version mismatch\n", stderr);
356 /* Disable secure memory. */
357 gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
359 /* ... If required, other initialization goes here. */
361 /* Tell Libgcrypt that initialization has completed. */
362 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
366 If you have to protect your keys or other information in memory against
367 being swapped out to disk and to enable an automatic overwrite of used
368 and freed memory, you need to initialize Libgcrypt this way:
371 /* Version check should be the very first call because it
372 makes sure that important subsystems are intialized. */
373 if (!gcry_check_version (GCRYPT_VERSION))
375 fputs ("libgcrypt version mismatch\n", stderr);
379 @anchor{sample-use-suspend-secmem}
380 /* We don't want to see any warnings, e.g. because we have not yet
381 parsed program options which might be used to suppress such
383 gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
385 /* ... If required, other initialization goes here. Note that the
386 process might still be running with increased privileges and that
387 the secure memory has not been intialized. */
389 /* Allocate a pool of 16k secure memory. This make the secure memory
390 available and also drops privileges where needed. */
391 gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
393 @anchor{sample-use-resume-secmem}
394 /* It is now okay to let Libgcrypt complain when there was/is a problem
395 with the secure memory. */
396 gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
398 /* ... If required, other initialization goes here. */
400 /* Tell Libgcrypt that initialization has completed. */
401 gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
404 It is important that these initialization steps are not done by a
405 library but by the actual application. A library using Libgcrypt might
406 want to check for finished initialization using:
409 if (!gcry_control (GCRYCTL_INITIALIZATION_FINISHED_P))
411 fputs ("libgcrypt has not been initialized\n", stderr);
416 Instead of terminating the process, the library may instead print a
417 warning and try to initialize Libgcrypt itself. See also the section on
418 multi-threading below for more pitfalls.
422 @node Multi-Threading
423 @section Multi-Threading
425 As mentioned earlier, the Libgcrypt library is
426 thread-safe if you adhere to the following requirements:
430 If your application is multi-threaded, you must set the thread support
431 callbacks with the @code{GCRYCTL_SET_THREAD_CBS} command
432 @strong{before} any other function in the library.
434 This is easy enough if you are indeed writing an application using
435 Libgcrypt. It is rather problematic if you are writing a library
436 instead. Here are some tips what to do if you are writing a library:
438 If your library requires a certain thread package, just initialize
439 Libgcrypt to use this thread package. If your library supports multiple
440 thread packages, but needs to be configured, you will have to
441 implement a way to determine which thread package the application
442 wants to use with your library anyway. Then configure Libgcrypt to use
445 If your library is fully reentrant without any special support by a
446 thread package, then you are lucky indeed. Unfortunately, this does
447 not relieve you from doing either of the two above, or use a third
448 option. The third option is to let the application initialize Libgcrypt
449 for you. Then you are not using Libgcrypt transparently, though.
451 As if this was not difficult enough, a conflict may arise if two
452 libraries try to initialize Libgcrypt independently of each others, and
453 both such libraries are then linked into the same application. To
454 make it a bit simpler for you, this will probably work, but only if
455 both libraries have the same requirement for the thread package. This
456 is currently only supported for the non-threaded case, GNU Pth and
457 pthread. Support for more thread packages is easy to add, so contact
458 us if you require it.
461 The function @code{gcry_check_version} must be called before any other
462 function in the library, except the @code{GCRYCTL_SET_THREAD_CBS}
463 command (called via the @code{gcry_control} function), because it
464 initializes the thread support subsystem in Libgcrypt. To
465 achieve this in multi-threaded programs, you must synchronize the
466 memory with respect to other threads that also want to use
467 Libgcrypt. For this, it is sufficient to call
468 @code{gcry_check_version} before creating the other threads using
469 Libgcrypt@footnote{At least this is true for POSIX threads,
470 as @code{pthread_create} is a function that synchronizes memory with
471 respects to other threads. There are many functions which have this
472 property, a complete list can be found in POSIX, IEEE Std 1003.1-2003,
473 Base Definitions, Issue 6, in the definition of the term ``Memory
474 Synchronization''. For other thread packages, more relaxed or more
475 strict rules may apply.}.
479 Just like the function @code{gpg_strerror}, the function
480 @code{gcry_strerror} is not thread safe. You have to use
481 @code{gpg_strerror_r} instead.
485 Libgcrypt contains convenient macros, which define the
486 necessary thread callbacks for PThread and for GNU Pth:
489 @item GCRY_THREAD_OPTION_PTH_IMPL
491 This macro defines the following (static) symbols: gcry_pth_init,
492 gcry_pth_mutex_init, gcry_pth_mutex_destroy, gcry_pth_mutex_lock,
493 gcry_pth_mutex_unlock, gcry_pth_read, gcry_pth_write, gcry_pth_select,
494 gcry_pth_waitpid, gcry_pth_accept, gcry_pth_connect, gcry_threads_pth.
496 After including this macro, gcry_control() shall be used with a
497 command of GCRYCTL_SET_THREAD_CBS in order to register the thread
498 callback structure named ``gcry_threads_pth''.
500 @item GCRY_THREAD_OPTION_PTHREAD_IMPL
502 This macro defines the following (static) symbols:
503 gcry_pthread_mutex_init, gcry_pthread_mutex_destroy, gcry_mutex_lock,
504 gcry_mutex_unlock, gcry_threads_pthread.
506 After including this macro, gcry_control() shall be used with a
507 command of GCRYCTL_SET_THREAD_CBS in order to register the thread
508 callback structure named ``gcry_threads_pthread''.
511 Note that these macros need to be terminated with a semicolon. Keep
512 in mind that these are convenient macros for C programmers; C++
513 programmers might have to wrap these macros in an ``extern C'' body.
520 Libgcrypt may be used in a FIPS 140 mode. Note, that this does not
521 necessary mean that Libcgrypt is n appoved FIPS 140-2 module. Check the
522 NIST database at @url{http://csrc.nist.gov/groups/STM/cmvp/} to see what
523 versions of Libgcrypt are approved.
525 Because FIPS 140 has certain restrictions on the use of cryptography
526 which are not always wanted, Libgcrypt needs to be put into FIPS mode
527 explicitly. Three alternative mechanisms are provided to switch
528 Libgcrypt into this mode:
532 If the file @file{/proc/sys/crypto/fips_enabled} exists and contains a
533 numeric value other than @code{0}, Libgcrypt is put into FIPS mode at
534 initialization time. Obviously this works only on systems with a
535 @code{proc} file system (ie.e GNU/Linux).
538 If the file @file{/etc/gcrypt/fips140.force} exists, Libgcrypt is put
539 into FIPS mode at initialization time. Note that this filename is
540 hardwired and does not depend on any configuration options.
543 If the applications requests FIPS mode using the control command
544 @code{GCRYCTL_FORCE_FIPS_MODE}. This must be done prior to any
545 initialization (i.e. before @code{gcry_check_version}).
549 Note that once Libgcrypt has been put into FIPS mode, it is not possible
550 to switch back to standard mode without terminating the process first.
551 If the log verbosity level of Libgcrypt has been set to at least 2, the
552 state transitions and the selftests are logged.
556 @c **********************************************************
557 @c ******************* General ****************************
558 @c **********************************************************
560 @chapter Generalities
563 * Controlling the library:: Controlling Libgcrypt's behavior.
564 * Modules:: Description of extension modules.
565 * Error Handling:: Error codes and such.
568 @node Controlling the library
569 @section Controlling the library
571 @deftypefun gcry_error_t gcry_control (enum gcry_ctl_cmds @var{cmd}, ...)
573 This function can be used to influence the general behavior of
574 Libgcrypt in several ways. Depending on @var{cmd}, more
575 arguments can or have to be provided.
578 @item GCRYCTL_ENABLE_M_GUARD; Arguments: none
579 This command enables the built-in memory guard. It must not be used to
580 activate the memory guard after the memory management has already been
581 used; therefore it can ONLY be used at initialization time. Note that
582 the memory guard is NOT used when the user of the library has set his
583 own memory management callbacks.
585 @item GCRYCTL_ENABLE_QUICK_RANDOM; Arguments: none
586 This command inhibits the use the very secure random quality level
587 (@code{GCRY_VERY_STRONG_RANDOM}) and degrades all request down to
588 @code{GCRY_STRONG_RANDOM}. In general this is not recommened. However,
589 for some applications the extra quality random Libgcrypt tries to create
590 is not justified and this option may help to get better performace.
591 Please check with a crypto expert whether this option can be used for
594 This option can only be used at initialization time.
597 @item GCRYCTL_DUMP_RANDOM_STATS; Arguments: none
598 This command dumps randum number generator related statistics to the
599 library's logging stream.
601 @item GCRYCTL_DUMP_MEMORY_STATS; Arguments: none
602 This command dumps memory managment related statistics to the library's
605 @item GCRYCTL_DUMP_SECMEM_STATS; Arguments: none
606 This command dumps secure memory manamgent related statistics to the
607 library's logging stream.
609 @item GCRYCTL_DROP_PRIVS; Arguments: none
610 This command disables the use of secure memory and drops the priviliges
611 of the current process. This command has not much use; the suggested way
612 to disable secure memory is to use @code{GCRYCTL_DISABLE_SECMEM} right
613 after initialization.
615 @item GCRYCTL_DISABLE_SECMEM; Arguments: none
616 This command disables the use of secure memory.
618 Many applications do not require secure memory, so they should disable
619 it right away. There won't be a problem if not disabling it unless one
620 makes use of a feature which requires secure memory - in that case the
621 process will abort because the secmem is not initialized. This command
622 should be executed right after @code{gcry_check_version}.
624 @item GCRYCTL_INIT_SECMEM; Arguments: int nbytes
625 This command is used to allocate a pool of secure memory and thus
626 enabling the use of secure memory. It also drops all extra privileges
627 the process has (i.e. if it is run as setuid (root)). If the argument
628 @var{nbytes} is 0, secure memory will be disabled. The minimum amount
629 of secure memory allocated is currently 16384 bytes; you may thus use a
630 value of 1 to request that default size.
632 @item GCRYCTL_TERM_SECMEM; Arguments: none
633 This command zeroises the secure memory and destroys the handler. The
634 secure memory pool may not be used anymore after running this command.
635 If the secure memory pool as already been destroyed, this command has no
636 effect. Applications might want to run this command from their exit
637 handler to make sure that the secure memory gets properly destroyed.
638 This command is not necessary thread-safe but that should not be needed
639 in cleanup code. It may be called from a signal handler.
641 @item GCRYCTL_DISABLE_SECMEM_WARN; Arguments: none
642 Disable warning messages about problems with the secure memory
643 subsystem. This command should be run right after
644 @code{gcry_check_version}.
646 @item GCRYCTL_SUSPEND_SECMEM_WARN; Arguments: none
647 Postpone warning messages from the secure memory subsystem.
648 @xref{sample-use-suspend-secmem,,the initialization example}, on how to
651 @item GCRYCTL_RESUME_SECMEM_WARN; Arguments: none
652 Resume warning messages from the secure memory subsystem.
653 @xref{sample-use-resume-secmem,,the initialization example}, on how to
656 @item GCRYCTL_USE_SECURE_RNDPOOL; Arguments: none
657 This command tells the PRNG to store random numbers in secure memory.
658 This command should be run right after @code{gcry_check_version} and not
659 later than the command GCRYCTL_INIT_SECMEM. Note that in FIPS mode the
660 secure memory is always used.
662 @item GCRYCTL_SET_RANDOM_SEED_FILE; Arguments: const char *filename
663 This command specifies the file, which is to be used as seed file for
664 the PRNG. If the seed file is registered prior to initialization of the
665 PRNG, the seed file's content (if it exists and seems to be valid) is
666 fed into the PRNG pool. After the seed file has been registered, the
667 PRNG can be signalled to write out the PRNG pool's content into the seed
668 file with the following command.
671 @item GCRYCTL_UPDATE_RANDOM_SEED_FILE; Arguments: none
672 Write out the PRNG pool's content into the registered seed file.
674 Multiple instances of the applications sharing the same random seed file
675 can be started in parallel, in which case they will read out the same
676 pool and then race for updating it (the last update overwrites earlier
677 updates). They will differentiate only by the weak entropy that is
678 added in read_seed_file based on the PID and clock, and up to 16 bytes
679 of weak random non-blockingly. The consequence is that the output of
680 these different instances is correlated to some extent. In a perfect
681 attack scenario, the attacker can control (or at least guess) the PID
682 and clock of the application, and drain the system's entropy pool to
683 reduce the "up to 16 bytes" above to 0. Then the dependencies of the
684 inital states of the pools are completely known. Note that this is not
685 an issue if random of @code{GCRY_VERY_STRONG_RANDOM} quality is
686 requested as in this case enough extra entropy gets mixed. It is also
687 not an issue when using Linux (rndlinux driver), because this one
688 guarantees to read full 16 bytes from /dev/urandom and thus there is no
689 way for an attacker without kernel access to conrol these 16 bytes.
691 @item GCRYCTL_SET_VERBOSITY; Arguments: int level
692 This command sets the verbosity of the logging. A level of 0 disables
693 all extra logging whereas positive numbers enable more verbose logging.
694 The level may be changed at any time but be aware that no memory
695 syncronization is done so the effect of this command might not
696 immediately show up in other threads. This command may even be used
697 prioe to @code{gcry_check_version}.
699 @item GCRYCTL_SET_DEBUG_FLAGS; Arguments: unsigned int flags
700 Set the debug flag bits as given by the argument. Be aware that that no
701 memory syncronization is done so the effect of this command might not
702 immediately show up in other threads. The debug flags are not
703 considered part of the API and thus may change without notice. As of
704 now bit 0 enables debugging of cipher functions and bit 1 debugging of
705 multi-precision-integers. This command may even be used prioe to
706 @code{gcry_check_version}.
708 @item GCRYCTL_CLEAR_DEBUG_FLAGS; Arguments: unsigned int flags
709 Set the debug flag bits as given by the argument. Be aware that that no
710 memory syncronization is done so the effect of this command might not
711 immediately show up in other threads. This command may even be used
712 prioe to @code{gcry_check_version}.
714 @item GCRYCTL_DISABLE_INTERNAL_LOCKING; Arguments: none
715 This command does nothing. It exists only for backward compatibility.
717 @item GCRYCTL_ANY_INITIALIZATION_P; Arguments: none
718 This command returns true if the library has been basically initialized.
719 Such a basic initialization happens implicitly with many commands to get
720 certain internal subsystems running. The common and suggested way to
721 do this basic intialization is by calling gcry_check_version.
723 @item GCRYCTL_INITIALIZATION_FINISHED; Arguments: none
724 This command tells the libray that the application has finished the
727 @item GCRYCTL_INITIALIZATION_FINISHED_P; Arguments: none
728 This command returns true if the command@*
729 GCRYCTL_INITIALIZATION_FINISHED has already been run.
731 @item GCRYCTL_SET_THREAD_CBS; Arguments: struct ath_ops *ath_ops
732 This command registers a thread-callback structure.
733 @xref{Multi-Threading}.
735 @item GCRYCTL_FAST_POLL; Arguments: none
736 Run a fast random poll.
738 @item GCRYCTL_SET_RNDEGD_SOCKET; Arguments: const char *filename
739 This command may be used to override the default name of the EGD socket
740 to connect to. It may be used only during initialization as it is not
741 thread safe. Changing the socket name again is not supported. The
742 function may return an error if the given filename is too long for a
745 EGD is an alternative random gatherer, used only on systems lacking a
746 proper random device.
748 @item GCRYCTL_PRINT_CONFIG; Arguments: FILE *stream
749 This command dumps information pertaining to the configuration of the
750 library to the given stream. If NULL is given for @var{stream}, the log
751 system is used. This command may be used before the intialization has
752 been finished but not before a gcry_version_check.
754 @item GCRYCTL_OPERATIONAL_P; Arguments: none
755 This command returns true if the library is in an operational state.
756 This information makes only sense in FIPS mode. In contrast to other
757 functions, this is a pure test function and won't put the library into
758 FIPS mode or change the internal state. This command may be used before
759 the intialization has been finished but not before a gcry_version_check.
761 @item GCRYCTL_FIPS_MODE_P; Arguments: none
762 This command returns true if the library is in FIPS mode. Note, that
763 this is no indication about the current state of the library. This
764 command may be used before the intialization has been finished but not
765 before a gcry_version_check.
767 @item GCRYCTL_FORCE_FIPS_MODE; Arguments: none
768 Running this command puts the library into FIPS mode. If the library is
769 already in FIPS mode, a selftest is triggered and thus the library will
770 be put into operational state. This command may be used before a call
771 to gcry_check_version and that is actually the recommended way to let an
772 application switch the library into FIPS mode. Note that Libgcrypt will
773 reject an attempt to switch to fips mode during or after the intialization.
775 @item GCRYCTL_SELFTEST; Arguments: none
776 This may be used at anytime to have the library run all implemented
777 selftests. It works in standard and in FIPS mode. Returns 0 on
778 success or an error code.
788 Libgcrypt supports the use of `extension modules', which
789 implement algorithms in addition to those already built into the library
792 @deftp {Data type} gcry_module_t
793 This data type represents a `module'.
796 Functions registering modules provided by the user take a `module
797 specification structure' as input and return a value of
798 @code{gcry_module_t} and an ID that is unique in the modules'
799 category. This ID can be used to reference the newly registered
800 module. After registering a module successfully, the new functionality
801 should be able to be used through the normal functions provided by
802 Libgcrypt until it is unregistered again.
804 @c **********************************************************
805 @c ******************* Errors ****************************
806 @c **********************************************************
808 @section Error Handling
810 Many functions in Libgcrypt can return an error if they
811 fail. For this reason, the application should always catch the error
812 condition and take appropriate measures, for example by releasing the
813 resources and passing the error up to the caller, or by displaying a
814 descriptive message to the user and cancelling the operation.
816 Some error values do not indicate a system error or an error in the
817 operation, but the result of an operation that failed properly. For
818 example, if you try to decrypt a tempered message, the decryption will
819 fail. Another error value actually means that the end of a data
820 buffer or list has been reached. The following descriptions explain
821 for many error codes what they mean usually. Some error values have
822 specific meanings if returned by a certain functions. Such cases are
823 described in the documentation of those functions.
825 Libgcrypt uses the @code{libgpg-error} library. This allows to share
826 the error codes with other components of the GnuPG system, and to pass
827 error values transparently from the crypto engine, or some helper
828 application of the crypto engine, to the user. This way no
829 information is lost. As a consequence, Libgcrypt does not use its own
830 identifiers for error codes, but uses those provided by
831 @code{libgpg-error}. They usually start with @code{GPG_ERR_}.
833 However, Libgcrypt does provide aliases for the functions
834 defined in libgpg-error, which might be preferred for name space
838 Most functions in Libgcrypt return an error code in the case
839 of failure. For this reason, the application should always catch the
840 error condition and take appropriate measures, for example by
841 releasing the resources and passing the error up to the caller, or by
842 displaying a descriptive message to the user and canceling the
845 Some error values do not indicate a system error or an error in the
846 operation, but the result of an operation that failed properly.
848 GnuPG components, including Libgcrypt, use an extra library named
849 libgpg-error to provide a common error handling scheme. For more
850 information on libgpg-error, see the according manual.
853 * Error Values:: The error value and what it means.
854 * Error Sources:: A list of important error sources.
855 * Error Codes:: A list of important error codes.
856 * Error Strings:: How to get a descriptive string from a value.
861 @subsection Error Values
864 @cindex error sources
866 @deftp {Data type} {gcry_err_code_t}
867 The @code{gcry_err_code_t} type is an alias for the
868 @code{libgpg-error} type @code{gpg_err_code_t}. The error code
869 indicates the type of an error, or the reason why an operation failed.
871 A list of important error codes can be found in the next section.
874 @deftp {Data type} {gcry_err_source_t}
875 The @code{gcry_err_source_t} type is an alias for the
876 @code{libgpg-error} type @code{gpg_err_source_t}. The error source
877 has not a precisely defined meaning. Sometimes it is the place where
878 the error happened, sometimes it is the place where an error was
879 encoded into an error value. Usually the error source will give an
880 indication to where to look for the problem. This is not always true,
881 but it is attempted to achieve this goal.
883 A list of important error sources can be found in the next section.
886 @deftp {Data type} {gcry_error_t}
887 The @code{gcry_error_t} type is an alias for the @code{libgpg-error}
888 type @code{gpg_error_t}. An error value like this has always two
889 components, an error code and an error source. Both together form the
892 Thus, the error value can not be directly compared against an error
893 code, but the accessor functions described below must be used.
894 However, it is guaranteed that only 0 is used to indicate success
895 (@code{GPG_ERR_NO_ERROR}), and that in this case all other parts of
896 the error value are set to 0, too.
898 Note that in Libgcrypt, the error source is used purely for
899 diagnostic purposes. Only the error code should be checked to test
900 for a certain outcome of a function. The manual only documents the
901 error code part of an error value. The error source is left
902 unspecified and might be anything.
905 @deftypefun {gcry_err_code_t} gcry_err_code (@w{gcry_error_t @var{err}})
906 The static inline function @code{gcry_err_code} returns the
907 @code{gcry_err_code_t} component of the error value @var{err}. This
908 function must be used to extract the error code from an error value in
909 order to compare it with the @code{GPG_ERR_*} error code macros.
912 @deftypefun {gcry_err_source_t} gcry_err_source (@w{gcry_error_t @var{err}})
913 The static inline function @code{gcry_err_source} returns the
914 @code{gcry_err_source_t} component of the error value @var{err}. This
915 function must be used to extract the error source from an error value in
916 order to compare it with the @code{GPG_ERR_SOURCE_*} error source macros.
919 @deftypefun {gcry_error_t} gcry_err_make (@w{gcry_err_source_t @var{source}}, @w{gcry_err_code_t @var{code}})
920 The static inline function @code{gcry_err_make} returns the error
921 value consisting of the error source @var{source} and the error code
924 This function can be used in callback functions to construct an error
925 value to return it to the library.
928 @deftypefun {gcry_error_t} gcry_error (@w{gcry_err_code_t @var{code}})
929 The static inline function @code{gcry_error} returns the error value
930 consisting of the default error source and the error code @var{code}.
932 For @acronym{GCRY} applications, the default error source is
933 @code{GPG_ERR_SOURCE_USER_1}. You can define
934 @code{GCRY_ERR_SOURCE_DEFAULT} before including @file{gcrypt.h} to
937 This function can be used in callback functions to construct an error
938 value to return it to the library.
941 The @code{libgpg-error} library provides error codes for all system
942 error numbers it knows about. If @var{err} is an unknown error
943 number, the error code @code{GPG_ERR_UNKNOWN_ERRNO} is used. The
944 following functions can be used to construct error values from system
947 @deftypefun {gcry_error_t} gcry_err_make_from_errno (@w{gcry_err_source_t @var{source}}, @w{int @var{err}})
948 The function @code{gcry_err_make_from_errno} is like
949 @code{gcry_err_make}, but it takes a system error like @code{errno}
950 instead of a @code{gcry_err_code_t} error code.
953 @deftypefun {gcry_error_t} gcry_error_from_errno (@w{int @var{err}})
954 The function @code{gcry_error_from_errno} is like @code{gcry_error},
955 but it takes a system error like @code{errno} instead of a
956 @code{gcry_err_code_t} error code.
959 Sometimes you might want to map system error numbers to error codes
960 directly, or map an error code representing a system error back to the
961 system error number. The following functions can be used to do that.
963 @deftypefun {gcry_err_code_t} gcry_err_code_from_errno (@w{int @var{err}})
964 The function @code{gcry_err_code_from_errno} returns the error code
965 for the system error @var{err}. If @var{err} is not a known system
966 error, the function returns @code{GPG_ERR_UNKNOWN_ERRNO}.
969 @deftypefun {int} gcry_err_code_to_errno (@w{gcry_err_code_t @var{err}})
970 The function @code{gcry_err_code_to_errno} returns the system error
971 for the error code @var{err}. If @var{err} is not an error code
972 representing a system error, or if this system error is not defined on
973 this system, the function returns @code{0}.
978 @subsection Error Sources
979 @cindex error codes, list of
981 The library @code{libgpg-error} defines an error source for every
982 component of the GnuPG system. The error source part of an error
983 value is not well defined. As such it is mainly useful to improve the
984 diagnostic error message for the user.
986 If the error code part of an error value is @code{0}, the whole error
987 value will be @code{0}. In this case the error source part is of
988 course @code{GPG_ERR_SOURCE_UNKNOWN}.
990 The list of error sources that might occur in applications using
991 @acronym{Libgcrypt} is:
994 @item GPG_ERR_SOURCE_UNKNOWN
995 The error source is not known. The value of this error source is
998 @item GPG_ERR_SOURCE_GPGME
999 The error source is @acronym{GPGME} itself.
1001 @item GPG_ERR_SOURCE_GPG
1002 The error source is GnuPG, which is the crypto engine used for the
1005 @item GPG_ERR_SOURCE_GPGSM
1006 The error source is GPGSM, which is the crypto engine used for the
1009 @item GPG_ERR_SOURCE_GCRYPT
1010 The error source is @code{libgcrypt}, which is used by crypto engines
1011 to perform cryptographic operations.
1013 @item GPG_ERR_SOURCE_GPGAGENT
1014 The error source is @command{gpg-agent}, which is used by crypto
1015 engines to perform operations with the secret key.
1017 @item GPG_ERR_SOURCE_PINENTRY
1018 The error source is @command{pinentry}, which is used by
1019 @command{gpg-agent} to query the passphrase to unlock a secret key.
1021 @item GPG_ERR_SOURCE_SCD
1022 The error source is the SmartCard Daemon, which is used by
1023 @command{gpg-agent} to delegate operations with the secret key to a
1026 @item GPG_ERR_SOURCE_KEYBOX
1027 The error source is @code{libkbx}, a library used by the crypto
1028 engines to manage local keyrings.
1030 @item GPG_ERR_SOURCE_USER_1
1031 @item GPG_ERR_SOURCE_USER_2
1032 @item GPG_ERR_SOURCE_USER_3
1033 @item GPG_ERR_SOURCE_USER_4
1034 These error sources are not used by any GnuPG component and can be
1035 used by other software. For example, applications using
1036 Libgcrypt can use them to mark error values coming from callback
1037 handlers. Thus @code{GPG_ERR_SOURCE_USER_1} is the default for errors
1038 created with @code{gcry_error} and @code{gcry_error_from_errno},
1039 unless you define @code{GCRY_ERR_SOURCE_DEFAULT} before including
1045 @subsection Error Codes
1046 @cindex error codes, list of
1048 The library @code{libgpg-error} defines many error values. The
1049 following list includes the most important error codes.
1053 This value indicates the end of a list, buffer or file.
1055 @item GPG_ERR_NO_ERROR
1056 This value indicates success. The value of this error code is
1057 @code{0}. Also, it is guaranteed that an error value made from the
1058 error code @code{0} will be @code{0} itself (as a whole). This means
1059 that the error source information is lost for this error code,
1060 however, as this error code indicates that no error occurred, this is
1061 generally not a problem.
1063 @item GPG_ERR_GENERAL
1064 This value means that something went wrong, but either there is not
1065 enough information about the problem to return a more useful error
1066 value, or there is no separate error value for this type of problem.
1068 @item GPG_ERR_ENOMEM
1069 This value means that an out-of-memory condition occurred.
1072 System errors are mapped to GPG_ERR_EFOO where FOO is the symbol for
1075 @item GPG_ERR_INV_VALUE
1076 This value means that some user provided data was out of range.
1078 @item GPG_ERR_UNUSABLE_PUBKEY
1079 This value means that some recipients for a message were invalid.
1081 @item GPG_ERR_UNUSABLE_SECKEY
1082 This value means that some signers were invalid.
1084 @item GPG_ERR_NO_DATA
1085 This value means that data was expected where no data was found.
1087 @item GPG_ERR_CONFLICT
1088 This value means that a conflict of some sort occurred.
1090 @item GPG_ERR_NOT_IMPLEMENTED
1091 This value indicates that the specific function (or operation) is not
1092 implemented. This error should never happen. It can only occur if
1093 you use certain values or configuration options which do not work,
1094 but for which we think that they should work at some later time.
1096 @item GPG_ERR_DECRYPT_FAILED
1097 This value indicates that a decryption operation was unsuccessful.
1099 @item GPG_ERR_WRONG_KEY_USAGE
1100 This value indicates that a key is not used appropriately.
1102 @item GPG_ERR_NO_SECKEY
1103 This value indicates that no secret key for the user ID is available.
1105 @item GPG_ERR_UNSUPPORTED_ALGORITHM
1106 This value means a verification failed because the cryptographic
1107 algorithm is not supported by the crypto backend.
1109 @item GPG_ERR_BAD_SIGNATURE
1110 This value means a verification failed because the signature is bad.
1112 @item GPG_ERR_NO_PUBKEY
1113 This value means a verification failed because the public key is not
1116 @item GPG_ERR_NOT_OPERATIONAL
1117 This value means that the library is not yet in state which allows to
1118 use this function. This error code is in particular returned if
1119 Libgcrypt is operated in FIPS mode and the internal state of the
1120 library does not yet or not anymore allow the use of a service.
1122 This error code is only available with newer libgpg-error versions, thus
1123 you might see ``invalid error code'' when passing this to
1124 @code{gpg_strerror}. The numeric value of this error code is 176.
1126 @item GPG_ERR_USER_1
1127 @item GPG_ERR_USER_2
1129 @item GPG_ERR_USER_16
1130 These error codes are not used by any GnuPG component and can be
1131 freely used by other software. Applications using Libgcrypt
1132 might use them to mark specific errors returned by callback handlers
1133 if no suitable error codes (including the system errors) for these
1134 errors exist already.
1139 @subsection Error Strings
1140 @cindex error values, printing of
1141 @cindex error codes, printing of
1142 @cindex error sources, printing of
1143 @cindex error strings
1145 @deftypefun {const char *} gcry_strerror (@w{gcry_error_t @var{err}})
1146 The function @code{gcry_strerror} returns a pointer to a statically
1147 allocated string containing a description of the error code contained
1148 in the error value @var{err}. This string can be used to output a
1149 diagnostic message to the user.
1153 @deftypefun {const char *} gcry_strsource (@w{gcry_error_t @var{err}})
1154 The function @code{gcry_strerror} returns a pointer to a statically
1155 allocated string containing a description of the error source
1156 contained in the error value @var{err}. This string can be used to
1157 output a diagnostic message to the user.
1160 The following example illustrates the use of the functions described
1165 gcry_cipher_hd_t handle;
1166 gcry_error_t err = 0;
1168 err = gcry_cipher_open (&handle, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, 0);
1171 fprintf (stderr, "Failure: %s/%s\n",
1172 gcry_strsource (err),
1173 gcry_strerror (err));
1178 @c **********************************************************
1179 @c ******************* General ****************************
1180 @c **********************************************************
1181 @node Handler Functions
1182 @chapter Handler Functions
1184 Libgcrypt makes it possible to install so called `handler functions',
1185 which get called by Libgcrypt in case of certain events.
1188 * Progress handler:: Using a progress handler function.
1189 * Allocation handler:: Using special memory allocation functions.
1190 * Error handler:: Using error handler functions.
1191 * Logging handler:: Using a special logging function.
1194 @node Progress handler
1195 @section Progress handler
1197 It is often useful to retrieve some feedback while long running
1198 operations are performed.
1200 @deftp {Data type} gcry_handler_progress_t
1201 Progress handler functions have to be of the type
1202 @code{gcry_handler_progress_t}, which is defined as:
1204 @code{void (*gcry_handler_progress_t) (void *, const char *, int, int, int)}
1207 The following function may be used to register a handler function for
1210 @deftypefun void gcry_set_progress_handler (gcry_handler_progress_t @var{cb}, void *@var{cb_data})
1212 This function installs @var{cb} as the `Progress handler' function.
1213 @var{cb} must be defined as follows:
1217 my_progress_handler (void *@var{cb_data}, const char *@var{what},
1218 int @var{printchar}, int @var{current}, int @var{total})
1224 A description of the arguments of the progress handler function follows.
1228 The argument provided in the call to @code{gcry_set_progress_handler}.
1230 A string identifying the type of the progress output. The following
1231 values for @var{what} are defined:
1235 Not enough entropy is available. @var{total} holds the number of
1239 Values for @var{printchar}:
1244 Need to refresh the pool of prime numbers.
1246 Number of bits adjusted.
1248 Searching for a generator.
1250 Fermat test on 10 candidates failed.
1252 Restart with a new random value.
1254 Rabin Miller test passed.
1262 @node Allocation handler
1263 @section Allocation handler
1265 It is possible to make Libgcrypt use special memory
1266 allocation functions instead of the built-in ones.
1268 Memory allocation functions are of the following types:
1269 @deftp {Data type} gcry_handler_alloc_t
1270 This type is defined as: @code{void *(*gcry_handler_alloc_t) (size_t n)}.
1272 @deftp {Data type} gcry_handler_secure_check_t
1273 This type is defined as: @code{int *(*gcry_handler_secure_check_t) (const void *)}.
1275 @deftp {Data type} gcry_handler_realloc_t
1276 This type is defined as: @code{void *(*gcry_handler_realloc_t) (void *p, size_t n)}.
1278 @deftp {Data type} gcry_handler_free_t
1279 This type is defined as: @code{void *(*gcry_handler_free_t) (void *)}.
1282 Special memory allocation functions can be installed with the
1285 @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})
1286 Install the provided functions and use them instead of the built-in
1287 functions for doing memory allocation.
1291 @section Error handler
1293 The following functions may be used to register handler functions that
1294 are called by Libgcrypt in case certain error conditions occur. They
1295 may and should be registered prior to calling @code{gcry_check_version}.
1297 @deftp {Data type} gcry_handler_no_mem_t
1298 This type is defined as: @code{void (*gcry_handler_no_mem_t) (void *, size_t, unsigned int)}
1300 @deftypefun void gcry_set_outofcore_handler (gcry_handler_no_mem_t @var{func_no_mem}, void *@var{cb_data})
1301 This function registers @var{func_no_mem} as `out-of-core handler',
1302 which means that it will be called in the case of not having enough
1306 @deftp {Data type} gcry_handler_error_t
1307 This type is defined as: @code{void (*gcry_handler_error_t) (void *, int, const char *)}
1310 @deftypefun void gcry_set_fatalerror_handler (gcry_handler_error_t @var{func_error}, void *@var{cb_data})
1311 This function registers @var{func_error} as `error handler',
1312 which means that it will be called in error conditions.
1315 @node Logging handler
1316 @section Logging handler
1318 @deftp {Data type} gcry_handler_log_t
1319 This type is defined as: @code{void (*gcry_handler_log_t) (void *, int, const char *, va_list)}
1322 @deftypefun void gcry_set_log_handler (gcry_handler_log_t @var{func_log}, void *@var{cb_data})
1323 This function registers @var{func_log} as `logging handler', which means
1324 that it will be called in case Libgcrypt wants to log a message. This
1325 function may and should be used prior to calling
1326 @code{gcry_check_version}.
1329 @c **********************************************************
1330 @c ******************* Ciphers ****************************
1331 @c **********************************************************
1332 @c @include cipher-ref.texi
1333 @node Symmetric cryptography
1334 @chapter Symmetric cryptography
1336 The cipher functions are used for symmetrical cryptography,
1337 i.e. cryptography using a shared key. The programming model follows
1338 an open/process/close paradigm and is in that similar to other
1339 building blocks provided by Libgcrypt.
1342 * Available ciphers:: List of ciphers supported by the library.
1343 * Cipher modules:: How to work with cipher modules.
1344 * Available cipher modes:: List of cipher modes supported by the library.
1345 * Working with cipher handles:: How to perform operations related to cipher handles.
1346 * General cipher functions:: General cipher functions independent of cipher handles.
1349 @node Available ciphers
1350 @section Available ciphers
1353 @item GCRY_CIPHER_NONE
1354 This is not a real algorithm but used by some functions as error return.
1355 The value always evaluates to false.
1357 @item GCRY_CIPHER_IDEA
1358 This is the IDEA algorithm. The constant is provided but there is
1359 currently no implementation for it because the algorithm is patented.
1361 @item GCRY_CIPHER_3DES
1362 Triple-DES with 3 Keys as EDE. The key size of this algorithm is 168 but
1363 you have to pass 192 bits because the most significant bits of each byte
1366 @item GCRY_CIPHER_CAST5
1367 CAST128-5 block cipher algorithm. The key size is 128 bits.
1369 @item GCRY_CIPHER_BLOWFISH
1370 The blowfish algorithm. The current implementation allows only for a key
1373 @item GCRY_CIPHER_SAFER_SK128
1374 Reserved and not currently implemented.
1376 @item GCRY_CIPHER_DES_SK
1377 Reserved and not currently implemented.
1379 @item GCRY_CIPHER_AES
1380 @itemx GCRY_CIPHER_AES128
1381 @itemx GCRY_CIPHER_RIJNDAEL
1382 @itemx GCRY_CIPHER_RIJNDAEL128
1383 AES (Rijndael) with a 128 bit key.
1385 @item GCRY_CIPHER_AES192
1386 @itemx GCRY_CIPHER_RIJNDAEL192
1387 AES (Rijndael) with a 192 bit key.
1389 @item GCRY_CIPHER_AES256
1390 @itemx GCRY_CIPHER_RIJNDAEL256
1391 AES (Rijndael) with a 256 bit key.
1393 @item GCRY_CIPHER_TWOFISH
1394 The Twofish algorithm with a 256 bit key.
1396 @item GCRY_CIPHER_TWOFISH128
1397 The Twofish algorithm with a 128 bit key.
1399 @item GCRY_CIPHER_ARCFOUR
1400 An algorithm which is 100% compatible with RSA Inc.'s RC4 algorithm.
1401 Note that this is a stream cipher and must be used very carefully to
1402 avoid a couple of weaknesses.
1404 @item GCRY_CIPHER_DES
1405 Standard DES with a 56 bit key. You need to pass 64 bit but the high
1406 bits of each byte are ignored. Note, that this is a weak algorithm
1407 which can be broken in reasonable time using a brute force approach.
1409 @item GCRY_CIPHER_SERPENT128
1410 @itemx GCRY_CIPHER_SERPENT192
1411 @itemx GCRY_CIPHER_SERPENT256
1412 The Serpent cipher from the AES contest.
1414 @item GCRY_CIPHER_RFC2268_40
1415 @itemx GCRY_CIPHER_RFC2268_128
1416 Ron's Cipher 2 in the 40 and 128 bit variants. Note, that we currently
1417 only support the 40 bit variant. The identifier for 128 is reserved for
1420 @item GCRY_CIPHER_SEED
1421 A 128 bit cipher as described by RFC4269.
1423 @item GCRY_CIPHER_CAMELLIA128
1424 @itemx GCRY_CIPHER_CAMELLIA192
1425 @itemx GCRY_CIPHER_CAMELLIA256
1426 The Camellia cipher by NTT. See
1427 @uref{http://info.isl.ntt.co.jp/@/crypt/@/eng/@/camellia/@/specifications.html}.
1431 @node Cipher modules
1432 @section Cipher modules
1434 Libgcrypt makes it possible to load additional `cipher modules'; these
1435 ciphers can be used just like the cipher algorithms that are built
1436 into the library directly. For an introduction into extension
1437 modules, see @xref{Modules}.
1439 @deftp {Data type} gcry_cipher_spec_t
1440 This is the `module specification structure' needed for registering
1441 cipher modules, which has to be filled in by the user before it can be
1442 used to register a module. It contains the following members:
1445 @item const char *name
1446 The primary name of the algorithm.
1447 @item const char **aliases
1448 A list of strings that are `aliases' for the algorithm. The list must
1449 be terminated with a NULL element.
1450 @item gcry_cipher_oid_spec_t *oids
1451 A list of OIDs that are to be associated with the algorithm. The
1452 list's last element must have it's `oid' member set to NULL. See
1453 below for an explanation of this type.
1454 @item size_t blocksize
1455 The block size of the algorithm, in bytes.
1457 The length of the key, in bits.
1458 @item size_t contextsize
1459 The size of the algorithm-specific `context', that should be allocated
1461 @item gcry_cipher_setkey_t setkey
1462 The function responsible for initializing a handle with a provided
1463 key. See below for a description of this type.
1464 @item gcry_cipher_encrypt_t encrypt
1465 The function responsible for encrypting a single block. See below for
1466 a description of this type.
1467 @item gcry_cipher_decrypt_t decrypt
1468 The function responsible for decrypting a single block. See below for
1469 a description of this type.
1470 @item gcry_cipher_stencrypt_t stencrypt
1471 Like `encrypt', for stream ciphers. See below for a description of
1473 @item gcry_cipher_stdecrypt_t stdecrypt
1474 Like `decrypt', for stream ciphers. See below for a description of
1479 @deftp {Data type} gcry_cipher_oid_spec_t
1480 This type is used for associating a user-provided algorithm
1481 implementation with certain OIDs. It contains the following members:
1483 @item const char *oid
1484 Textual representation of the OID.
1486 Cipher mode for which this OID is valid.
1490 @deftp {Data type} gcry_cipher_setkey_t
1491 Type for the `setkey' function, defined as: gcry_err_code_t
1492 (*gcry_cipher_setkey_t) (void *c, const unsigned char *key, unsigned
1496 @deftp {Data type} gcry_cipher_encrypt_t
1497 Type for the `encrypt' function, defined as: gcry_err_code_t
1498 (*gcry_cipher_encrypt_t) (void *c, const unsigned char *outbuf, const
1499 unsigned char *inbuf)
1502 @deftp {Data type} gcry_cipher_decrypt_t
1503 Type for the `decrypt' function, defined as: gcry_err_code_t
1504 (*gcry_cipher_decrypt_t) (void *c, const unsigned char *outbuf, const
1505 unsigned char *inbuf)
1508 @deftp {Data type} gcry_cipher_stencrypt_t
1509 Type for the `stencrypt' function, defined as: gcry_err_code_t
1510 (*gcry_cipher_stencrypt_t) (void *c, const unsigned char *outbuf, const
1511 unsigned char *, unsigned int n)
1514 @deftp {Data type} gcry_cipher_stdecrypt_t
1515 Type for the `stdecrypt' function, defined as: gcry_err_code_t
1516 (*gcry_cipher_stdecrypt_t) (void *c, const unsigned char *outbuf, const
1517 unsigned char *, unsigned int n)
1520 @deftypefun gcry_error_t gcry_cipher_register (gcry_cipher_spec_t *@var{cipher}, unsigned int *algorithm_id, gcry_module_t *@var{module})
1522 Register a new cipher module whose specification can be found in
1523 @var{cipher}. On success, a new algorithm ID is stored in
1524 @var{algorithm_id} and a pointer representing this module is stored
1528 @deftypefun void gcry_cipher_unregister (gcry_module_t @var{module})
1529 Unregister the cipher identified by @var{module}, which must have been
1530 registered with gcry_cipher_register.
1533 @deftypefun gcry_error_t gcry_cipher_list (int *@var{list}, int *@var{list_length})
1534 Get a list consisting of the IDs of the loaded cipher modules. If
1535 @var{list} is zero, write the number of loaded cipher modules to
1536 @var{list_length} and return. If @var{list} is non-zero, the first
1537 *@var{list_length} algorithm IDs are stored in @var{list}, which must
1538 be of according size. In case there are less cipher modules than
1539 *@var{list_length}, *@var{list_length} is updated to the correct
1543 @node Available cipher modes
1544 @section Available cipher modes
1547 @item GCRY_CIPHER_MODE_NONE
1548 No mode specified. This should not be used. The only exception is that
1549 if Libgcrypt is not used in FIPS mode and if any debug flag has been
1550 set, this mode may be used to bypass the actual encryption.
1552 @item GCRY_CIPHER_MODE_ECB
1553 Electronic Codebook mode.
1555 @item GCRY_CIPHER_MODE_CFB
1556 Cipher Feedback mode.
1558 @item GCRY_CIPHER_MODE_CBC
1559 Cipher Block Chaining mode.
1561 @item GCRY_CIPHER_MODE_STREAM
1562 Stream mode, only to be used with stream cipher algorithms.
1564 @item GCRY_CIPHER_MODE_OFB
1565 Output Feedback mode.
1567 @item GCRY_CIPHER_MODE_CTR
1572 @node Working with cipher handles
1573 @section Working with cipher handles
1575 To use a cipher algorithm, you must first allocate an according
1576 handle. This is to be done using the open function:
1578 @deftypefun gcry_error_t gcry_cipher_open (gcry_cipher_hd_t *@var{hd}, int @var{algo}, int @var{mode}, unsigned int @var{flags})
1580 This function creates the context handle required for most of the
1581 other cipher functions and returns a handle to it in `hd'. In case of
1582 an error, an according error code is returned.
1584 The ID of algorithm to use must be specified via @var{algo}. See
1585 @xref{Available ciphers}, for a list of supported ciphers and the
1586 according constants.
1588 Besides using the constants directly, the function
1589 @code{gcry_cipher_map_name} may be used to convert the textual name of
1590 an algorithm into the according numeric ID.
1592 The cipher mode to use must be specified via @var{mode}. See
1593 @xref{Available cipher modes}, for a list of supported cipher modes
1594 and the according constants. Note that some modes are incompatible
1595 with some algorithms - in particular, stream mode
1596 (GCRY_CIPHER_MODE_STREAM) only works with stream ciphers. Any block
1597 cipher mode (GCRY_CIPHER_MODE_ECB, GCRY_CIPHER_MODE_CBC,
1598 GCRY_CIPHER_MODE_CFB, GCRY_CIPHER_MODE_OFB or GCRY_CIPHER_MODE_CTR)
1599 will work with any block cipher algorithm.
1601 The third argument @var{flags} can either be passed as @code{0} or as
1602 the bit-wise OR of the following constants.
1605 @item GCRY_CIPHER_SECURE
1606 Make sure that all operations are allocated in secure memory. This is
1607 useful when the key material is highly confidential.
1608 @item GCRY_CIPHER_ENABLE_SYNC
1609 This flag enables the CFB sync mode, which is a special feature of
1610 Libgcrypt's CFB mode implementation to allow for OpenPGP's CFB variant.
1611 See @code{gcry_cipher_sync}.
1612 @item GCRY_CIPHER_CBC_CTS
1613 Enable cipher text stealing (CTS) for the CBC mode. Cannot be used
1614 simultaneous as GCRY_CIPHER_CBC_MAC. CTS mode makes it possible to
1615 transform data of almost arbitrary size (only limitation is that it
1616 must be greater than the algorithm's block size).
1617 @item GCRY_CIPHER_CBC_MAC
1618 Compute CBC-MAC keyed checksums. This is the same as CBC mode, but
1619 only output the last block. Cannot be used simultaneous as
1620 GCRY_CIPHER_CBC_CTS.
1624 Use the following function to release an existing handle:
1626 @deftypefun void gcry_cipher_close (gcry_cipher_hd_t @var{h})
1628 This function releases the context created by @code{gcry_cipher_open}.
1631 In order to use a handle for performing cryptographic operations, a
1632 `key' has to be set first:
1634 @deftypefun gcry_error_t gcry_cipher_setkey (gcry_cipher_hd_t @var{h}, const void *@var{k}, size_t @var{l})
1636 Set the key @var{k} used for encryption or decryption in the context
1637 denoted by the handle @var{h}. The length @var{l} of the key @var{k}
1638 must match the required length of the algorithm set for this context or
1639 be in the allowed range for algorithms with variable key size. The
1640 function checks this and returns an error if there is a problem. A
1641 caller should always check for an error.
1645 Most crypto modes requires an initialization vector (IV), which
1646 usually is a non-secret random string acting as a kind of salt value.
1647 The CTR mode requires a counter, which is also similar to a salt
1648 value. To set the IV or CTR, use these functions:
1650 @deftypefun gcry_error_t gcry_cipher_setiv (gcry_cipher_hd_t @var{h}, const void *@var{k}, size_t @var{l})
1652 Set the initialization vector used for encryption or decryption. The
1653 vector is passed as the buffer @var{K} of length @var{l} and copied to
1654 internal data structures. The function checks that the IV matches the
1655 requirement of the selected algorithm and mode.
1658 @deftypefun gcry_error_t gcry_cipher_setctr (gcry_cipher_hd_t @var{h}, const void *@var{c}, size_t @var{l})
1660 Set the counter vector used for encryption or decryption. The counter
1661 is passed as the buffer @var{c} of length @var{l} and copied to
1662 internal data structures. The function checks that the counter
1663 matches the requirement of the selected algorithm (i.e., it must be
1664 the same size as the block size).
1667 @deftypefun gcry_error_t gcry_cipher_reset (gcry_cipher_hd_t @var{h})
1669 Set the given handle's context back to the state it had after the last
1670 call to gcry_cipher_setkey and clear the initialization vector.
1672 Note that gcry_cipher_reset is implemented as a macro.
1675 The actual encryption and decryption is done by using one of the
1676 following functions. They may be used as often as required to process
1679 @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})
1681 @code{gcry_cipher_encrypt} is used to encrypt the data. This function
1682 can either work in place or with two buffers. It uses the cipher
1683 context already setup and described by the handle @var{h}. There are 2
1684 ways to use the function: If @var{in} is passed as @code{NULL} and
1685 @var{inlen} is @code{0}, in-place encryption of the data in @var{out} or
1686 length @var{outsize} takes place. With @var{in} being not @code{NULL},
1687 @var{inlen} bytes are encrypted to the buffer @var{out} which must have
1688 at least a size of @var{inlen}. @var{outsize} must be set to the
1689 allocated size of @var{out}, so that the function can check that there
1690 is sufficient space. Note that overlapping buffers are not allowed.
1692 Depending on the selected algorithms and encryption mode, the length of
1693 the buffers must be a multiple of the block size.
1695 The function returns @code{0} on success or an error code.
1699 @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})
1701 @code{gcry_cipher_decrypt} is used to decrypt the data. This function
1702 can either work in place or with two buffers. It uses the cipher
1703 context already setup and described by the handle @var{h}. There are 2
1704 ways to use the function: If @var{in} is passed as @code{NULL} and
1705 @var{inlen} is @code{0}, in-place decryption of the data in @var{out} or
1706 length @var{outsize} takes place. With @var{in} being not @code{NULL},
1707 @var{inlen} bytes are decrypted to the buffer @var{out} which must have
1708 at least a size of @var{inlen}. @var{outsize} must be set to the
1709 allocated size of @var{out}, so that the function can check that there
1710 is sufficient space. Note that overlapping buffers are not allowed.
1712 Depending on the selected algorithms and encryption mode, the length of
1713 the buffers must be a multiple of the block size.
1715 The function returns @code{0} on success or an error code.
1719 OpenPGP (as defined in RFC-2440) requires a special sync operation in
1720 some places. The following function is used for this:
1722 @deftypefun gcry_error_t gcry_cipher_sync (gcry_cipher_hd_t @var{h})
1724 Perform the OpenPGP sync operation on context @var{h}. Note that this
1725 is a no-op unless the context was created with the flag
1726 @code{GCRY_CIPHER_ENABLE_SYNC}
1729 Some of the described functions are implemented as macros utilizing a
1730 catch-all control function. This control function is rarely used
1731 directly but there is nothing which would inhibit it:
1733 @deftypefun gcry_error_t gcry_cipher_ctl (gcry_cipher_hd_t @var{h}, int @var{cmd}, void *@var{buffer}, size_t @var{buflen})
1735 @code{gcry_cipher_ctl} controls various aspects of the cipher module and
1736 specific cipher contexts. Usually some more specialized functions or
1737 macros are used for this purpose. The semantics of the function and its
1738 parameters depends on the the command @var{cmd} and the passed context
1739 handle @var{h}. Please see the comments in the source code
1740 (@code{src/global.c}) for details.
1743 @deftypefun gcry_error_t gcry_cipher_info (gcry_cipher_hd_t @var{h}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes})
1745 @code{gcry_cipher_info} is used to retrieve various
1746 information about a cipher context or the cipher module in general.
1748 Currently no information is available.
1751 @node General cipher functions
1752 @section General cipher functions
1754 To work with the algorithms, several functions are available to map
1755 algorithm names to the internal identifiers, as well as ways to
1756 retrieve information about an algorithm or the current cipher context.
1758 @deftypefun gcry_error_t gcry_cipher_algo_info (int @var{algo}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes})
1760 This function is used to retrieve information on a specific algorithm.
1761 You pass the cipher algorithm ID as @var{algo} and the type of
1762 information requested as @var{what}. The result is either returned as
1763 the return code of the function or copied to the provided @var{buffer}
1764 whose allocated length must be available in an integer variable with the
1765 address passed in @var{nbytes}. This variable will also receive the
1766 actual used length of the buffer.
1768 Here is a list of supported codes for @var{what}:
1770 @c begin constants for gcry_cipher_algo_info
1772 @item GCRYCTL_GET_KEYLEN:
1773 Return the length of the key. If the algorithm supports multiple key
1774 lengths, the maximum supported value is returned. The length is
1775 returned as number of octets (bytes) and not as number of bits in
1776 @var{nbytes}; @var{buffer} must be zero.
1778 @item GCRYCTL_GET_BLKLEN:
1779 Return the block length of the algorithm. The length is returned as a
1780 number of octets in @var{nbytes}; @var{buffer} must be zero.
1782 @item GCRYCTL_TEST_ALGO:
1783 Returns @code{0} when the specified algorithm is available for use.
1784 @var{buffer} and @var{nbytes} must be zero.
1787 @c end constants for gcry_cipher_algo_info
1790 @c end gcry_cipher_algo_info
1792 @deftypefun const char *gcry_cipher_algo_name (int @var{algo})
1794 @code{gcry_cipher_algo_name} returns a string with the name of the
1795 cipher algorithm @var{algo}. If the algorithm is not known or another
1796 error occurred, the string @code{"?"} is returned. This function should
1797 not be used to test for the availability of an algorithm.
1800 @deftypefun int gcry_cipher_map_name (const char *@var{name})
1802 @code{gcry_cipher_map_name} returns the algorithm identifier for the
1803 cipher algorithm described by the string @var{name}. If this algorithm
1804 is not available @code{0} is returned.
1807 @deftypefun int gcry_cipher_mode_from_oid (const char *@var{string})
1809 Return the cipher mode associated with an @acronym{ASN.1} object
1810 identifier. The object identifier is expected to be in the
1811 @acronym{IETF}-style dotted decimal notation. The function returns
1812 @code{0} for an unknown object identifier or when no mode is associated
1817 @c **********************************************************
1818 @c ******************* Public Key *************************
1819 @c **********************************************************
1820 @node Public Key cryptography
1821 @chapter Public Key cryptography
1823 Public key cryptography, also known as asymmetric cryptography, is an
1824 easy way for key management and to provide digital signatures.
1825 Libgcrypt provides two completely different interfaces to
1826 public key cryptography, this chapter explains the one based on
1830 * Available algorithms:: Algorithms supported by the library.
1831 * Used S-expressions:: Introduction into the used S-expression.
1832 * Public key modules:: How to work with public key modules.
1833 * Cryptographic Functions:: Functions for performing the cryptographic actions.
1834 * General public-key related Functions:: General functions, not implementing any cryptography.
1836 * AC Interface:: Alternative interface to public key functions.
1839 @node Available algorithms
1840 @section Available algorithms
1842 Libgcrypt supports the RSA (Rivest-Shamir-Adleman) algorithms as well
1843 as DSA (Digital Signature Algorithm) and Elgamal. The versatile
1844 interface allows to add more algorithms in the future.
1846 @node Used S-expressions
1847 @section Used S-expressions
1849 Libgcrypt's API for asymmetric cryptography is based on data structures
1850 called S-expressions (see
1851 @uref{http://people.csail.mit.edu/@/rivest/@/sexp.html}) and does not work
1852 with contexts as most of the other building blocks of Libgcrypt do.
1854 The following information are stored in S-expressions:
1859 @item plain text data
1861 @item encrypted data
1868 To describe how Libgcrypt expect keys, we use examples. Note that
1876 indicate parameters whereas lowercase words are literals.
1878 Note that all MPI (multi-precision-integers) values are expected to be in
1879 @code{GCRYMPI_FMT_USG} format. An easy way to create S-expressions is
1880 by using @code{gcry_sexp_build} which allows to pass a string with
1881 printf-like escapes to insert MPI values.
1884 * RSA key parameters:: Parameters used with an RSA key.
1885 * DSA key parameters:: Parameters used with a DSA key.
1886 * ECC key parameters:: Parameters used with ECC keys.
1889 @node RSA key parameters
1890 @subsection RSA key parameters
1893 An RSA private key is described by this S-expression:
1907 An RSA public key is described by this S-expression:
1919 RSA public modulus @math{n}.
1921 RSA public exponent @math{e}.
1923 RSA secret exponent @math{d = e^{-1} \bmod (p-1)(q-1)}.
1925 RSA secret prime @math{p}.
1927 RSA secret prime @math{q} with @math{p < q}.
1929 Multiplicative inverse @math{u = p^{-1} \bmod q}.
1932 For signing and decryption the parameters @math{(p, q, u)} are optional
1933 but greatly improve the performance. Either all of these optional
1934 parameters must be given or none of them. They are mandatory for
1937 Note that OpenSSL uses slighly different parameters: @math{q < p} and
1938 @math{u = q^{-1} \bmod p}. To use these parameters you will need to
1939 swap the values and recompute @math{u}. Here is example code to do this:
1942 if (gcry_mpi_cmp (p, q) > 0)
1944 gcry_mpi_swap (p, q);
1945 gcry_mpi_invm (u, p, q);
1952 @node DSA key parameters
1953 @subsection DSA key parameters
1956 A DSA private key is described by this S-expression:
1972 DSA group order @math{q} (which is a prime divisor of @math{p-1}).
1974 DSA group generator @math{g}.
1976 DSA public key value @math{y = g^x \bmod p}.
1978 DSA secret exponent x.
1981 The public key is similar with "private-key" replaced by "public-key"
1985 @node ECC key parameters
1986 @subsection ECC key parameters
1989 An ECC private key is described by this S-expression:
2005 Prime specifying the field @math{GF(p)}.
2008 The two coefficients of the Weierstrass equation @math{y^2 = x^3 + ax + b}
2010 Base point @math{g}.
2014 The point representing the public key @math{Q = dP}.
2016 The private key @math{d}
2019 All point values are encoded in standard format; Libgcrypt does
2020 currently only support uncompressed points, thus the first byte needs to
2023 The public key is similar with "private-key" replaced by "public-key"
2026 If the domain parameters are well-known, the name of this curve may be
2032 (curve "NIST P-192")
2037 The @code{curve} parameter may be given in any case and is used to replace
2041 Currently implemented curves are:
2044 @itemx 1.2.840.10045.3.1.1
2047 The NIST 192 bit curve, its OID, X9.62 and SECP aliases.
2051 The NIST 224 bit curve and its SECP alias.
2054 @itemx 1.2.840.10045.3.1.7
2057 The NIST 256 bit curve, its OID, X9.62 and SECP aliases.
2061 The NIST 384 bit curve and its SECP alias.
2065 The NIST 521 bit curve and its SECP alias.
2068 As usual the OIDs may optionally be prefixed with the string @code{OID.}
2073 @node Public key modules
2074 @section Public key modules
2076 Libgcrypt makes it possible to load additional `public key
2077 modules'; these public key algorithms can be used just like the
2078 algorithms that are built into the library directly. For an
2079 introduction into extension modules, see @xref{Modules}.
2081 @deftp {Data type} gcry_pk_spec_t
2082 This is the `module specification structure' needed for registering
2083 public key modules, which has to be filled in by the user before it
2084 can be used to register a module. It contains the following members:
2087 @item const char *name
2088 The primary name of this algorithm.
2089 @item char **aliases
2090 A list of strings that are `aliases' for the algorithm. The list
2091 must be terminated with a NULL element.
2092 @item const char *elements_pkey
2093 String containing the one-letter names of the MPI values contained in
2095 @item const char *element_skey
2096 String containing the one-letter names of the MPI values contained in
2098 @item const char *elements_enc
2099 String containing the one-letter names of the MPI values that are the
2100 result of an encryption operation using this algorithm.
2101 @item const char *elements_sig
2102 String containing the one-letter names of the MPI values that are the
2103 result of a sign operation using this algorithm.
2104 @item const char *elements_grip
2105 String containing the one-letter names of the MPI values that are to
2106 be included in the `key grip'.
2108 The bitwise-OR of the following flags, depending on the abilities of
2111 @item GCRY_PK_USAGE_SIGN
2112 The algorithm supports signing and verifying of data.
2113 @item GCRY_PK_USAGE_ENCR
2114 The algorithm supports the encryption and decryption of data.
2116 @item gcry_pk_generate_t generate
2117 The function responsible for generating a new key pair. See below for
2118 a description of this type.
2119 @item gcry_pk_check_secret_key_t check_secret_key
2120 The function responsible for checking the sanity of a provided secret
2121 key. See below for a description of this type.
2122 @item gcry_pk_encrypt_t encrypt
2123 The function responsible for encrypting data. See below for a
2124 description of this type.
2125 @item gcry_pk_decrypt_t decrypt
2126 The function responsible for decrypting data. See below for a
2127 description of this type.
2128 @item gcry_pk_sign_t sign
2129 The function responsible for signing data. See below for a description
2131 @item gcry_pk_verify_t verify
2132 The function responsible for verifying that the provided signature
2133 matches the provided data. See below for a description of this type.
2134 @item gcry_pk_get_nbits_t get_nbits
2135 The function responsible for returning the number of bits of a provided
2136 key. See below for a description of this type.
2140 @deftp {Data type} gcry_pk_generate_t
2141 Type for the `generate' function, defined as: gcry_err_code_t
2142 (*gcry_pk_generate_t) (int algo, unsigned int nbits, unsigned long
2143 use_e, gcry_mpi_t *skey, gcry_mpi_t **retfactors)
2146 @deftp {Data type} gcry_pk_check_secret_key_t
2147 Type for the `check_secret_key' function, defined as: gcry_err_code_t
2148 (*gcry_pk_check_secret_key_t) (int algo, gcry_mpi_t *skey)
2151 @deftp {Data type} gcry_pk_encrypt_t
2152 Type for the `encrypt' function, defined as: gcry_err_code_t
2153 (*gcry_pk_encrypt_t) (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
2154 gcry_mpi_t *pkey, int flags)
2157 @deftp {Data type} gcry_pk_decrypt_t
2158 Type for the `decrypt' function, defined as: gcry_err_code_t
2159 (*gcry_pk_decrypt_t) (int algo, gcry_mpi_t *result, gcry_mpi_t *data,
2160 gcry_mpi_t *skey, int flags)
2163 @deftp {Data type} gcry_pk_sign_t
2164 Type for the `sign' function, defined as: gcry_err_code_t
2165 (*gcry_pk_sign_t) (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
2169 @deftp {Data type} gcry_pk_verify_t
2170 Type for the `verify' function, defined as: gcry_err_code_t
2171 (*gcry_pk_verify_t) (int algo, gcry_mpi_t hash, gcry_mpi_t *data,
2172 gcry_mpi_t *pkey, int (*cmp) (void *, gcry_mpi_t), void *opaquev)
2175 @deftp {Data type} gcry_pk_get_nbits_t
2176 Type for the `get_nbits' function, defined as: unsigned
2177 (*gcry_pk_get_nbits_t) (int algo, gcry_mpi_t *pkey)
2180 @deftypefun gcry_error_t gcry_pk_register (gcry_pk_spec_t *@var{pubkey}, unsigned int *algorithm_id, gcry_module_t *@var{module})
2182 Register a new public key module whose specification can be found in
2183 @var{pubkey}. On success, a new algorithm ID is stored in
2184 @var{algorithm_id} and a pointer representing this module is stored
2188 @deftypefun void gcry_pk_unregister (gcry_module_t @var{module})
2189 Unregister the public key module identified by @var{module}, which
2190 must have been registered with gcry_pk_register.
2193 @deftypefun gcry_error_t gcry_pk_list (int *@var{list}, int *@var{list_length})
2194 Get a list consisting of the IDs of the loaded pubkey modules. If
2195 @var{list} is zero, write the number of loaded pubkey modules to
2196 @var{list_length} and return. If @var{list} is non-zero, the first
2197 *@var{list_length} algorithm IDs are stored in @var{list}, which must
2198 be of according size. In case there are less pubkey modules than
2199 *@var{list_length}, *@var{list_length} is updated to the correct
2203 @node Cryptographic Functions
2204 @section Cryptographic Functions
2207 Note that we will in future allow to use keys without p,q and u
2208 specified and may also support other parameters for performance
2213 Some functions operating on S-expressions support `flags', that
2214 influence the operation. These flags have to be listed in a
2215 sub-S-expression named `flags'; the following flags are known:
2219 Use PKCS#1 block type 2 padding.
2221 Do not use a technique called `blinding', which is used by default in
2222 order to prevent leaking of secret information. Blinding is only
2223 implemented by RSA, but it might be implemented by other algorithms in
2224 the future as well, when necessary.
2228 Now that we know the key basics, we can carry on and explain how to
2229 encrypt and decrypt data. In almost all cases the data is a random
2230 session key which is in turn used for the actual encryption of the real
2231 data. There are 2 functions to do this:
2233 @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}})
2235 Obviously a public key must be provided for encryption. It is
2236 expected as an appropriate S-expression (see above) in @var{pkey}.
2237 The data to be encrypted can either be in the simple old format, which
2238 is a very simple S-expression consisting only of one MPI, or it may be
2239 a more complex S-expression which also allows to specify flags for
2240 operation, like e.g. padding rules.
2243 If you don't want to let Libgcrypt handle the padding, you must pass an
2244 appropriate MPI using this expression for @var{data}:
2253 This has the same semantics as the old style MPI only way. @var{MPI} is
2254 the actual data, already padded appropriate for your protocol. Most
2255 systems however use PKCS#1 padding and so you can use this S-expression
2261 (value @var{block}))
2265 Here, the "flags" list has the "pkcs1" flag which let the function know
2266 that it should provide PKCS#1 block type 2 padding. The actual data to
2267 be encrypted is passed as a string of octets in @var{block}. The
2268 function checks that this data actually can be used with the given key,
2269 does the padding and encrypts it.
2271 If the function could successfully perform the encryption, the return
2272 value will be 0 and a a new S-expression with the encrypted result is
2273 allocated and assigned to the variable at the address of @var{r_ciph}.
2274 The caller is responsible to release this value using
2275 @code{gcry_sexp_release}. In case of an error, an error code is
2276 returned and @var{r_ciph} will be set to @code{NULL}.
2279 The returned S-expression has this format when used with RSA:
2288 Where @var{a-mpi} is an MPI with the result of the RSA operation. When
2289 using the Elgamal algorithm, the return value will have this format:
2299 Where @var{a-mpi} and @var{b-mpi} are MPIs with the result of the
2300 Elgamal encryption operation.
2302 @c end gcry_pk_encrypt
2304 @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}})
2306 Obviously a private key must be provided for decryption. It is expected
2307 as an appropriate S-expression (see above) in @var{skey}. The data to
2308 be decrypted must match the format of the result as returned by
2309 @code{gcry_pk_encrypt}, but should be enlarged with a @code{flags}
2321 Note that this function currently does not know of any padding
2322 methods and the caller must do any un-padding on his own.
2325 The function returns 0 on success or an error code. The variable at the
2326 address of @var{r_plain} will be set to NULL on error or receive the
2327 decrypted value on success. The format of @var{r_plain} is a
2328 simple S-expression part (i.e. not a valid one) with just one MPI if
2329 there was no @code{flags} element in @var{data}; if at least an empty
2330 @code{flags} is passed in @var{data}, the format is:
2333 (value @var{plaintext})
2336 @c end gcry_pk_decrypt
2339 Another operation commonly performed using public key cryptography is
2340 signing data. In some sense this is even more important than
2341 encryption because digital signatures are an important instrument for
2342 key management. Libgcrypt supports digital signatures using
2343 2 functions, similar to the encryption functions:
2345 @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}})
2347 This function creates a digital signature for @var{data} using the
2348 private key @var{skey} and place it into the variable at the address of
2349 @var{r_sig}. @var{data} may either be the simple old style S-expression
2350 with just one MPI or a modern and more versatile S-expression which
2351 allows to let Libgcrypt handle padding:
2356 (hash @var{hash-algo} @var{block}))
2360 This example requests to sign the data in @var{block} after applying
2361 PKCS#1 block type 1 style padding. @var{hash-algo} is a string with the
2362 hash algorithm to be encoded into the signature, this may be any hash
2363 algorithm name as supported by Libgcrypt. Most likely, this will be
2364 "sha1", "rmd160" or "md5". It is obvious that the length of @var{block}
2365 must match the size of that message digests; the function checks that
2366 this and other constraints are valid.
2369 If PKCS#1 padding is not required (because the caller does already
2370 provide a padded value), either the old format or better the following
2371 format should be used:
2380 Here, the data to be signed is directly given as an @var{MPI}.
2383 The signature is returned as a newly allocated S-expression in
2384 @var{r_sig} using this format for RSA:
2392 Where @var{s-mpi} is the result of the RSA sign operation. For DSA the
2393 S-expression returned is:
2402 Where @var{r-mpi} and @var{s-mpi} are the result of the DSA sign
2403 operation. For Elgamal signing (which is slow, yields large numbers
2404 and probably is not as secure as the other algorithms), the same format is
2405 used with "elg" replacing "dsa".
2410 The operation most commonly used is definitely the verification of a
2411 signature. Libgcrypt provides this function:
2413 @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}})
2415 This is used to check whether the signature @var{sig} matches the
2416 @var{data}. The public key @var{pkey} must be provided to perform this
2417 verification. This function is similar in its parameters to
2418 @code{gcry_pk_sign} with the exceptions that the public key is used
2419 instead of the private key and that no signature is created but a
2420 signature, in a format as created by @code{gcry_pk_sign}, is passed to
2421 the function in @var{sig}.
2424 The result is 0 for success (i.e. the data matches the signature), or an
2425 error code where the most relevant code is @code{GCRYERR_BAD_SIGNATURE}
2426 to indicate that the signature does not match the provided data.
2429 @c end gcry_pk_verify
2431 @node General public-key related Functions
2432 @section General public-key related Functions
2435 A couple of utility functions are available to retrieve the length of
2436 the key, map algorithm identifiers and perform sanity checks:
2438 @deftypefun {const char *} gcry_pk_algo_name (int @var{algo})
2440 Map the public key algorithm id @var{algo} to a string representation of
2441 the algorithm name. For unknown algorithms this functions returns the
2442 string @code{"?"}. This function should not be used to test for the
2443 availability of an algorithm.
2446 @deftypefun int gcry_pk_map_name (const char *@var{name})
2448 Map the algorithm @var{name} to a public key algorithm Id. Returns 0 if
2449 the algorithm name is not known.
2452 @deftypefun int gcry_pk_test_algo (int @var{algo})
2454 Return 0 if the public key algorithm @var{algo} is available for use.
2455 Note that this is implemented as a macro.
2459 @deftypefun {unsigned int} gcry_pk_get_nbits (gcry_sexp_t @var{key})
2461 Return what is commonly referred as the key length for the given
2462 public or private in @var{key}.
2465 @deftypefun {unsigned char *} gcry_pk_get_keygrip (@w{gcry_sexp_t @var{key}}, @w{unsigned char *@var{array}})
2467 Return the so called "keygrip" which is the SHA-1 hash of the public key
2468 parameters expressed in a way depended on the algorithm. @var{array}
2469 must either provide space for 20 bytes or be @code{NULL}. In the latter
2470 case a newly allocated array of that size is returned. On success a
2471 pointer to the newly allocated space or to @var{array} is returned.
2472 @code{NULL} is returned to indicate an error which is most likely an
2473 unknown algorithm or one where a "keygrip" has not yet been defined.
2474 The function accepts public or secret keys in @var{key}.
2477 @deftypefun gcry_error_t gcry_pk_testkey (gcry_sexp_t @var{key})
2479 Return zero if the private key @var{key} is `sane', an error code otherwise.
2480 Note that it is not possible to check the `saneness' of a public key.
2485 @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}})
2487 Depending on the value of @var{what} return various information about
2488 the public key algorithm with the id @var{algo}. Note that the
2489 function returns @code{-1} on error and the actual error code must be
2490 retrieved using the function @code{gcry_errno}. The currently defined
2491 values for @var{what} are:
2494 @item GCRYCTL_TEST_ALGO:
2495 Return 0 if the specified algorithm is available for use.
2496 @var{buffer} must be @code{NULL}, @var{nbytes} may be passed as
2497 @code{NULL} or point to a variable with the required usage of the
2498 algorithm. This may be 0 for "don't care" or the bit-wise OR of these
2502 @item GCRY_PK_USAGE_SIGN
2503 Algorithm is usable for signing.
2504 @item GCRY_PK_USAGE_ENCR
2505 Algorithm is usable for encryption.
2508 Unless you need to test for the allowed usage, it is in general better
2509 to use the macro gcry_pk_test_algo instead.
2511 @item GCRYCTL_GET_ALGO_USAGE:
2512 Return the usage flags for the given algorithm. An invalid algorithm
2513 return 0. Disabled algorithms are ignored here because we
2514 want to know whether the algorithm is at all capable of a certain usage.
2516 @item GCRYCTL_GET_ALGO_NPKEY
2517 Return the number of elements the public key for algorithm @var{algo}
2518 consist of. Return 0 for an unknown algorithm.
2520 @item GCRYCTL_GET_ALGO_NSKEY
2521 Return the number of elements the private key for algorithm @var{algo}
2522 consist of. Note that this value is always larger than that of the
2523 public key. Return 0 for an unknown algorithm.
2525 @item GCRYCTL_GET_ALGO_NSIGN
2526 Return the number of elements a signature created with the algorithm
2527 @var{algo} consists of. Return 0 for an unknown algorithm or for an
2528 algorithm not capable of creating signatures.
2530 @item GCRYCTL_GET_ALGO_NENC
2531 Return the number of elements a encrypted message created with the algorithm
2532 @var{algo} consists of. Return 0 for an unknown algorithm or for an
2533 algorithm not capable of encryption.
2537 Please note that parameters not required should be passed as @code{NULL}.
2539 @c end gcry_pk_algo_info
2542 @deftypefun gcry_error_t gcry_pk_ctl (@w{int @var{cmd}}, @w{void *@var{buffer}}, @w{size_t @var{buflen}})
2544 This is a general purpose function to perform certain control
2545 operations. @var{cmd} controls what is to be done. The return value is
2546 0 for success or an error code. Currently supported values for
2550 @item GCRYCTL_DISABLE_ALGO
2551 Disable the algorithm given as an algorithm id in @var{buffer}.
2552 @var{buffer} must point to an @code{int} variable with the algorithm id
2553 and @var{buflen} must have the value @code{sizeof (int)}.
2560 Libgcrypt also provides a function for generating public key
2563 @deftypefun gcry_error_t gcry_pk_genkey (@w{gcry_sexp_t *@var{r_key}}, @w{gcry_sexp_t @var{parms}})
2565 This function create a new public key pair using information given in
2566 the S-expression @var{parms} and stores the private and the public key
2567 in one new S-expression at the address given by @var{r_key}. In case of
2568 an error, @var{r_key} is set to @code{NULL}. The return code is 0 for
2569 success or an error code otherwise.
2572 Here is an example for @var{parms} for creating a 1024 bit RSA key:
2581 To create an Elgamal key, substitute "elg" for "rsa" and to create a DSA
2582 key use "dsa". Valid ranges for the key length depend on the
2583 algorithms; all commonly used key lengths are supported. Currently
2584 supported parameters are:
2588 This is always required to specify the length of the key. The argument
2589 is a string with a number in C-notation. The value should be a multiple
2592 @item curve @var{name}
2593 For ECC a named curve may be used instead of giving the number of
2594 requested bits. This allows to request a specific curve to override a
2595 default selection Libgcrypt would have taken if @code{nbits} has been
2596 given. The available names are listed with the description of the ECC
2597 public key parameters.
2600 This is only used with RSA to give a hint for the public exponent. The
2601 value will be used as a base to test for a usable exponent. Some values
2606 Use a secure and fast value. This is currently the number 41.
2608 Use a secure value as required by some specification. This is currently
2615 If this parameter is not used, Libgcrypt uses for historic reasons
2619 This is only meanigful for DSA keys. If it is given the DSA key is
2620 generated with a Q parameyer of this size. If it is not given or zero
2621 Q is deduced from NBITS in this way:
2623 @item 512 <= N <= 1024
2634 Note that in this case only the values for N, as given in the table,
2635 are allowed. When specifying Q all values of N in the range 512 to
2636 15680 are valid as long as they are multiples of 8.
2639 This is only meaningful for RSA keys. This is a flag with no value. If
2640 given the RSA key is created using a faster and a somewhat less secure
2641 random number generator. This flag may be used for keys which are only
2642 used for a short time and do not require full cryptographic strength.
2646 @c end table of parameters
2649 The key pair is returned in a format depending on the algorithm. Both
2650 private and public keys are returned in one container and may be
2651 accompanied by some miscellaneous information.
2654 As an example, here is what the Elgamal key generation returns:
2670 (pm1-factors @var{n1 n2 ... nn})))
2674 As you can see, some of the information is duplicated, but this provides
2675 an easy way to extract either the public or the private key. Note that
2676 the order of the elements is not defined, e.g. the private key may be
2677 stored before the public key. @var{n1 n2 ... nn} is a list of prime
2678 numbers used to composite @var{p-mpi}; this is in general not a very
2681 @c end gcry_pk_genkey
2684 @section Alternative Public Key Interface
2686 This section documents the alternative interface to asymmetric
2687 cryptography (ac) that is not based on S-expressions, but on native C
2688 data structures. As opposed to the pk interface described in the
2689 former chapter, this one follows an open/use/close paradigm like other
2690 building blocks of the library.
2692 @strong{This interface has a few known problems; most noteworthy an
2693 inherent tendency to leak memory. It might not be available in
2694 forthcoming versions Libgcrypt.}
2698 * Available asymmetric algorithms:: List of algorithms supported by the library.
2699 * Working with sets of data:: How to work with sets of data.
2700 * Working with IO objects:: How to work with IO objects.
2701 * Working with handles:: How to use handles.
2702 * Working with keys:: How to work with keys.
2703 * Using cryptographic functions:: How to perform cryptographic operations.
2704 * Handle-independent functions:: General functions independent of handles.
2707 @node Available asymmetric algorithms
2708 @subsection Available asymmetric algorithms
2710 Libgcrypt supports the RSA (Rivest-Shamir-Adleman)
2711 algorithms as well as DSA (Digital Signature Algorithm) and Elgamal.
2712 The versatile interface allows to add more algorithms in the future.
2714 @deftp {Data type} gcry_ac_id_t
2716 The following constants are defined for this type:
2720 Rivest-Shamir-Adleman
2722 Digital Signature Algorithm
2726 Elgamal, encryption only.
2730 @node Working with sets of data
2731 @subsection Working with sets of data
2733 In the context of this interface the term `data set' refers to a list
2734 of `named MPI values' that is used by functions performing
2735 cryptographic operations; a named MPI value is a an MPI value,
2736 associated with a label.
2738 Such data sets are used for representing keys, since keys simply
2739 consist of a variable amount of numbers. Furthermore some functions
2740 return data sets to the caller that are to be provided to other
2743 This section documents the data types, symbols and functions that are
2744 relevant for working with data sets.
2746 @deftp {Data type} gcry_ac_data_t
2750 The following flags are supported:
2753 @item GCRY_AC_FLAG_DEALLOC
2754 Used for storing data in a data set. If given, the data will be
2755 released by the library. Note that whenever one of the ac functions
2756 is about to release objects because of this flag, the objects are
2757 expected to be stored in memory allocated through the Libgcrypt memory
2758 management. In other words: gcry_free() is used instead of free().
2760 @item GCRY_AC_FLAG_COPY
2761 Used for storing/retrieving data in/from a data set. If given, the
2762 library will create copies of the provided/contained data, which will
2763 then be given to the user/associated with the data set.
2766 @deftypefun gcry_error_t gcry_ac_data_new (gcry_ac_data_t *@var{data})
2767 Creates a new, empty data set and stores it in @var{data}.
2770 @deftypefun void gcry_ac_data_destroy (gcry_ac_data_t @var{data})
2771 Destroys the data set @var{data}.
2774 @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})
2775 Add the value @var{mpi} to @var{data} with the label @var{name}. If
2776 @var{flags} contains GCRY_AC_FLAG_COPY, the data set will contain
2777 copies of @var{name} and @var{mpi}. If @var{flags} contains
2778 GCRY_AC_FLAG_DEALLOC or GCRY_AC_FLAG_COPY, the values
2779 contained in the data set will be deallocated when they are to be
2780 removed from the data set.
2783 @deftypefun gcry_error_t gcry_ac_data_copy (gcry_ac_data_t *@var{data_cp}, gcry_ac_data_t @var{data})
2784 Create a copy of the data set @var{data} and store it in
2785 @var{data_cp}. FIXME: exact semantics undefined.
2788 @deftypefun unsigned int gcry_ac_data_length (gcry_ac_data_t @var{data})
2789 Returns the number of named MPI values inside of the data set
2793 @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})
2794 Store the value labelled with @var{name} found in @var{data} in
2795 @var{mpi}. If @var{flags} contains GCRY_AC_FLAG_COPY, store a copy of
2796 the @var{mpi} value contained in the data set. @var{mpi} may be NULL
2797 (this might be useful for checking the existence of an MPI with
2801 @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})
2802 Stores in @var{name} and @var{mpi} the named @var{mpi} value contained
2803 in the data set @var{data} with the index @var{idx}. If @var{flags}
2804 contains GCRY_AC_FLAG_COPY, store copies of the values contained in
2805 the data set. @var{name} or @var{mpi} may be NULL.
2808 @deftypefun void gcry_ac_data_clear (gcry_ac_data_t @var{data})
2809 Destroys any values contained in the data set @var{data}.
2812 @deftypefun gcry_error_t gcry_ac_data_to_sexp (gcry_ac_data_t @var{data}, gcry_sexp_t *@var{sexp}, const char **@var{identifiers})
2813 This function converts the data set @var{data} into a newly created
2814 S-Expression, which is to be stored in @var{sexp}; @var{identifiers}
2815 is a NULL terminated list of C strings, which specifies the structure
2816 of the S-Expression.
2820 If @var{identifiers} is a list of pointers to the strings ``foo'' and
2821 ``bar'' and if @var{data} is a data set containing the values ``val1 =
2822 0x01'' and ``val2 = 0x02'', then the resulting S-Expression will look
2823 like this: (foo (bar ((val1 0x01) (val2 0x02))).
2826 @deftypefun gcry_error gcry_ac_data_from_sexp (gcry_ac_data_t *@var{data}, gcry_sexp_t @var{sexp}, const char **@var{identifiers})
2827 This function converts the S-Expression @var{sexp} into a newly
2828 created data set, which is to be stored in @var{data};
2829 @var{identifiers} is a NULL terminated list of C strings, which
2830 specifies the structure of the S-Expression. If the list of
2831 identifiers does not match the structure of the S-Expression, the
2835 @node Working with IO objects
2836 @subsection Working with IO objects
2838 Note: IO objects are currently only used in the context of message
2839 encoding/decoding and encryption/signature schemes.
2841 @deftp {Data type} {gcry_ac_io_t}
2842 @code{gcry_ac_io_t} is the type to be used for IO objects.
2845 IO objects provide an uniform IO layer on top of different underlying
2846 IO mechanisms; either they can be used for providing data to the
2847 library (mode is GCRY_AC_IO_READABLE) or they can be used for
2848 retrieving data from the library (mode is GCRY_AC_IO_WRITABLE).
2850 IO object need to be initialized by calling on of the following
2853 @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}, ...);
2854 Initialize @var{ac_io} according to @var{mode}, @var{type} and the
2855 variable list of arguments. The list of variable arguments to specify
2856 depends on the given @var{type}.
2859 @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});
2860 Initialize @var{ac_io} according to @var{mode}, @var{type} and the
2861 variable list of arguments @var{ap}. The list of variable arguments
2862 to specify depends on the given @var{type}.
2865 The following types of IO objects exist:
2868 @item GCRY_AC_IO_STRING
2869 In case of GCRY_AC_IO_READABLE the IO object will provide data from a
2870 memory string. Arguments to specify at initialization time:
2872 @item unsigned char *
2873 Pointer to the beginning of the memory string
2875 Size of the memory string
2877 In case of GCRY_AC_IO_WRITABLE the object will store retrieved data in
2878 a newly allocated memory string. Arguments to specify at
2879 initialization time:
2881 @item unsigned char **
2882 Pointer to address, at which the pointer to the newly created memory
2883 string is to be stored
2885 Pointer to address, at which the size of the newly created memory
2886 string is to be stored
2889 @item GCRY_AC_IO_CALLBACK
2890 In case of GCRY_AC_IO_READABLE the object will forward read requests
2891 to a provided callback function. Arguments to specify at
2892 initialization time:
2894 @item gcry_ac_data_read_cb_t
2895 Callback function to use
2897 Opaque argument to provide to the callback function
2899 In case of GCRY_AC_IO_WRITABLE the object will forward write requests
2900 to a provided callback function. Arguments to specify at
2901 initialization time:
2903 @item gcry_ac_data_write_cb_t
2904 Callback function to use
2906 Opaque argument to provide to the callback function
2910 @node Working with handles
2911 @subsection Working with handles
2913 In order to use an algorithm, an according handle must be created.
2914 This is done using the following function:
2916 @deftypefun gcry_error_t gcry_ac_open (gcry_ac_handle_t *@var{handle}, int @var{algorithm}, int @var{flags})
2918 Creates a new handle for the algorithm @var{algorithm} and stores it
2919 in @var{handle}. @var{flags} is not used currently.
2921 @var{algorithm} must be a valid algorithm ID, see @xref{Available
2922 asymmetric algorithms}, for a list of supported algorithms and the
2923 according constants. Besides using the listed constants directly, the
2924 functions @code{gcry_pk_name_to_id} may be used to convert the textual
2925 name of an algorithm into the according numeric ID.
2928 @deftypefun void gcry_ac_close (gcry_ac_handle_t @var{handle})
2929 Destroys the handle @var{handle}.
2932 @node Working with keys
2933 @subsection Working with keys
2935 @deftp {Data type} gcry_ac_key_type_t
2939 @item GCRY_AC_KEY_SECRET
2940 Specifies a secret key.
2941 @item GCRY_AC_KEY_PUBLIC
2942 Specifies a public key.
2946 @deftp {Data type} gcry_ac_key_t
2947 This type represents a single `key', either a secret one or a public
2951 @deftp {Data type} gcry_ac_key_pair_t
2952 This type represents a `key pair' containing a secret and a public key.
2955 Key data structures can be created in two different ways; a new key
2956 pair can be generated, resulting in ready-to-use key. Alternatively a
2957 key can be initialized from a given data set.
2959 @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})
2960 Creates a new key of type @var{type}, consisting of the MPI values
2961 contained in the data set @var{data} and stores it in @var{key}.
2964 @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})
2966 Generates a new key pair via the handle @var{handle} of @var{NBITS}
2967 bits and stores it in @var{key_pair}.
2969 In case non-standard settings are wanted, a pointer to a structure of
2970 type @code{gcry_ac_key_spec_<algorithm>_t}, matching the selected
2971 algorithm, can be given as @var{key_spec}. @var{misc_data} is not
2972 used yet. Such a structure does only exist for RSA. A description
2973 of the members of the supported structures follows.
2976 @item gcry_ac_key_spec_rsa_t
2979 Generate the key pair using a special @code{e}. The value of @code{e}
2980 has the following meanings:
2983 Let Libgcrypt decide what exponent should be used.
2985 Request the use of a ``secure'' exponent; this is required by some
2986 specification to be 65537.
2988 Try starting at this value until a working exponent is found. Note
2989 that the current implementation leaks some information about the
2990 private key because the incrementation used is not randomized. Thus,
2991 this function will be changed in the future to return a random
2992 exponent of the given size.
3000 gcry_ac_key_pair_t key_pair;
3001 gcry_ac_key_spec_rsa_t rsa_spec;
3003 rsa_spec.e = gcry_mpi_new (0);
3004 gcry_mpi_set_ui (rsa_spec.e, 1);
3006 err = gcry_ac_open (&handle, GCRY_AC_RSA, 0);
3009 err = gcry_ac_key_pair_generate (handle, 1024, &rsa_spec, &key_pair, NULL);
3016 @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})
3017 Returns the key of type @var{which} out of the key pair
3021 @deftypefun void gcry_ac_key_destroy (gcry_ac_key_t @var{key})
3022 Destroys the key @var{key}.
3025 @deftypefun void gcry_ac_key_pair_destroy (gcry_ac_key_pair_t @var{key_pair})
3026 Destroys the key pair @var{key_pair}.
3029 @deftypefun gcry_ac_data_t gcry_ac_key_data_get (gcry_ac_key_t @var{key})
3030 Returns the data set contained in the key @var{key}.
3033 @deftypefun gcry_error_t gcry_ac_key_test (gcry_ac_handle_t @var{handle}, gcry_ac_key_t @var{key})
3034 Verifies that the private key @var{key} is sane via @var{handle}.
3037 @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})
3038 Stores the number of bits of the key @var{key} in @var{nbits} via @var{handle}.
3041 @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})
3042 Writes the 20 byte long key grip of the key @var{key} to
3043 @var{key_grip} via @var{handle}.
3046 @node Using cryptographic functions
3047 @subsection Using cryptographic functions
3049 The following flags might be relevant:
3052 @item GCRY_AC_FLAG_NO_BLINDING
3053 Disable any blinding, which might be supported by the chosen
3054 algorithm; blinding is the default.
3057 There exist two kinds of cryptographic functions available through the
3058 ac interface: primitives, and high-level functions.
3060 Primitives deal with MPIs (data sets) directly; what they provide is
3061 direct access to the cryptographic operations provided by an algorithm
3064 High-level functions deal with octet strings, according to a specified
3065 ``scheme''. Schemes make use of ``encoding methods'', which are
3066 responsible for converting the provided octet strings into MPIs, which
3067 are then forwared to the cryptographic primitives. Since schemes are
3068 to be used for a special purpose in order to achieve a particular
3069 security goal, there exist ``encryption schemes'' and ``signature
3070 schemes''. Encoding methods can be used seperately or implicitly
3073 What follows is a description of the cryptographic primitives.
3075 @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})
3076 Encrypts the plain text MPI value @var{data_plain} with the key public
3077 @var{key} under the control of the flags @var{flags} and stores the
3078 resulting data set into @var{data_encrypted}.
3081 @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})
3082 Decrypts the encrypted data contained in the data set
3083 @var{data_encrypted} with the secret key KEY under the control of the
3084 flags @var{flags} and stores the resulting plain text MPI value in
3088 @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})
3089 Signs the data contained in @var{data} with the secret key @var{key}
3090 and stores the resulting signature in the data set
3091 @var{data_signature}.
3094 @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})
3095 Verifies that the signature contained in the data set
3096 @var{data_signature} is indeed the result of signing the data
3097 contained in @var{data} with the secret key belonging to the public
3101 What follows is a description of the high-level functions.
3103 The type ``gcry_ac_em_t'' is used for specifying encoding methods; the
3104 following methods are supported:
3107 @item GCRY_AC_EME_PKCS_V1_5
3108 PKCS-V1_5 Encoding Method for Encryption. Options must be provided
3109 through a pointer to a correctly initialized object of type
3110 gcry_ac_eme_pkcs_v1_5_t.
3112 @item GCRY_AC_EMSA_PKCS_V1_5
3113 PKCS-V1_5 Encoding Method for Signatures with Appendix. Options must
3114 be provided through a pointer to a correctly initialized object of
3115 type gcry_ac_emsa_pkcs_v1_5_t.
3118 Option structure types:
3121 @item gcry_ac_eme_pkcs_v1_5_t
3123 @item gcry_ac_key_t key
3124 @item gcry_ac_handle_t handle
3126 @item gcry_ac_emsa_pkcs_v1_5_t
3128 @item gcry_md_algo_t md
3133 Encoding methods can be used directly through the following functions:
3135 @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})
3136 Encodes the message contained in @var{m} of size @var{m_n} according
3137 to @var{method}, @var{flags} and @var{options}. The newly created
3138 encoded message is stored in @var{em} and @var{em_n}.
3141 @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})
3142 Decodes the message contained in @var{em} of size @var{em_n} according
3143 to @var{method}, @var{flags} and @var{options}. The newly created
3144 decoded message is stored in @var{m} and @var{m_n}.
3147 The type ``gcry_ac_scheme_t'' is used for specifying schemes; the
3148 following schemes are supported:
3151 @item GCRY_AC_ES_PKCS_V1_5
3152 PKCS-V1_5 Encryption Scheme. No options can be provided.
3153 @item GCRY_AC_SSA_PKCS_V1_5
3154 PKCS-V1_5 Signature Scheme (with Appendix). Options can be provided
3155 through a pointer to a correctly initialized object of type
3156 gcry_ac_ssa_pkcs_v1_5_t.
3159 Option structure types:
3162 @item gcry_ac_ssa_pkcs_v1_5_t
3164 @item gcry_md_algo_t md
3168 The functions implementing schemes:
3170 @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})
3171 Encrypts the plain text readable from @var{io_message} through
3172 @var{handle} with the public key @var{key} according to @var{scheme},
3173 @var{flags} and @var{opts}. If @var{opts} is not NULL, it has to be a
3174 pointer to a structure specific to the chosen scheme (gcry_ac_es_*_t).
3175 The encrypted message is written to @var{io_cipher}.
3178 @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})
3179 Decrypts the cipher text readable from @var{io_cipher} through
3180 @var{handle} with the secret key @var{key} according to @var{scheme},
3181 @var{flags} and @var{opts}. If @var{opts} is not NULL, it has to be a
3182 pointer to a structure specific to the chosen scheme (gcry_ac_es_*_t).
3183 The decrypted message is written to @var{io_message}.
3186 @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})
3187 Signs the message readable from @var{io_message} through @var{handle}
3188 with the secret key @var{key} according to @var{scheme}, @var{flags}
3189 and @var{opts}. If @var{opts} is not NULL, it has to be a pointer to
3190 a structure specific to the chosen scheme (gcry_ac_ssa_*_t). The
3191 signature is written to @var{io_signature}.
3194 @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})
3195 Verifies through @var{handle} that the signature readable from
3196 @var{io_signature} is indeed the result of signing the message
3197 readable from @var{io_message} with the secret key belonging to the
3198 public key @var{key} according to @var{scheme} and @var{opts}. If
3199 @var{opts} is not NULL, it has to be an anonymous structure
3200 (gcry_ac_ssa_*_t) specific to the chosen scheme.
3203 @node Handle-independent functions
3204 @subsection Handle-independent functions
3206 These two functions are deprecated; do not use them for new code.
3208 @deftypefun gcry_error_t gcry_ac_id_to_name (gcry_ac_id_t @var{algorithm}, const char **@var{name})
3209 Stores the textual representation of the algorithm whose id is given
3210 in @var{algorithm} in @var{name}. Deprecated; use @code{gcry_pk_algo_name}.
3213 @deftypefun gcry_error_t gcry_ac_name_to_id (const char *@var{name}, gcry_ac_id_t *@var{algorithm})
3214 Stores the numeric ID of the algorithm whose textual representation is
3215 contained in @var{name} in @var{algorithm}. Deprecated; use
3216 @code{gcry_pk_map_name}.
3219 @c **********************************************************
3220 @c ******************* Hash Functions *********************
3221 @c **********************************************************
3225 Libgcrypt provides an easy and consistent to use interface for hashing.
3226 Hashing is buffered and several hash algorithms can be updated at once.
3227 It is possible to compute a MAC using the same routines. The
3228 programming model follows an open/process/close paradigm and is in that
3229 similar to other building blocks provided by Libgcrypt.
3231 For convenience reasons, a few cyclic redundancy check value operations
3235 * Available hash algorithms:: List of hash algorithms supported by the library.
3236 * Hash algorithm modules:: How to work with hash algorithm modules.
3237 * Working with hash algorithms:: List of functions related to hashing.
3240 @node Available hash algorithms
3241 @section Available hash algorithms
3243 @c begin table of hash algorithms
3246 This is not a real algorithm but used by some functions as an error
3247 return value. This constant is guaranteed to have the value @code{0}.
3250 This is the SHA-1 algorithm which yields a message digest of 20 bytes.
3252 @item GCRY_MD_RMD160
3253 This is the 160 bit version of the RIPE message digest (RIPE-MD-160).
3254 Like SHA-1 it also yields a digest of 20 bytes.
3257 This is the well known MD5 algorithm, which yields a message digest of
3261 This is the MD4 algorithm, which yields a message digest of 16 bytes.
3264 This is an reserved identifier for MD-2; there is no implementation yet.
3267 This is the TIGER/192 algorithm which yields a message digest of 24 bytes.
3270 This is an reserved for the HAVAL algorithm with 5 passes and 160
3271 bit. It yields a message digest of 20 bytes. Note that there is no
3272 implementation yet available.
3274 @item GCRY_MD_SHA224
3275 This is the SHA-224 algorithm which yields a message digest of 28 bytes.
3276 See Change Notice 1 for FIPS 180-2 for the specification.
3278 @item GCRY_MD_SHA256
3279 This is the SHA-256 algorithm which yields a message digest of 32 bytes.
3280 See FIPS 180-2 for the specification.
3282 @item GCRY_MD_SHA384
3283 This is the SHA-384 algorithm which yields a message digest of 48 bytes.
3284 See FIPS 180-2 for the specification.
3286 @item GCRY_MD_SHA512
3287 This is the SHA-384 algorithm which yields a message digest of 64 bytes.
3288 See FIPS 180-2 for the specification.
3291 This is the ISO 3309 and ITU-T V.42 cyclic redundancy check. It
3292 yields an output of 4 bytes.
3294 @item GCRY_MD_CRC32_RFC1510
3295 This is the above cyclic redundancy check function, as modified by RFC
3296 1510. It yields an output of 4 bytes.
3298 @item GCRY_MD_CRC24_RFC2440
3299 This is the OpenPGP cyclic redundancy check function. It yields an
3302 @item GCRY_MD_WHIRLPOOL
3303 This is the Whirlpool algorithm which yields a message digest of 64
3307 @c end table of hash algorithms
3309 @node Hash algorithm modules
3310 @section Hash algorithm modules
3312 Libgcrypt makes it possible to load additional `message
3313 digest modules'; these digests can be used just like the message digest
3314 algorithms that are built into the library directly. For an
3315 introduction into extension modules, see @xref{Modules}.
3317 @deftp {Data type} gcry_md_spec_t
3318 This is the `module specification structure' needed for registering
3319 message digest modules, which has to be filled in by the user before
3320 it can be used to register a module. It contains the following
3324 @item const char *name
3325 The primary name of this algorithm.
3326 @item unsigned char *asnoid
3327 Array of bytes that form the ASN OID.
3329 Length of bytes in `asnoid'.
3330 @item gcry_md_oid_spec_t *oids
3331 A list of OIDs that are to be associated with the algorithm. The
3332 list's last element must have it's `oid' member set to NULL. See
3333 below for an explanation of this type. See below for an explanation
3336 Length of the message digest algorithm. See below for an explanation
3338 @item gcry_md_init_t init
3339 The function responsible for initializing a handle. See below for an
3340 explanation of this type.
3341 @item gcry_md_write_t write
3342 The function responsible for writing data into a message digest
3343 context. See below for an explanation of this type.
3344 @item gcry_md_final_t final
3345 The function responsible for `finalizing' a message digest context.
3346 See below for an explanation of this type.
3347 @item gcry_md_read_t read
3348 The function responsible for reading out a message digest result. See
3349 below for an explanation of this type.
3350 @item size_t contextsize
3351 The size of the algorithm-specific `context', that should be
3352 allocated for each handle.
3356 @deftp {Data type} gcry_md_oid_spec_t
3357 This type is used for associating a user-provided algorithm
3358 implementation with certain OIDs. It contains the following members:
3361 @item const char *oidstring
3362 Textual representation of the OID.
3366 @deftp {Data type} gcry_md_init_t
3367 Type for the `init' function, defined as: void (*gcry_md_init_t) (void
3371 @deftp {Data type} gcry_md_write_t
3372 Type for the `write' function, defined as: void (*gcry_md_write_t)
3373 (void *c, unsigned char *buf, size_t nbytes)
3376 @deftp {Data type} gcry_md_final_t
3377 Type for the `final' function, defined as: void (*gcry_md_final_t)
3381 @deftp {Data type} gcry_md_read_t
3382 Type for the `read' function, defined as: unsigned char
3383 *(*gcry_md_read_t) (void *c)
3386 @deftypefun gcry_error_t gcry_md_register (gcry_md_spec_t *@var{digest}, unsigned int *algorithm_id, gcry_module_t *@var{module})
3388 Register a new digest module whose specification can be found in
3389 @var{digest}. On success, a new algorithm ID is stored in
3390 @var{algorithm_id} and a pointer representing this module is stored
3394 @deftypefun void gcry_md_unregister (gcry_module_t @var{module})
3395 Unregister the digest identified by @var{module}, which must have been
3396 registered with gcry_md_register.
3399 @deftypefun gcry_error_t gcry_md_list (int *@var{list}, int *@var{list_length})
3400 Get a list consisting of the IDs of the loaded message digest modules.
3401 If @var{list} is zero, write the number of loaded message digest
3402 modules to @var{list_length} and return. If @var{list} is non-zero,
3403 the first *@var{list_length} algorithm IDs are stored in @var{list},
3404 which must be of according size. In case there are less message
3405 digests modules than *@var{list_length}, *@var{list_length} is updated
3406 to the correct number.
3409 @node Working with hash algorithms
3410 @section Working with hash algorithms
3412 To use most of these function it is necessary to create a context;
3415 @deftypefun gcry_error_t gcry_md_open (gcry_md_hd_t *@var{hd}, int @var{algo}, unsigned int @var{flags})
3417 Create a message digest object for algorithm @var{algo}. @var{flags}
3418 may be given as an bitwise OR of constants described below. @var{algo}
3419 may be given as @code{0} if the algorithms to use are later set using
3420 @code{gcry_md_enable}. @var{hd} is guaranteed to either receive a valid
3423 For a list of supported algorithms, see @xref{Available hash
3426 The flags allowed for @var{mode} are:
3428 @c begin table of hash flags
3430 @item GCRY_MD_FLAG_SECURE
3431 Allocate all buffers and the resulting digest in "secure memory". Use
3432 this is the hashed data is highly confidential.
3434 @item GCRY_MD_FLAG_HMAC
3435 Turn the algorithm into a HMAC message authentication algorithm. This
3436 only works if just one algorithm is enabled for the handle. Note that the function
3437 @code{gcry_md_setkey} must be used to set the MAC key. If you want CBC
3438 message authentication codes based on a cipher, see @xref{Working with
3442 @c begin table of hash flags
3444 You may use the function @code{gcry_md_is_enabled} to later check
3445 whether an algorithm has been enabled.
3448 @c end function gcry_md_open
3450 If you want to calculate several hash algorithms at the same time, you
3451 have to use the following function right after the @code{gcry_md_open}:
3453 @deftypefun gcry_error_t gcry_md_enable (gcry_md_hd_t @var{h}, int @var{algo})
3455 Add the message digest algorithm @var{algo} to the digest object
3456 described by handle @var{h}. Duplicated enabling of algorithms is
3457 detected and ignored.
3460 If the flag @code{GCRY_MD_FLAG_HMAC} was used, the key for the MAC must
3461 be set using the function:
3463 @deftypefun gcry_error_t gcry_md_setkey (gcry_md_hd_t @var{h}, const void *@var{key}, size_t @var{keylen})
3465 For use with the HMAC feature, set the MAC key to the value of @var{key}
3466 of length @var{keylen}.
3470 After you are done with the hash calculation, you should release the
3473 @deftypefun void gcry_md_close (gcry_md_hd_t @var{h})
3475 Release all resources of hash context @var{h}. @var{h} should not be
3476 used after a call to this function. A @code{NULL} passed as @var{h} is
3481 Often you have to do several hash operations using the same algorithm.
3482 To avoid the overhead of creating and releasing context, a reset function
3485 @deftypefun void gcry_md_reset (gcry_md_hd_t @var{h})
3487 Reset the current context to its initial state. This is effectively
3488 identical to a close followed by an open and enabling all currently
3493 Often it is necessary to start hashing some data and then continue to
3494 hash different data. To avoid hashing the same data several times (which
3495 might not even be possible if the data is received from a pipe), a
3496 snapshot of the current hash context can be taken and turned into a new
3499 @deftypefun gcry_error_t gcry_md_copy (gcry_md_hd_t *@var{handle_dst}, gcry_md_hd_t @var{handle_src})
3501 Create a new digest object as an exact copy of the object described by
3502 handle @var{handle_src} and store it in @var{handle_dst}. The context
3503 is not reset and you can continue to hash data using this context and
3504 independently using the original context.
3508 Now that we have prepared everything to calculate hashes, it is time to
3509 see how it is actually done. There are two ways for this, one to
3510 update the hash with a block of memory and one macro to update the hash
3511 by just one character. Both methods can be used on the same hash context.
3513 @deftypefun void gcry_md_write (gcry_md_hd_t @var{h}, const void *@var{buffer}, size_t @var{length})
3515 Pass @var{length} bytes of the data in @var{buffer} to the digest object
3516 with handle @var{h} to update the digest values. This
3517 function should be used for large blocks of data.
3520 @deftypefun void gcry_md_putc (gcry_md_hd_t @var{h}, int @var{c})
3522 Pass the byte in @var{c} to the digest object with handle @var{h} to
3523 update the digest value. This is an efficient function, implemented as
3524 a macro to buffer the data before an actual update.
3527 The semantics of the hash functions do not provide for reading out intermediate
3528 message digests because the calculation must be finalized first. This
3529 finalization may for example include the number of bytes hashed in the
3530 message digest or some padding.
3532 @deftypefun void gcry_md_final (gcry_md_hd_t @var{h})
3534 Finalize the message digest calculation. This is not really needed
3535 because @code{gcry_md_read} does this implicitly. After this has been
3536 done no further updates (by means of @code{gcry_md_write} or
3537 @code{gcry_md_putc} are allowed. Only the first call to this function
3538 has an effect. It is implemented as a macro.
3541 The way to read out the calculated message digest is by using the
3544 @deftypefun unsigned char *gcry_md_read (gcry_md_hd_t @var{h}, int @var{algo})
3546 @code{gcry_md_read} returns the message digest after finalizing the
3547 calculation. This function may be used as often as required but it will
3548 always return the same value for one handle. The returned message digest
3549 is allocated within the message context and therefore valid until the
3550 handle is released or reseted (using @code{gcry_md_close} or
3551 @code{gcry_md_reset}. @var{algo} may be given as 0 to return the only
3552 enabled message digest or it may specify one of the enabled algorithms.
3553 The function does return @code{NULL} if the requested algorithm has not
3557 Because it is often necessary to get the message digest of one block of
3558 memory, a fast convenience function is available for this task:
3560 @deftypefun void gcry_md_hash_buffer (int @var{algo}, void *@var{digest}, const void *@var{buffer}, size_t @var{length});
3562 @code{gcry_md_hash_buffer} is a shortcut function to calculate a message
3563 digest of a buffer. This function does not require a context and
3564 immediately returns the message digest of the @var{length} bytes at
3565 @var{buffer}. @var{digest} must be allocated by the caller, large
3566 enough to hold the message digest yielded by the the specified algorithm
3567 @var{algo}. This required size may be obtained by using the function
3568 @code{gcry_md_get_algo_dlen}.
3570 Note that this function will abort the process if an unavailable
3574 @c ***********************************
3575 @c ***** MD info functions ***********
3576 @c ***********************************
3578 Hash algorithms are identified by internal algorithm numbers (see
3579 @code{gcry_md_open} for a list). However, in most applications they are
3580 used by names, so two functions are available to map between string
3581 representations and hash algorithm identifiers.
3583 @deftypefun const char *gcry_md_algo_name (int @var{algo})
3585 Map the digest algorithm id @var{algo} to a string representation of the
3586 algorithm name. For unknown algorithms this function returns the
3587 string @code{"?"}. This function should not be used to test for the
3588 availability of an algorithm.
3591 @deftypefun int gcry_md_map_name (const char *@var{name})
3593 Map the algorithm with @var{name} to a digest algorithm identifier.
3594 Returns 0 if the algorithm name is not known. Names representing
3595 @acronym{ASN.1} object identifiers are recognized if the @acronym{IETF}
3596 dotted format is used and the OID is prefixed with either "@code{oid.}"
3597 or "@code{OID.}". For a list of supported OIDs, see the source code at
3598 @file{cipher/md.c}. This function should not be used to test for the
3599 availability of an algorithm.
3602 @deftypefun gcry_error_t gcry_md_get_asnoid (int @var{algo}, void *@var{buffer}, size_t *@var{length})
3604 Return an DER encoded ASN.1 OID for the algorithm @var{algo} in the
3605 user allocated @var{buffer}. @var{length} must point to variable with
3606 the available size of @var{buffer} and receives after return the
3607 actual size of the returned OID. The returned error code may be
3608 @code{GPG_ERR_TOO_SHORT} if the provided buffer is to short to receive
3609 the OID; it is possible to call the function with @code{NULL} for
3610 @var{buffer} to have it only return the required size. The function
3611 returns 0 on success.
3616 To test whether an algorithm is actually available for use, the
3617 following macro should be used:
3619 @deftypefun gcry_error_t gcry_md_test_algo (int @var{algo})
3621 The macro returns 0 if the algorithm @var{algo} is available for use.
3624 If the length of a message digest is not known, it can be retrieved
3625 using the following function:
3627 @deftypefun unsigned int gcry_md_get_algo_dlen (int @var{algo})
3629 Retrieve the length in bytes of the digest yielded by algorithm
3630 @var{algo}. This is often used prior to @code{gcry_md_read} to allocate
3631 sufficient memory for the digest.
3635 In some situations it might be hard to remember the algorithm used for
3636 the ongoing hashing. The following function might be used to get that
3639 @deftypefun int gcry_md_get_algo (gcry_md_hd_t @var{h})
3641 Retrieve the algorithm used with the handle @var{h}. Note that this
3642 does not work reliable if more than one algorithm is enabled in @var{h}.
3645 The following macro might also be useful:
3647 @deftypefun int gcry_md_is_secure (gcry_md_hd_t @var{h})
3649 This function returns true when the digest object @var{h} is allocated
3650 in "secure memory"; i.e. @var{h} was created with the
3651 @code{GCRY_MD_FLAG_SECURE}.
3654 @deftypefun int gcry_md_is_enabled (gcry_md_hd_t @var{h}, int @var{algo})
3656 This function returns true when the algorithm @var{algo} has been
3657 enabled for the digest object @var{h}.
3662 Tracking bugs related to hashing is often a cumbersome task which
3663 requires to add a lot of printf statements into the code.
3664 Libgcrypt provides an easy way to avoid this. The actual data
3665 hashed can be written to files on request.
3667 @deftypefun void gcry_md_debug (gcry_md_hd_t @var{h}, const char *@var{suffix})
3669 Enable debugging for the digest object with handle @var{h}. This
3670 creates create files named @file{dbgmd-<n>.<string>} while doing the
3671 actual hashing. @var{suffix} is the string part in the filename. The
3672 number is a counter incremented for each new hashing. The data in the
3673 file is the raw data as passed to @code{gcry_md_write} or
3674 @code{gcry_md_putc}. If @code{NULL} is used for @var{suffix}, the
3675 debugging is stopped and the file closed. This is only rarely required
3676 because @code{gcry_md_close} implicitly stops debugging.
3680 The following two deprecated macros are used for debugging by old code.
3681 They shopuld be replaced by @code{gcry_md_debug}.
3683 @deftypefun void gcry_md_start_debug (gcry_md_hd_t @var{h}, const char *@var{suffix})
3685 Enable debugging for the digest object with handle @var{h}. This
3686 creates create files named @file{dbgmd-<n>.<string>} while doing the
3687 actual hashing. @var{suffix} is the string part in the filename. The
3688 number is a counter incremented for each new hashing. The data in the
3689 file is the raw data as passed to @code{gcry_md_write} or
3690 @code{gcry_md_putc}.
3694 @deftypefun void gcry_md_stop_debug (gcry_md_hd_t @var{h}, int @var{reserved})
3696 Stop debugging on handle @var{h}. @var{reserved} should be specified as
3697 0. This function is usually not required because @code{gcry_md_close}
3698 does implicitly stop debugging.
3702 @c **********************************************************
3703 @c ******************* Random *****************************
3704 @c **********************************************************
3705 @node Random Numbers
3706 @chapter Random Numbers
3709 * Quality of random numbers:: Libgcrypt uses different quality levels.
3710 * Retrieving random numbers:: How to retrieve random numbers.
3713 @node Quality of random numbers
3714 @section Quality of random numbers
3716 @acronym{Libgcypt} offers random numbers of different quality levels:
3718 @deftp {Data type} enum gcry_random_level
3719 The constants for the random quality levels are of this type.
3723 @item GCRY_WEAK_RANDOM
3724 For all functions, except for @code{gcry_mpi_randomize}, this level maps
3725 to GCRY_STRONG_RANDOM. IF you do not want this, consider using
3726 @code{gcry_create_nonce}.
3727 @item GCRY_STRONG_RANDOM
3728 Use this level for e.g. session keys and similar purposes.
3729 @item GCRY_VERY_STRONG_RANDOM
3730 Use this level for e.g. key material.
3733 @node Retrieving random numbers
3734 @section Retrieving random numbers
3736 @deftypefun void gcry_randomize (unsigned char *@var{buffer}, size_t @var{length}, enum gcry_random_level @var{level})
3738 Fill @var{buffer} with @var{length} random bytes using a random quality
3739 as defined by @var{level}.
3742 @deftypefun void * gcry_random_bytes (size_t @var{nbytes}, enum gcry_random_level @var{level})
3744 Convenience function to allocate a memory block consisting of
3745 @var{nbytes} fresh random bytes using a random quality as defined by
3749 @deftypefun void * gcry_random_bytes_secure (size_t @var{nbytes}, enum gcry_random_level @var{level})
3751 Convenience function to allocate a memory block consisting of
3752 @var{nbytes} fresh random bytes using a random quality as defined by
3753 @var{level}. This function differs from @code{gcry_random_bytes} in
3754 that the returned buffer is allocated in a ``secure'' area of the
3758 @deftypefun void gcry_create_nonce (unsigned char *@var{buffer}, size_t @var{length})
3760 Fill @var{buffer} with @var{length} unpredictable bytes. This is
3761 commonly called a nonce and may also be used for initialization
3762 vectors and padding. This is an extra function nearly independent of
3763 the other random function for 3 reasons: It better protects the
3764 regular random generator's internal state, provides better performance
3765 and does not drain the precious entropy pool.
3771 @c **********************************************************
3772 @c ******************* S-Expressions ***********************
3773 @c **********************************************************
3775 @chapter S-expressions
3777 S-expressions are used by the public key functions to pass complex data
3778 structures around. These LISP like objects are used by some
3779 cryptographic protocols (cf. RFC-2692) and Libgcrypt provides functions
3780 to parse and construct them. For detailed information, see
3781 @cite{Ron Rivest, code and description of S-expressions,
3782 @uref{http://theory.lcs.mit.edu/~rivest/sexp.html}}.
3785 * Data types for S-expressions:: Data types related with S-expressions.
3786 * Working with S-expressions:: How to work with S-expressions.
3789 @node Data types for S-expressions
3790 @section Data types for S-expressions
3792 @deftp {Data type} gcry_sexp_t
3793 The @code{gcry_sexp_t} type describes an object with the Libgcrypt internal
3794 representation of an S-expression.
3797 @node Working with S-expressions
3798 @section Working with S-expressions
3801 There are several functions to create an Libgcrypt S-expression object
3802 from its external representation or from a string template. There is
3803 also a function to convert the internal representation back into one of
3804 the external formats:
3807 @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}})
3809 This is the generic function to create an new S-expression object from
3810 its external representation in @var{buffer} of @var{length} bytes. On
3811 success the result is stored at the address given by @var{r_sexp}.
3812 With @var{autodetect} set to 0, the data in @var{buffer} is expected to
3813 be in canonized format, with @var{autodetect} set to 1 the parses any of
3814 the defined external formats. If @var{buffer} does not hold a valid
3815 S-expression an error code is returned and @var{r_sexp} set to
3817 Note that the caller is responsible for releasing the newly allocated
3818 S-expression using @code{gcry_sexp_release}.
3821 @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*)})
3823 This function is identical to @code{gcry_sexp_new} but has an extra
3824 argument @var{freefnc}, which, when not set to @code{NULL}, is expected
3825 to be a function to release the @var{buffer}; most likely the standard
3826 @code{free} function is used for this argument. This has the effect of
3827 transferring the ownership of @var{buffer} to the created object in
3828 @var{r_sexp}. The advantage of using this function is that Libgcrypt
3829 might decide to directly use the provided buffer and thus avoid extra
3833 @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}})
3835 This is another variant of the above functions. It behaves nearly
3836 identical but provides an @var{erroff} argument which will receive the
3837 offset into the buffer where the parsing stopped on error.
3840 @deftypefun gcry_error_t gcry_sexp_build (@w{gcry_sexp_t *@var{r_sexp}}, @w{size_t *@var{erroff}}, @w{const char *@var{format}, ...})
3842 This function creates an internal S-expression from the string template
3843 @var{format} and stores it at the address of @var{r_sexp}. If there is a
3844 parsing error, the function returns an appropriate error code and stores
3845 the offset into @var{format} where the parsing stopped in @var{erroff}.
3846 The function supports a couple of printf-like formatting characters and
3847 expects arguments for some of these escape sequences right after
3848 @var{format}. The following format characters are defined:
3852 The next argument is expected to be of type @code{gcry_mpi_t} and a copy of
3853 its value is inserted into the resulting S-expression.
3855 The next argument is expected to be of type @code{char *} and that
3856 string is inserted into the resulting S-expression.
3858 The next argument is expected to be of type @code{int} and its value is
3859 inserted into the resulting S-expression.
3861 The next argument is expected to be of type @code{int} directly
3862 followed by an argument of type @code{char *}. This represents a
3863 buffer of given length to be inserted into the resulting regular
3868 No other format characters are defined and would return an error. Note
3869 that the format character @samp{%%} does not exists, because a percent
3870 sign is not a valid character in an S-expression.
3873 @deftypefun void gcry_sexp_release (@w{gcry_sexp_t @var{sexp}})
3875 Release the S-expression object @var{sexp}.
3880 The next 2 functions are used to convert the internal representation
3881 back into a regular external S-expression format and to show the
3882 structure for debugging.
3884 @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}})
3886 Copies the S-expression object @var{sexp} into @var{buffer} using the
3887 format specified in @var{mode}. @var{maxlength} must be set to the
3888 allocated length of @var{buffer}. The function returns the actual
3889 length of valid bytes put into @var{buffer} or 0 if the provided buffer
3890 is too short. Passing @code{NULL} for @var{buffer} returns the required
3891 length for @var{buffer}. For convenience reasons an extra byte with
3892 value 0 is appended to the buffer.
3895 The following formats are supported:
3898 @item GCRYSEXP_FMT_DEFAULT
3899 Returns a convenient external S-expression representation.
3901 @item GCRYSEXP_FMT_CANON
3902 Return the S-expression in canonical format.
3904 @item GCRYSEXP_FMT_BASE64
3905 Not currently supported.
3907 @item GCRYSEXP_FMT_ADVANCED
3908 Returns the S-expression in advanced format.
3912 @deftypefun void gcry_sexp_dump (@w{gcry_sexp_t @var{sexp}})
3914 Dumps @var{sexp} in a format suitable for debugging to Libgcrypt's
3919 Often canonical encoding is used in the external representation. The
3920 following function can be used to check for valid encoding and to learn
3921 the length of the S-expression"
3923 @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}})
3925 Scan the canonical encoded @var{buffer} with implicit length values and
3926 return the actual length this S-expression uses. For a valid S-expression
3927 it should never return 0. If @var{length} is not 0, the maximum
3928 length to scan is given; this can be used for syntax checks of
3929 data passed from outside. @var{errcode} and @var{erroff} may both be
3930 passed as @code{NULL}.
3936 There are a couple of functions to parse S-expressions and retrieve
3939 @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}})
3941 Scan the S-expression for a sublist with a type (the car of the list)
3942 matching the string @var{token}. If @var{toklen} is not 0, the token is
3943 assumed to be raw memory of this length. The function returns a newly
3944 allocated S-expression consisting of the found sublist or @code{NULL}
3949 @deftypefun int gcry_sexp_length (@w{const gcry_sexp_t @var{list}})
3951 Return the length of the @var{list}. For a valid S-expression this
3952 should be at least 1.
3956 @deftypefun gcry_sexp_t gcry_sexp_nth (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}})
3958 Create and return a new S-expression from the element with index @var{number} in
3959 @var{list}. Note that the first element has the index 0. If there is
3960 no such element, @code{NULL} is returned.
3963 @deftypefun gcry_sexp_t gcry_sexp_car (@w{const gcry_sexp_t @var{list}})
3965 Create and return a new S-expression from the first element in
3966 @var{list}; this called the "type" and should always exist and be a
3967 string. @code{NULL} is returned in case of a problem.
3970 @deftypefun gcry_sexp_t gcry_sexp_cdr (@w{const gcry_sexp_t @var{list}})
3972 Create and return a new list form all elements except for the first one.
3973 Note that this function may return an invalid S-expression because it
3974 is not guaranteed, that the type exists and is a string. However, for
3975 parsing a complex S-expression it might be useful for intermediate
3976 lists. Returns @code{NULL} on error.
3980 @deftypefun {const char *} gcry_sexp_nth_data (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{size_t *@var{datalen}})
3982 This function is used to get data from a @var{list}. A pointer to the
3983 actual data with index @var{number} is returned and the length of this
3984 data will be stored to @var{datalen}. If there is no data at the given
3985 index or the index represents another list, @code{NULL} is returned.
3986 @strong{Caution:} The returned pointer is valid as long as @var{list} is
3987 not modified or released.
3990 Here is an example on how to extract and print the surname (Meier) from
3991 the S-expression @samp{(Name Otto Meier (address Burgplatz 3))}:
3997 name = gcry_sexp_nth_data (list, 2, &len);
3998 printf ("my name is %.*s\n", (int)len, name);
4002 @deftypefun char *gcry_sexp_nth_string (@w{gcry_sexp_t @var{list}}, @w{int @var{number}})
4004 This function is used to get and convert data from a @var{list}. The
4005 data is assumed to be a Nul terminated string. The caller must
4006 release this returned value using @code{gcry_free}. If there is
4007 no data at the given index, the index represents a list or the value
4008 can't be converted to a string, @code{NULL} is returned.
4011 @deftypefun gcry_mpi_t gcry_sexp_nth_mpi (@w{gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{int @var{mpifmt}})
4013 This function is used to get and convert data from a @var{list}. This
4014 data is assumed to be an MPI stored in the format described by
4015 @var{mpifmt} and returned as a standard Libgcrypt MPI. The caller must
4016 release this returned value using @code{gcry_mpi_release}. If there is
4017 no data at the given index, the index represents a list or the value
4018 can't be converted to an MPI, @code{NULL} is returned.
4022 @c **********************************************************
4023 @c ******************* MPIs ******** ***********************
4024 @c **********************************************************
4026 @chapter MPI library
4029 * Data types:: MPI related data types.
4030 * Basic functions:: First steps with MPI numbers.
4031 * MPI formats:: External representation of MPIs.
4032 * Calculations:: Performing MPI calculations.
4033 * Comparisons:: How to compare MPI values.
4034 * Bit manipulations:: How to access single bits of MPI values.
4035 * Miscellaneous:: Miscellaneous MPI functions.
4038 Public key cryptography is based on mathematics with large numbers. To
4039 implement the public key functions, a library for handling these large
4040 numbers is required. Because of the general usefulness of such a
4041 library, its interface is exposed by Libgcrypt.
4042 In the context of Libgcrypt and in most other applications, these large
4043 numbers are called MPIs (multi-precision-integers).
4048 @deftp {Data type} gcry_mpi_t
4049 The @code{gcry_mpi_t} type represents an object to hold an MPI.
4052 @node Basic functions
4053 @section Basic functions
4056 To work with MPIs, storage must be allocated and released for the
4057 numbers. This can be done with one of these functions:
4059 @deftypefun gcry_mpi_t gcry_mpi_new (@w{unsigned int @var{nbits}})
4061 Allocate a new MPI object, initialize it to 0 and initially allocate
4062 enough memory for a number of at least @var{nbits}. This pre-allocation is
4063 only a small performance issue and not actually necessary because
4064 Libgcrypt automatically re-allocates the required memory.
4067 @deftypefun gcry_mpi_t gcry_mpi_snew (@w{unsigned int @var{nbits}})
4069 This is identical to @code{gcry_mpi_new} but allocates the MPI in the so
4070 called "secure memory" which in turn will take care that all derived
4071 values will also be stored in this "secure memory". Use this for highly
4072 confidential data like private key parameters.
4075 @deftypefun gcry_mpi_t gcry_mpi_copy (@w{const gcry_mpi_t @var{a}})
4077 Create a new MPI as the exact copy of @var{a}.
4081 @deftypefun void gcry_mpi_release (@w{gcry_mpi_t @var{a}})
4083 Release the MPI @var{a} and free all associated resources. Passing
4084 @code{NULL} is allowed and ignored. When a MPI stored in the "secure
4085 memory" is released, that memory gets wiped out immediately.
4089 The simplest operations are used to assign a new value to an MPI:
4091 @deftypefun gcry_mpi_t gcry_mpi_set (@w{gcry_mpi_t @var{w}}, @w{const gcry_mpi_t @var{u}})
4093 Assign the value of @var{u} to @var{w} and return @var{w}. If
4094 @code{NULL} is passed for @var{w}, a new MPI is allocated, set to the
4095 value of @var{u} and returned.
4098 @deftypefun gcry_mpi_t gcry_mpi_set_ui (@w{gcry_mpi_t @var{w}}, @w{unsigned long @var{u}})
4100 Assign the value of @var{u} to @var{w} and return @var{w}. If
4101 @code{NULL} is passed for @var{w}, a new MPI is allocated, set to the
4102 value of @var{u} and returned. This function takes an @code{unsigned
4103 int} as type for @var{u} and thus it is only possible to set @var{w} to
4104 small values (usually up to the word size of the CPU).
4107 @deftypefun void gcry_mpi_swap (@w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}})
4109 Swap the values of @var{a} and @var{b}.
4113 @section MPI formats
4116 The following functions are used to convert between an external
4117 representation of an MPI and the internal one of Libgcrypt.
4119 @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}})
4121 Convert the external representation of an integer stored in @var{buffer}
4122 with a length of @var{buflen} into a newly created MPI returned which
4123 will be stored at the address of @var{r_mpi}. For certain formats the
4124 length argument is not required and should be passed as @code{0}. After a
4125 successful operation the variable @var{nscanned} receives the number of
4126 bytes actually scanned unless @var{nscanned} was given as
4127 @code{NULL}. @var{format} describes the format of the MPI as stored in
4131 @item GCRYMPI_FMT_STD
4132 2-complement stored without a length header.
4134 @item GCRYMPI_FMT_PGP
4135 As used by OpenPGP (only defined as unsigned). This is basically
4136 @code{GCRYMPI_FMT_STD} with a 2 byte big endian length header.
4138 @item GCRYMPI_FMT_SSH
4139 As used in the Secure Shell protocol. This is @code{GCRYMPI_FMT_STD}
4140 with a 4 byte big endian header.
4142 @item GCRYMPI_FMT_HEX
4143 Stored as a C style string with each byte of the MPI encoded as 2 hex
4144 digits. When using this format, @var{buflen} must be zero.
4146 @item GCRYMPI_FMT_USG
4147 Simple unsigned integer.
4151 Note that all of the above formats store the integer in big-endian
4156 @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}})
4158 Convert the MPI @var{a} into an external representation described by
4159 @var{format} (see above) and store it in the provided @var{buffer}
4160 which has a usable length of at least the @var{buflen} bytes. If
4161 @var{nwritten} is not NULL, it will receive the number of bytes
4162 actually stored in @var{buffer} after a successful operation.
4165 @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}})
4167 Convert the MPI @var{a} into an external representation described by
4168 @var{format} (see above) and store it in a newly allocated buffer which
4169 address will be stored in the variable @var{buffer} points to. The
4170 number of bytes stored in this buffer will be stored in the variable
4171 @var{nbytes} points to, unless @var{nbytes} is @code{NULL}.
4174 @deftypefun void gcry_mpi_dump (@w{const gcry_mpi_t @var{a}})
4176 Dump the value of @var{a} in a format suitable for debugging to
4177 Libgcrypt's logging stream. Note that one leading space but no trailing
4178 space or linefeed will be printed. It is okay to pass @code{NULL} for
4184 @section Calculations
4187 Basic arithmetic operations:
4189 @deftypefun void gcry_mpi_add (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
4191 @math{@var{w} = @var{u} + @var{v}}.
4195 @deftypefun void gcry_mpi_add_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4197 @math{@var{w} = @var{u} + @var{v}}. Note that @var{v} is an unsigned integer.
4201 @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}})
4203 @math{@var{w} = @var{u} + @var{v} \bmod @var{m}}.
4206 @deftypefun void gcry_mpi_sub (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
4208 @math{@var{w} = @var{u} - @var{v}}.
4211 @deftypefun void gcry_mpi_sub_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4213 @math{@var{w} = @var{u} - @var{v}}. @var{v} is an unsigned integer.
4216 @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}})
4218 @math{@var{w} = @var{u} - @var{v} \bmod @var{m}}.
4221 @deftypefun void gcry_mpi_mul (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
4223 @math{@var{w} = @var{u} * @var{v}}.
4226 @deftypefun void gcry_mpi_mul_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4228 @math{@var{w} = @var{u} * @var{v}}. @var{v} is an unsigned integer.
4231 @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}})
4233 @math{@var{w} = @var{u} * @var{v} \bmod @var{m}}.
4236 @deftypefun void gcry_mpi_mul_2exp (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{e}})
4238 @c FIXME: I am in need for a real TeX{info} guru:
4239 @c I don't know why TeX can grok @var{e} here.
4240 @math{@var{w} = @var{u} * 2^e}.
4243 @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}})
4245 @math{@var{q} = @var{dividend} / @var{divisor}}, @math{@var{r} =
4246 @var{dividend} \bmod @var{divisor}}. @var{q} and @var{r} may be passed
4247 as @code{NULL}. @var{round} should be negative or 0.
4250 @deftypefun void gcry_mpi_mod (@w{gcry_mpi_t @var{r}}, @w{gcry_mpi_t @var{dividend}}, @w{gcry_mpi_t @var{divisor}})
4252 @math{@var{r} = @var{dividend} \bmod @var{divisor}}.
4255 @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}})
4257 @c I don't know why TeX can grok @var{e} here.
4258 @math{@var{w} = @var{b}^e \bmod @var{m}}.
4261 @deftypefun int gcry_mpi_gcd (@w{gcry_mpi_t @var{g}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}})
4263 Set @var{g} to the greatest common divisor of @var{a} and @var{b}.
4264 Return true if the @var{g} is 1.
4267 @deftypefun int gcry_mpi_invm (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{m}})
4269 Set @var{x} to the multiplicative inverse of @math{@var{a} \bmod @var{m}}.
4270 Return true if the inverse exists.
4275 @section Comparisons
4278 The next 2 functions are used to compare MPIs:
4281 @deftypefun int gcry_mpi_cmp (@w{const gcry_mpi_t @var{u}}, @w{const gcry_mpi_t @var{v}})
4283 Compare the multi-precision-integers number @var{u} and @var{v}
4284 returning 0 for equality, a positive value for @var{u} > @var{v} and a
4285 negative for @var{u} < @var{v}.
4288 @deftypefun int gcry_mpi_cmp_ui (@w{const gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4290 Compare the multi-precision-integers number @var{u} with the unsigned
4291 integer @var{v} returning 0 for equality, a positive value for @var{u} >
4292 @var{v} and a negative for @var{u} < @var{v}.
4296 @node Bit manipulations
4297 @section Bit manipulations
4300 There are a couple of functions to get information on arbitrary bits
4301 in an MPI and to set or clear them:
4303 @deftypefun {unsigned int} gcry_mpi_get_nbits (@w{gcry_mpi_t @var{a}})
4305 Return the number of bits required to represent @var{a}.
4308 @deftypefun int gcry_mpi_test_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4310 Return true if bit number @var{n} (counting from 0) is set in @var{a}.
4313 @deftypefun void gcry_mpi_set_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4315 Set bit number @var{n} in @var{a}.
4318 @deftypefun void gcry_mpi_clear_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4320 Clear bit number @var{n} in @var{a}.
4323 @deftypefun void gcry_mpi_set_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4325 Set bit number @var{n} in @var{a} and clear all bits greater than @var{n}.
4328 @deftypefun void gcry_mpi_clear_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4330 Clear bit number @var{n} in @var{a} and all bits greater than @var{n}.
4333 @deftypefun void gcry_mpi_rshift (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4335 Shift the value of @var{a} by @var{n} bits to the right and store the
4339 @deftypefun void gcry_mpi_lshift (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})