Imported Upstream version 1.8.4
[platform/upstream/libgcrypt.git] / doc / gcrypt.texi
1 \input texinfo                  @c -*- Texinfo -*-
2 @c %**start of header
3 @setfilename gcrypt.info
4 @include version.texi
5 @settitle The Libgcrypt Reference Manual
6 @c Unify some of the indices.
7 @syncodeindex tp fn
8 @syncodeindex pg fn
9 @c %**end of header
10 @copying
11 This manual is for Libgcrypt
12 (version @value{VERSION}, @value{UPDATED}),
13 which is GNU's library of cryptographic building blocks.
14
15 @noindent
16 Copyright @copyright{} 2000, 2002, 2003, 2004, 2006, 2007, 2008, 2009, 2011, 2012 Free Software Foundation, Inc. @*
17 Copyright @copyright{} 2012, 2013, 2016, 2017 g10 Code GmbH
18
19 @quotation
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU General Public License as published by the
22 Free Software Foundation; either version 2 of the License, or (at your
23 option) any later version. The text of the license can be found in the
24 section entitled ``GNU General Public License''.
25 @end quotation
26 @end copying
27
28 @dircategory GNU Libraries
29 @direntry
30 * libgcrypt: (gcrypt).  Cryptographic function library.
31 @end direntry
32
33 @c A couple of macros with no effect on texinfo
34 @c but used by the yat2m processor.
35 @macro manpage {a}
36 @end macro
37 @macro mansect {a}
38 @end macro
39 @macro manpause
40 @end macro
41 @macro mancont
42 @end macro
43
44 @c
45 @c Printing stuff taken from gcc.
46 @c
47 @macro gnupgtabopt{body}
48 @code{\body\}
49 @end macro
50
51
52 @c
53 @c Titlepage
54 @c
55 @setchapternewpage odd
56 @titlepage
57 @title The Libgcrypt Reference Manual
58 @subtitle Version @value{VERSION}
59 @subtitle @value{UPDATED}
60 @author Werner Koch (@email{wk@@gnupg.org})
61 @author Moritz Schulte (@email{mo@@g10code.com})
62
63 @page
64 @vskip 0pt plus 1filll
65 @insertcopying
66 @end titlepage
67
68 @ifnothtml
69 @summarycontents
70 @contents
71 @page
72 @end ifnothtml
73
74
75 @ifnottex
76 @node Top
77 @top The Libgcrypt Library
78 @insertcopying
79 @end ifnottex
80
81
82 @menu
83 * Introduction::                 What is Libgcrypt.
84 * Preparation::                  What you should do before using the library.
85 * Generalities::                 General library functions and data types.
86 * Handler Functions::            Working with handler functions.
87 * Symmetric cryptography::       How to use symmetric cryptography.
88 * Public Key cryptography::      How to use public key cryptography.
89 * Hashing::                      How to use hash algorithms.
90 * Message Authentication Codes:: How to use MAC algorithms.
91 * Key Derivation::               How to derive keys from strings
92 * Random Numbers::               How to work with random numbers.
93 * S-expressions::                How to manage S-expressions.
94 * MPI library::                  How to work with multi-precision-integers.
95 * Prime numbers::                How to use the Prime number related functions.
96 * Utilities::                    Utility functions.
97 * Tools::                        Utility tools.
98 * Configuration::                Configuration files and environment variables.
99 * Architecture::                 How Libgcrypt works internally.
100
101 Appendices
102
103 * Self-Tests::                  Description of the self-tests.
104 * FIPS Mode::                   Description of the FIPS mode.
105 * Library Copying::             The GNU Lesser General Public License
106                                 says how you can copy and share Libgcrypt.
107 * Copying::                     The GNU General Public License says how you
108                                 can copy and share some parts of Libgcrypt.
109
110 Indices
111
112 * Figures and Tables::          Index of figures and tables.
113 * Concept Index::               Index of concepts and programs.
114 * Function and Data Index::     Index of functions, variables and data types.
115
116 @end menu
117
118 @ifhtml
119 @page
120 @summarycontents
121 @contents
122 @end ifhtml
123
124
125 @c **********************************************************
126 @c *******************  Introduction  ***********************
127 @c **********************************************************
128 @node Introduction
129 @chapter Introduction
130
131 Libgcrypt is a library providing cryptographic building blocks.
132
133 @menu
134 * Getting Started::             How to use this manual.
135 * Features::                    A glance at Libgcrypt's features.
136 * Overview::                    Overview about the library.
137 @end menu
138
139 @node Getting Started
140 @section Getting Started
141
142 This manual documents the Libgcrypt library application programming
143 interface (API).  All functions and data types provided by the library
144 are explained.
145
146 @noindent
147 The reader is assumed to possess basic knowledge about applied
148 cryptography.
149
150 This manual can be used in several ways.  If read from the beginning
151 to the end, it gives a good introduction into the library and how it
152 can be used in an application.  Forward references are included where
153 necessary.  Later on, the manual can be used as a reference manual to
154 get just the information needed about any particular interface of the
155 library.  Experienced programmers might want to start looking at the
156 examples at the end of the manual, and then only read up those parts
157 of the interface which are unclear.
158
159
160 @node Features
161 @section Features
162
163 Libgcrypt might have a couple of advantages over other libraries doing
164 a similar job.
165
166 @table @asis
167 @item It's Free Software
168 Anybody can use, modify, and redistribute it under the terms of the GNU
169 Lesser General Public License (@pxref{Library Copying}).  Note, that
170 some parts (which are in general not needed by applications) are subject
171 to the terms of the GNU General Public License (@pxref{Copying}); please
172 see the README file of the distribution for of list of these parts.
173
174 @item It encapsulates the low level cryptography
175 Libgcrypt provides a high level interface to cryptographic
176 building blocks using an extensible and flexible API.
177
178 @end table
179
180 @node Overview
181 @section Overview
182
183 @noindent
184 The Libgcrypt library is fully thread-safe, where it makes
185 sense to be thread-safe.  Not thread-safe are some cryptographic
186 functions that modify a certain context stored in handles.  If the
187 user really intents to use such functions from different threads on
188 the same handle, he has to take care of the serialization of such
189 functions himself.  If not described otherwise, every function is
190 thread-safe.
191
192 Libgcrypt depends on the library `libgpg-error', which contains some
193 common code used by other GnuPG components.
194
195 @c **********************************************************
196 @c *******************  Preparation  ************************
197 @c **********************************************************
198 @node Preparation
199 @chapter Preparation
200
201 To use Libgcrypt, you have to perform some changes to your
202 sources and the build system.  The necessary changes are small and
203 explained in the following sections.  At the end of this chapter, it
204 is described how the library is initialized, and how the requirements
205 of the library are verified.
206
207 @menu
208 * Header::                      What header file you need to include.
209 * Building sources::            How to build sources using the library.
210 * Building sources using Automake::  How to build sources with the help of Automake.
211 * Initializing the library::    How to initialize the library.
212 * Multi-Threading::             How Libgcrypt can be used in a MT environment.
213 * Enabling FIPS mode::          How to enable the FIPS mode.
214 * Hardware features::           How to disable hardware features.
215 @end menu
216
217
218 @node Header
219 @section Header
220
221 All interfaces (data types and functions) of the library are defined
222 in the header file @file{gcrypt.h}.  You must include this in all source
223 files using the library, either directly or through some other header
224 file, like this:
225
226 @example
227 #include <gcrypt.h>
228 @end example
229
230 The name space of Libgcrypt is @code{gcry_*} for function
231 and type names and @code{GCRY*} for other symbols.  In addition the
232 same name prefixes with one prepended underscore are reserved for
233 internal use and should never be used by an application.  Note that
234 Libgcrypt uses libgpg-error, which uses @code{gpg_*} as
235 name space for function and type names and @code{GPG_*} for other
236 symbols, including all the error codes.
237
238 @noindent
239 Certain parts of gcrypt.h may be excluded by defining these macros:
240
241 @table @code
242 @item GCRYPT_NO_MPI_MACROS
243 Do not define the shorthand macros @code{mpi_*} for @code{gcry_mpi_*}.
244
245 @item GCRYPT_NO_DEPRECATED
246 Do not include definitions for deprecated features.  This is useful to
247 make sure that no deprecated features are used.
248 @end table
249
250 @node Building sources
251 @section Building sources
252
253 If you want to compile a source file including the `gcrypt.h' header
254 file, you must make sure that the compiler can find it in the
255 directory hierarchy.  This is accomplished by adding the path to the
256 directory in which the header file is located to the compilers include
257 file search path (via the @option{-I} option).
258
259 However, the path to the include file is determined at the time the
260 source is configured.  To solve this problem, Libgcrypt ships with a small
261 helper program @command{libgcrypt-config} that knows the path to the
262 include file and other configuration options.  The options that need
263 to be added to the compiler invocation at compile time are output by
264 the @option{--cflags} option to @command{libgcrypt-config}.  The following
265 example shows how it can be used at the command line:
266
267 @example
268 gcc -c foo.c `libgcrypt-config --cflags`
269 @end example
270
271 Adding the output of @samp{libgcrypt-config --cflags} to the
272 compiler’s command line will ensure that the compiler can find the
273 Libgcrypt header file.
274
275 A similar problem occurs when linking the program with the library.
276 Again, the compiler has to find the library files.  For this to work,
277 the path to the library files has to be added to the library search path
278 (via the @option{-L} option).  For this, the option @option{--libs} to
279 @command{libgcrypt-config} can be used.  For convenience, this option
280 also outputs all other options that are required to link the program
281 with the Libgcrypt libraries (in particular, the @samp{-lgcrypt}
282 option).  The example shows how to link @file{foo.o} with the Libgcrypt
283 library to a program @command{foo}.
284
285 @example
286 gcc -o foo foo.o `libgcrypt-config --libs`
287 @end example
288
289 Of course you can also combine both examples to a single command by
290 specifying both options to @command{libgcrypt-config}:
291
292 @example
293 gcc -o foo foo.c `libgcrypt-config --cflags --libs`
294 @end example
295
296 @node Building sources using Automake
297 @section Building sources using Automake
298
299 It is much easier if you use GNU Automake instead of writing your own
300 Makefiles.  If you do that, you do not have to worry about finding and
301 invoking the @command{libgcrypt-config} script at all.
302 Libgcrypt provides an extension to Automake that does all
303 the work for you.
304
305 @c A simple macro for optional variables.
306 @macro ovar{varname}
307 @r{[}@var{\varname\}@r{]}
308 @end macro
309 @defmac AM_PATH_LIBGCRYPT (@ovar{minimum-version}, @ovar{action-if-found}, @ovar{action-if-not-found})
310 Check whether Libgcrypt (at least version
311 @var{minimum-version}, if given) exists on the host system.  If it is
312 found, execute @var{action-if-found}, otherwise do
313 @var{action-if-not-found}, if given.
314
315 Additionally, the function defines @code{LIBGCRYPT_CFLAGS} to the
316 flags needed for compilation of the program to find the
317 @file{gcrypt.h} header file, and @code{LIBGCRYPT_LIBS} to the linker
318 flags needed to link the program to the Libgcrypt library.  If the
319 used helper script does not match the target type you are building for
320 a warning is printed and the string @code{libgcrypt} is appended to the
321 variable @code{gpg_config_script_warn}.
322
323 This macro searches for @command{libgcrypt-config} along the PATH.  If
324 you are cross-compiling, it is useful to set the environment variable
325 @code{SYSROOT} to the top directory of your target.  The macro will
326 then first look for the helper program in the @file{bin} directory
327 below that top directory.  An absolute directory name must be used for
328 @code{SYSROOT}.  Finally, if the configure command line option
329 @code{--with-libgcrypt-prefix} is used, only its value is used for the top
330 directory below which the helper script is expected.
331
332 @end defmac
333
334 You can use the defined Autoconf variables like this in your
335 @file{Makefile.am}:
336
337 @example
338 AM_CPPFLAGS = $(LIBGCRYPT_CFLAGS)
339 LDADD = $(LIBGCRYPT_LIBS)
340 @end example
341
342 @node Initializing the library
343 @section Initializing the library
344
345 Before the library can be used, it must initialize itself.  This is
346 achieved by invoking the function @code{gcry_check_version} described
347 below.
348
349 Also, it is often desirable to check that the version of
350 Libgcrypt used is indeed one which fits all requirements.
351 Even with binary compatibility, new features may have been introduced,
352 but due to problem with the dynamic linker an old version may actually
353 be used.  So you may want to check that the version is okay right
354 after program startup.
355
356 @deftypefun {const char *} gcry_check_version (const char *@var{req_version})
357
358 The function @code{gcry_check_version} initializes some subsystems used
359 by Libgcrypt and must be invoked before any other function in the
360 library.
361 @xref{Multi-Threading}.
362
363 Furthermore, this function returns the version number of the library.
364 It can also verify that the version number is higher than a certain
365 required version number @var{req_version}, if this value is not a null
366 pointer.
367 @end deftypefun
368
369 Libgcrypt uses a concept known as secure memory, which is a region of
370 memory set aside for storing sensitive data.  Because such memory is a
371 scarce resource, it needs to be setup in advanced to a fixed size.
372 Further, most operating systems have special requirements on how that
373 secure memory can be used.  For example, it might be required to install
374 an application as ``setuid(root)'' to allow allocating such memory.
375 Libgcrypt requires a sequence of initialization steps to make sure that
376 this works correctly.  The following examples show the necessary steps.
377
378 If you don't have a need for secure memory, for example if your
379 application does not use secret keys or other confidential data or it
380 runs in a controlled environment where key material floating around in
381 memory is not a problem, you should initialize Libgcrypt this way:
382
383 @example
384   /* Version check should be the very first call because it
385      makes sure that important subsystems are initialized. */
386   if (!gcry_check_version (GCRYPT_VERSION))
387     @{
388       fputs ("libgcrypt version mismatch\n", stderr);
389       exit (2);
390     @}
391
392   /* Disable secure memory.  */
393   gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
394
395   /* ... If required, other initialization goes here.  */
396
397   /* Tell Libgcrypt that initialization has completed. */
398   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
399 @end example
400
401
402 If you have to protect your keys or other information in memory against
403 being swapped out to disk and to enable an automatic overwrite of used
404 and freed memory, you need to initialize Libgcrypt this way:
405
406 @example
407   /* Version check should be the very first call because it
408      makes sure that important subsystems are initialized. */
409   if (!gcry_check_version (GCRYPT_VERSION))
410     @{
411       fputs ("libgcrypt version mismatch\n", stderr);
412       exit (2);
413     @}
414
415 @anchor{sample-use-suspend-secmem}
416   /* We don't want to see any warnings, e.g. because we have not yet
417      parsed program options which might be used to suppress such
418      warnings. */
419   gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
420
421   /* ... If required, other initialization goes here.  Note that the
422      process might still be running with increased privileges and that
423      the secure memory has not been initialized.  */
424
425   /* Allocate a pool of 16k secure memory.  This makes the secure memory
426      available and also drops privileges where needed.  Note that by
427      using functions like gcry_xmalloc_secure and gcry_mpi_snew Libgcrypt
428      may expand the secure memory pool with memory which lacks the
429      property of not being swapped out to disk.   */
430   gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
431
432 @anchor{sample-use-resume-secmem}
433   /* It is now okay to let Libgcrypt complain when there was/is
434      a problem with the secure memory. */
435   gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
436
437   /* ... If required, other initialization goes here.  */
438
439   /* Tell Libgcrypt that initialization has completed. */
440   gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
441 @end example
442
443 It is important that these initialization steps are not done by a
444 library but by the actual application.  A library using Libgcrypt might
445 want to check for finished initialization using:
446
447 @example
448   if (!gcry_control (GCRYCTL_INITIALIZATION_FINISHED_P))
449     @{
450       fputs ("libgcrypt has not been initialized\n", stderr);
451       abort ();
452     @}
453 @end example
454
455 Instead of terminating the process, the library may instead print a
456 warning and try to initialize Libgcrypt itself.  See also the section on
457 multi-threading below for more pitfalls.
458
459
460
461 @node Multi-Threading
462 @section Multi-Threading
463
464 As mentioned earlier, the Libgcrypt library is
465 thread-safe if you adhere to the following requirements:
466
467 @itemize @bullet
468 @item
469 If you use pthread and your applications forks and does not directly
470 call exec (even calling stdio functions), all kind of problems may
471 occur.  Future versions of Libgcrypt will try to cleanup using
472 pthread_atfork but even that may lead to problems.  This is a common
473 problem with almost all applications using pthread and fork.
474
475
476 @item
477 The function @code{gcry_check_version} must be called before any other
478 function in the library.  To
479 achieve this in multi-threaded programs, you must synchronize the
480 memory with respect to other threads that also want to use
481 Libgcrypt.  For this, it is sufficient to call
482 @code{gcry_check_version} before creating the other threads using
483 Libgcrypt@footnote{At least this is true for POSIX threads,
484 as @code{pthread_create} is a function that synchronizes memory with
485 respects to other threads.  There are many functions which have this
486 property, a complete list can be found in POSIX, IEEE Std 1003.1-2003,
487 Base Definitions, Issue 6, in the definition of the term ``Memory
488 Synchronization''.  For other thread packages, more relaxed or more
489 strict rules may apply.}.
490
491 @item
492 Just like the function @code{gpg_strerror}, the function
493 @code{gcry_strerror} is not thread safe.  You have to use
494 @code{gpg_strerror_r} instead.
495
496 @end itemize
497
498
499 @node Enabling FIPS mode
500 @section How to enable the FIPS mode
501 @cindex FIPS mode
502 @cindex FIPS 140
503
504 @anchor{enabling fips mode}
505 Libgcrypt may be used in a FIPS 140-2 mode.  Note, that this does not
506 necessary mean that Libcgrypt is an appoved FIPS 140-2 module.  Check the
507 NIST database at @url{http://csrc.nist.gov/groups/STM/cmvp/} to see what
508 versions of Libgcrypt are approved.
509
510 Because FIPS 140 has certain restrictions on the use of cryptography
511 which are not always wanted, Libgcrypt needs to be put into FIPS mode
512 explicitly.  Three alternative mechanisms are provided to switch
513 Libgcrypt into this mode:
514
515 @itemize
516 @item
517 If the file @file{/proc/sys/crypto/fips_enabled} exists and contains a
518 numeric value other than @code{0}, Libgcrypt is put into FIPS mode at
519 initialization time.  Obviously this works only on systems with a
520 @code{proc} file system (i.e. GNU/Linux).
521
522 @item
523 If the file @file{/etc/gcrypt/fips_enabled} exists, Libgcrypt is put
524 into FIPS mode at initialization time.  Note that this filename is
525 hardwired and does not depend on any configuration options.
526
527 @item
528 If the application requests FIPS mode using the control command
529 @code{GCRYCTL_FORCE_FIPS_MODE}.  This must be done prior to any
530 initialization (i.e. before @code{gcry_check_version}).
531
532 @end itemize
533
534 @cindex Enforced FIPS mode
535
536 In addition to the standard FIPS mode, Libgcrypt may also be put into
537 an Enforced FIPS mode by writing a non-zero value into the file
538 @file{/etc/gcrypt/fips_enabled} or by using the control command
539 @code{GCRYCTL_SET_ENFORCED_FIPS_FLAG} before any other calls to
540 libgcrypt.  The Enforced FIPS mode helps to detect applications
541 which don't fulfill all requirements for using
542 Libgcrypt in FIPS mode (@pxref{FIPS Mode}).
543
544 Once Libgcrypt has been put into FIPS mode, it is not possible to
545 switch back to standard mode without terminating the process first.
546 If the logging verbosity level of Libgcrypt has been set to at least
547 2, the state transitions and the self-tests are logged.
548
549 @node Hardware features
550 @section How to disable hardware features
551 @cindex hardware features
552
553 @anchor{hardware features}
554 Libgcrypt makes use of certain hardware features.  If the use of a
555 feature is not desired it may be either be disabled by a program or
556 globally using a configuration file.  The currently supported features
557 are
558
559 @table @code
560 @item padlock-rng
561 @item padlock-aes
562 @item padlock-sha
563 @item padlock-mmul
564 @item intel-cpu
565 @item intel-fast-shld
566 @item intel-bmi2
567 @item intel-ssse3
568 @item intel-pclmul
569 @item intel-aesni
570 @item intel-rdrand
571 @item intel-avx
572 @item intel-avx2
573 @item intel-rdtsc
574 @item arm-neon
575 @end table
576
577 To disable a feature for all processes using Libgcrypt 1.6 or newer,
578 create the file @file{/etc/gcrypt/hwf.deny} and put each feature not
579 to be used on a single line.  Empty lines, white space, and lines
580 prefixed with a hash mark are ignored.  The file should be world
581 readable.
582
583 To disable a feature specifically for a program that program must tell
584 it Libgcrypt before before calling @code{gcry_check_version}.
585 Example:@footnote{NB. Libgcrypt uses the RDRAND feature only as one
586 source of entropy.  A CPU with a broken RDRAND will thus not
587 compromise of the random number generator}
588
589 @example
590   gcry_control (GCRYCTL_DISABLE_HWF, "intel-rdrand", NULL);
591 @end example
592
593 @noindent
594 To print the list of active features you may use this command:
595
596 @example
597   mpicalc --print-config | grep ^hwflist: | tr : '\n' | tail -n +2
598 @end example
599
600
601 @c **********************************************************
602 @c *******************  General  ****************************
603 @c **********************************************************
604 @node Generalities
605 @chapter Generalities
606
607 @menu
608 * Controlling the library::     Controlling Libgcrypt's behavior.
609 * Error Handling::              Error codes and such.
610 @end menu
611
612 @node Controlling the library
613 @section Controlling the library
614
615 @deftypefun gcry_error_t gcry_control (enum gcry_ctl_cmds @var{cmd}, ...)
616
617 This function can be used to influence the general behavior of
618 Libgcrypt in several ways.  Depending on @var{cmd}, more
619 arguments can or have to be provided.
620
621 @table @code
622 @item GCRYCTL_ENABLE_M_GUARD; Arguments: none
623 This command enables the built-in memory guard.  It must not be used
624 to activate the memory guard after the memory management has already
625 been used; therefore it can ONLY be used before
626 @code{gcry_check_version}.  Note that the memory guard is NOT used
627 when the user of the library has set his own memory management
628 callbacks.
629
630 @item GCRYCTL_ENABLE_QUICK_RANDOM; Arguments: none
631 This command inhibits the use the very secure random quality level
632 (@code{GCRY_VERY_STRONG_RANDOM}) and degrades all request down to
633 @code{GCRY_STRONG_RANDOM}.  In general this is not recommended.  However,
634 for some applications the extra quality random Libgcrypt tries to create
635 is not justified and this option may help to get better performance.
636 Please check with a crypto expert whether this option can be used for
637 your application.
638
639 This option can only be used at initialization time.
640
641
642 @item GCRYCTL_DUMP_RANDOM_STATS; Arguments: none
643 This command dumps random number generator related statistics to the
644 library's logging stream.
645
646 @item GCRYCTL_DUMP_MEMORY_STATS; Arguments: none
647 This command dumps memory management related statistics to the library's
648 logging stream.
649
650 @item GCRYCTL_DUMP_SECMEM_STATS; Arguments: none
651 This command dumps secure memory management related statistics to the
652 library's logging stream.
653
654 @item GCRYCTL_DROP_PRIVS; Arguments: none
655 This command disables the use of secure memory and drops the privileges
656 of the current process.  This command has not much use; the suggested way
657 to disable secure memory is to use @code{GCRYCTL_DISABLE_SECMEM} right
658 after initialization.
659
660 @item GCRYCTL_DISABLE_SECMEM; Arguments: none
661 This command disables the use of secure memory.  If this command is
662 used in FIPS mode, FIPS mode will be disabled and the function
663 @code{gcry_fips_mode_active} returns false.  However, in Enforced FIPS
664 mode this command has no effect at all.
665
666 Many applications do not require secure memory, so they should disable
667 it right away.  This command should be executed right after
668 @code{gcry_check_version}.
669
670 @item GCRYCTL_DISABLE_LOCKED_SECMEM; Arguments: none
671 This command disables the use of the mlock call for secure memory.
672 Disabling the use of mlock may for example be done if an encrypted
673 swap space is in use.  This command should be executed right after
674 @code{gcry_check_version}.  Note that by using functions like
675 gcry_xmalloc_secure and gcry_mpi_snew Libgcrypt may expand the secure
676 memory pool with memory which lacks the property of not being swapped
677 out to disk (but will still be zeroed out on free).
678
679 @item GCRYCTL_DISABLE_PRIV_DROP; Arguments: none
680 This command sets a global flag to tell the secure memory subsystem
681 that it shall not drop privileges after secure memory has been
682 allocated.  This command is commonly used right after
683 @code{gcry_check_version} but may also be used right away at program
684 startup.  It won't have an effect after the secure memory pool has
685 been initialized.  WARNING: A process running setuid(root) is a severe
686 security risk.  Processes making use of Libgcrypt or other complex
687 code should drop these extra privileges as soon as possible.  If this
688 command has been used the caller is responsible for dropping the
689 privileges.
690
691 @item GCRYCTL_INIT_SECMEM; Arguments: unsigned int nbytes
692 This command is used to allocate a pool of secure memory and thus
693 enabling the use of secure memory.  It also drops all extra privileges
694 the process has (i.e. if it is run as setuid (root)).  If the argument
695 @var{nbytes} is 0, secure memory will be disabled.  The minimum amount
696 of secure memory allocated is currently 16384 bytes; you may thus use a
697 value of 1 to request that default size.
698
699 @item GCRYCTL_TERM_SECMEM; Arguments: none
700 This command zeroises the secure memory and destroys the handler.  The
701 secure memory pool may not be used anymore after running this command.
702 If the secure memory pool as already been destroyed, this command has
703 no effect.  Applications might want to run this command from their
704 exit handler to make sure that the secure memory gets properly
705 destroyed.  This command is not necessarily thread-safe but that
706 should not be needed in cleanup code.  It may be called from a signal
707 handler.
708
709 @item GCRYCTL_DISABLE_SECMEM_WARN; Arguments: none
710 Disable warning messages about problems with the secure memory
711 subsystem. This command should be run right after
712 @code{gcry_check_version}.
713
714 @item GCRYCTL_SUSPEND_SECMEM_WARN; Arguments: none
715 Postpone warning messages from the secure memory subsystem.
716 @xref{sample-use-suspend-secmem,,the initialization example}, on how to
717 use it.
718
719 @item GCRYCTL_RESUME_SECMEM_WARN; Arguments: none
720 Resume warning messages from the secure memory subsystem.
721 @xref{sample-use-resume-secmem,,the initialization example}, on how to
722 use it.
723
724 @item GCRYCTL_USE_SECURE_RNDPOOL; Arguments: none
725 This command tells the PRNG to store random numbers in secure memory.
726 This command should be run right after @code{gcry_check_version} and not
727 later than the command GCRYCTL_INIT_SECMEM.  Note that in FIPS mode the
728 secure memory is always used.
729
730 @item GCRYCTL_SET_RANDOM_SEED_FILE; Arguments: const char *filename
731 This command specifies the file, which is to be used as seed file for
732 the PRNG.  If the seed file is registered prior to initialization of the
733 PRNG, the seed file's content (if it exists and seems to be valid) is
734 fed into the PRNG pool.  After the seed file has been registered, the
735 PRNG can be signalled to write out the PRNG pool's content into the seed
736 file with the following command.
737
738
739 @item GCRYCTL_UPDATE_RANDOM_SEED_FILE; Arguments: none
740 Write out the PRNG pool's content into the registered seed file.
741
742 Multiple instances of the applications sharing the same random seed file
743 can be started in parallel, in which case they will read out the same
744 pool and then race for updating it (the last update overwrites earlier
745 updates).  They will differentiate only by the weak entropy that is
746 added in read_seed_file based on the PID and clock, and up to 16 bytes
747 of weak random non-blockingly.  The consequence is that the output of
748 these different instances is correlated to some extent.  In a perfect
749 attack scenario, the attacker can control (or at least guess) the PID
750 and clock of the application, and drain the system's entropy pool to
751 reduce the "up to 16 bytes" above to 0.  Then the dependencies of the
752 initial states of the pools are completely known.  Note that this is not
753 an issue if random of @code{GCRY_VERY_STRONG_RANDOM} quality is
754 requested as in this case enough extra entropy gets mixed.  It is also
755 not an issue when using Linux (rndlinux driver), because this one
756 guarantees to read full 16 bytes from /dev/urandom and thus there is no
757 way for an attacker without kernel access to control these 16 bytes.
758
759 @item GCRYCTL_CLOSE_RANDOM_DEVICE; Arguments: none
760 Try to close the random device.  If on Unix system you call fork(),
761 the child process does no call exec(), and you do not intend to use
762 Libgcrypt in the child, it might be useful to use this control code to
763 close the inherited file descriptors of the random device.  If
764 Libgcrypt is later used again by the child, the device will be
765 re-opened.  On non-Unix systems this control code is ignored.
766
767 @item GCRYCTL_SET_VERBOSITY; Arguments: int level
768 This command sets the verbosity of the logging.  A level of 0 disables
769 all extra logging whereas positive numbers enable more verbose logging.
770 The level may be changed at any time but be aware that no memory
771 synchronization is done so the effect of this command might not
772 immediately show up in other threads.  This command may even be used
773 prior to @code{gcry_check_version}.
774
775 @item GCRYCTL_SET_DEBUG_FLAGS; Arguments: unsigned int flags
776 Set the debug flag bits as given by the argument.  Be aware that that no
777 memory synchronization is done so the effect of this command might not
778 immediately show up in other threads.  The debug flags are not
779 considered part of the API and thus may change without notice.  As of
780 now bit 0 enables debugging of cipher functions and bit 1 debugging of
781 multi-precision-integers.  This command may even be used prior to
782 @code{gcry_check_version}.
783
784 @item GCRYCTL_CLEAR_DEBUG_FLAGS; Arguments: unsigned int flags
785 Set the debug flag bits as given by the argument.  Be aware that that no
786 memory synchronization is done so the effect of this command might not
787 immediately show up in other threads.  This command may even be used
788 prior to @code{gcry_check_version}.
789
790 @item GCRYCTL_DISABLE_INTERNAL_LOCKING; Arguments: none
791 This command does nothing.  It exists only for backward compatibility.
792
793 @item GCRYCTL_ANY_INITIALIZATION_P; Arguments: none
794 This command returns true if the library has been basically initialized.
795 Such a basic initialization happens implicitly with many commands to get
796 certain internal subsystems running.  The common and suggested way to
797 do this basic initialization is by calling gcry_check_version.
798
799 @item GCRYCTL_INITIALIZATION_FINISHED; Arguments: none
800 This command tells the library that the application has finished the
801 initialization.
802
803 @item GCRYCTL_INITIALIZATION_FINISHED_P; Arguments: none
804 This command returns true if the command@*
805 GCRYCTL_INITIALIZATION_FINISHED has already been run.
806
807 @item GCRYCTL_SET_THREAD_CBS; Arguments: struct ath_ops *ath_ops
808 This command is obsolete since version 1.6.
809
810 @item GCRYCTL_FAST_POLL; Arguments: none
811 Run a fast random poll.
812
813 @item GCRYCTL_SET_RNDEGD_SOCKET; Arguments: const char *filename
814 This command may be used to override the default name of the EGD socket
815 to connect to.  It may be used only during initialization as it is not
816 thread safe.  Changing the socket name again is not supported.  The
817 function may return an error if the given filename is too long for a
818 local socket name.
819
820 EGD is an alternative random gatherer, used only on systems lacking a
821 proper random device.
822
823 @item GCRYCTL_PRINT_CONFIG; Arguments: FILE *stream
824 This command dumps information pertaining to the configuration of the
825 library to the given stream.  If NULL is given for @var{stream}, the log
826 system is used.  This command may be used before the initialization has
827 been finished but not before a @code{gcry_check_version}.  Note that
828 the macro @code{estream_t} can be used instead of @code{gpgrt_stream_t}.
829
830 @item GCRYCTL_OPERATIONAL_P; Arguments: none
831 This command returns true if the library is in an operational state.
832 This information makes only sense in FIPS mode.  In contrast to other
833 functions, this is a pure test function and won't put the library into
834 FIPS mode or change the internal state.  This command may be used before
835 the initialization has been finished but not before a @code{gcry_check_version}.
836
837 @item GCRYCTL_FIPS_MODE_P; Arguments: none
838 This command returns true if the library is in FIPS mode.  Note, that
839 this is no indication about the current state of the library.  This
840 command may be used before the initialization has been finished but not
841 before a @code{gcry_check_version}.  An application may use this command or
842 the convenience macro below to check whether FIPS mode is actually
843 active.
844
845 @deftypefun int gcry_fips_mode_active (void)
846
847 Returns true if the FIPS mode is active.  Note that this is
848 implemented as a macro.
849 @end deftypefun
850
851
852
853 @item GCRYCTL_FORCE_FIPS_MODE; Arguments: none
854 Running this command puts the library into FIPS mode.  If the library is
855 already in FIPS mode, a self-test is triggered and thus the library will
856 be put into operational state.  This command may be used before a call
857 to @code{gcry_check_version} and that is actually the recommended way to let an
858 application switch the library into FIPS mode.  Note that Libgcrypt will
859 reject an attempt to switch to fips mode during or after the initialization.
860
861 @item GCRYCTL_SET_ENFORCED_FIPS_FLAG; Arguments: none
862 Running this command sets the internal flag that puts the library into
863 the enforced FIPS mode during the FIPS mode initialization.  This command
864 does not affect the library if the library is not put into the FIPS mode and
865 it must be used before any other libgcrypt library calls that initialize
866 the library such as @code{gcry_check_version}. Note that Libgcrypt will
867 reject an attempt to switch to the enforced fips mode during or after
868 the initialization.
869
870 @item GCRYCTL_SET_PREFERRED_RNG_TYPE; Arguments: int
871 These are advisory commands to select a certain random number
872 generator.  They are only advisory because libraries may not know what
873 an application actually wants or vice versa.  Thus Libgcrypt employs a
874 priority check to select the actually used RNG.  If an applications
875 selects a lower priority RNG but a library requests a higher priority
876 RNG Libgcrypt will switch to the higher priority RNG.  Applications
877 and libraries should use these control codes before
878 @code{gcry_check_version}.  The available generators are:
879 @table @code
880 @item GCRY_RNG_TYPE_STANDARD
881 A conservative standard generator based on the ``Continuously Seeded
882 Pseudo Random Number Generator'' designed by Peter Gutmann.
883 @item GCRY_RNG_TYPE_FIPS
884 A deterministic random number generator conforming to he document
885 ``NIST-Recommended Random Number Generator Based on ANSI X9.31
886 Appendix A.2.4 Using the 3-Key Triple DES and AES Algorithms''
887 (2005-01-31).  This implementation uses the AES variant.
888 @item GCRY_RNG_TYPE_SYSTEM
889 A wrapper around the system's native RNG.  On Unix system these are
890 usually the /dev/random and /dev/urandom devices.
891 @end table
892 The default is @code{GCRY_RNG_TYPE_STANDARD} unless FIPS mode as been
893 enabled; in which case @code{GCRY_RNG_TYPE_FIPS} is used and locked
894 against further changes.
895
896 @item GCRYCTL_GET_CURRENT_RNG_TYPE; Arguments: int *
897 This command stores the type of the currently used RNG as an integer
898 value at the provided address.
899
900
901 @item GCRYCTL_SELFTEST; Arguments: none
902 This may be used at anytime to have the library run all implemented
903 self-tests.  It works in standard and in FIPS mode.  Returns 0 on
904 success or an error code on failure.
905
906 @item GCRYCTL_DISABLE_HWF; Arguments: const char *name
907
908 Libgcrypt detects certain features of the CPU at startup time.  For
909 performance tests it is sometimes required not to use such a feature.
910 This option may be used to disable a certain feature; i.e. Libgcrypt
911 behaves as if this feature has not been detected.  This call can be
912 used several times to disable a set of features, or features may be
913 given as a colon or comma delimited string.  The special feature
914 "all" can be used to disable all available features.
915
916 Note that the detection code might be run if the feature has been
917 disabled.  This command must be used at initialization time;
918 i.e. before calling @code{gcry_check_version}.
919
920 @item GCRYCTL_REINIT_SYSCALL_CLAMP; Arguments: none
921
922 Libgcrypt wraps blocking system calls with two functions calls
923 (``system call clamp'') to give user land threading libraries a hook
924 for re-scheduling.  This works by reading the system call clamp from
925 Libgpg-error at initialization time.  However sometimes Libgcrypt
926 needs to be initialized before the user land threading systems and at
927 that point the system call clamp has not been registered with
928 Libgpg-error and in turn Libgcrypt would not use them.  The control
929 code can be used to tell Libgcrypt that a system call clamp has now
930 been registered with Libgpg-error and advised it to read the clamp
931 again.  Obviously this control code may only be used before a second
932 thread is started in a process.
933
934
935 @end table
936
937 @end deftypefun
938
939 @c **********************************************************
940 @c *******************  Errors  ****************************
941 @c **********************************************************
942 @node Error Handling
943 @section Error Handling
944
945 Many functions in Libgcrypt can return an error if they
946 fail.  For this reason, the application should always catch the error
947 condition and take appropriate measures, for example by releasing the
948 resources and passing the error up to the caller, or by displaying a
949 descriptive message to the user and cancelling the operation.
950
951 Some error values do not indicate a system error or an error in the
952 operation, but the result of an operation that failed properly.  For
953 example, if you try to decrypt a tempered message, the decryption will
954 fail.  Another error value actually means that the end of a data
955 buffer or list has been reached.  The following descriptions explain
956 for many error codes what they mean usually.  Some error values have
957 specific meanings if returned by a certain functions.  Such cases are
958 described in the documentation of those functions.
959
960 Libgcrypt uses the @code{libgpg-error} library.  This allows to share
961 the error codes with other components of the GnuPG system, and to pass
962 error values transparently from the crypto engine, or some helper
963 application of the crypto engine, to the user.  This way no
964 information is lost.  As a consequence, Libgcrypt does not use its own
965 identifiers for error codes, but uses those provided by
966 @code{libgpg-error}.  They usually start with @code{GPG_ERR_}.
967
968 However, Libgcrypt does provide aliases for the functions
969 defined in libgpg-error, which might be preferred for name space
970 consistency.
971
972
973 Most functions in Libgcrypt return an error code in the case
974 of failure.  For this reason, the application should always catch the
975 error condition and take appropriate measures, for example by
976 releasing the resources and passing the error up to the caller, or by
977 displaying a descriptive message to the user and canceling the
978 operation.
979
980 Some error values do not indicate a system error or an error in the
981 operation, but the result of an operation that failed properly.
982
983 GnuPG components, including Libgcrypt, use an extra library named
984 libgpg-error to provide a common error handling scheme.  For more
985 information on libgpg-error, see the according manual.
986
987 @menu
988 * Error Values::                The error value and what it means.
989 * Error Sources::               A list of important error sources.
990 * Error Codes::                 A list of important error codes.
991 * Error Strings::               How to get a descriptive string from a value.
992 @end menu
993
994
995 @node Error Values
996 @subsection Error Values
997 @cindex error values
998 @cindex error codes
999 @cindex error sources
1000
1001 @deftp {Data type} {gcry_err_code_t}
1002 The @code{gcry_err_code_t} type is an alias for the
1003 @code{libgpg-error} type @code{gpg_err_code_t}.  The error code
1004 indicates the type of an error, or the reason why an operation failed.
1005
1006 A list of important error codes can be found in the next section.
1007 @end deftp
1008
1009 @deftp {Data type} {gcry_err_source_t}
1010 The @code{gcry_err_source_t} type is an alias for the
1011 @code{libgpg-error} type @code{gpg_err_source_t}.  The error source
1012 has not a precisely defined meaning.  Sometimes it is the place where
1013 the error happened, sometimes it is the place where an error was
1014 encoded into an error value.  Usually the error source will give an
1015 indication to where to look for the problem.  This is not always true,
1016 but it is attempted to achieve this goal.
1017
1018 A list of important error sources can be found in the next section.
1019 @end deftp
1020
1021 @deftp {Data type} {gcry_error_t}
1022 The @code{gcry_error_t} type is an alias for the @code{libgpg-error}
1023 type @code{gpg_error_t}.  An error value like this has always two
1024 components, an error code and an error source.  Both together form the
1025 error value.
1026
1027 Thus, the error value can not be directly compared against an error
1028 code, but the accessor functions described below must be used.
1029 However, it is guaranteed that only 0 is used to indicate success
1030 (@code{GPG_ERR_NO_ERROR}), and that in this case all other parts of
1031 the error value are set to 0, too.
1032
1033 Note that in Libgcrypt, the error source is used purely for
1034 diagnostic purposes.  Only the error code should be checked to test
1035 for a certain outcome of a function.  The manual only documents the
1036 error code part of an error value.  The error source is left
1037 unspecified and might be anything.
1038 @end deftp
1039
1040 @deftypefun {gcry_err_code_t} gcry_err_code (@w{gcry_error_t @var{err}})
1041 The static inline function @code{gcry_err_code} returns the
1042 @code{gcry_err_code_t} component of the error value @var{err}.  This
1043 function must be used to extract the error code from an error value in
1044 order to compare it with the @code{GPG_ERR_*} error code macros.
1045 @end deftypefun
1046
1047 @deftypefun {gcry_err_source_t} gcry_err_source (@w{gcry_error_t @var{err}})
1048 The static inline function @code{gcry_err_source} returns the
1049 @code{gcry_err_source_t} component of the error value @var{err}.  This
1050 function must be used to extract the error source from an error value in
1051 order to compare it with the @code{GPG_ERR_SOURCE_*} error source macros.
1052 @end deftypefun
1053
1054 @deftypefun {gcry_error_t} gcry_err_make (@w{gcry_err_source_t @var{source}}, @w{gcry_err_code_t @var{code}})
1055 The static inline function @code{gcry_err_make} returns the error
1056 value consisting of the error source @var{source} and the error code
1057 @var{code}.
1058
1059 This function can be used in callback functions to construct an error
1060 value to return it to the library.
1061 @end deftypefun
1062
1063 @deftypefun {gcry_error_t} gcry_error (@w{gcry_err_code_t @var{code}})
1064 The static inline function @code{gcry_error} returns the error value
1065 consisting of the default error source and the error code @var{code}.
1066
1067 For @acronym{GCRY} applications, the default error source is
1068 @code{GPG_ERR_SOURCE_USER_1}.  You can define
1069 @code{GCRY_ERR_SOURCE_DEFAULT} before including @file{gcrypt.h} to
1070 change this default.
1071
1072 This function can be used in callback functions to construct an error
1073 value to return it to the library.
1074 @end deftypefun
1075
1076 The @code{libgpg-error} library provides error codes for all system
1077 error numbers it knows about.  If @var{err} is an unknown error
1078 number, the error code @code{GPG_ERR_UNKNOWN_ERRNO} is used.  The
1079 following functions can be used to construct error values from system
1080 errno numbers.
1081
1082 @deftypefun {gcry_error_t} gcry_err_make_from_errno (@w{gcry_err_source_t @var{source}}, @w{int @var{err}})
1083 The function @code{gcry_err_make_from_errno} is like
1084 @code{gcry_err_make}, but it takes a system error like @code{errno}
1085 instead of a @code{gcry_err_code_t} error code.
1086 @end deftypefun
1087
1088 @deftypefun {gcry_error_t} gcry_error_from_errno (@w{int @var{err}})
1089 The function @code{gcry_error_from_errno} is like @code{gcry_error},
1090 but it takes a system error like @code{errno} instead of a
1091 @code{gcry_err_code_t} error code.
1092 @end deftypefun
1093
1094 Sometimes you might want to map system error numbers to error codes
1095 directly, or map an error code representing a system error back to the
1096 system error number.  The following functions can be used to do that.
1097
1098 @deftypefun {gcry_err_code_t} gcry_err_code_from_errno (@w{int @var{err}})
1099 The function @code{gcry_err_code_from_errno} returns the error code
1100 for the system error @var{err}.  If @var{err} is not a known system
1101 error, the function returns @code{GPG_ERR_UNKNOWN_ERRNO}.
1102 @end deftypefun
1103
1104 @deftypefun {int} gcry_err_code_to_errno (@w{gcry_err_code_t @var{err}})
1105 The function @code{gcry_err_code_to_errno} returns the system error
1106 for the error code @var{err}.  If @var{err} is not an error code
1107 representing a system error, or if this system error is not defined on
1108 this system, the function returns @code{0}.
1109 @end deftypefun
1110
1111
1112 @node Error Sources
1113 @subsection Error Sources
1114 @cindex error codes, list of
1115
1116 The library @code{libgpg-error} defines an error source for every
1117 component of the GnuPG system.  The error source part of an error
1118 value is not well defined.  As such it is mainly useful to improve the
1119 diagnostic error message for the user.
1120
1121 If the error code part of an error value is @code{0}, the whole error
1122 value will be @code{0}.  In this case the error source part is of
1123 course @code{GPG_ERR_SOURCE_UNKNOWN}.
1124
1125 The list of error sources that might occur in applications using
1126 @acronym{Libgcrypt} is:
1127
1128 @table @code
1129 @item GPG_ERR_SOURCE_UNKNOWN
1130 The error source is not known.  The value of this error source is
1131 @code{0}.
1132
1133 @item GPG_ERR_SOURCE_GPGME
1134 The error source is @acronym{GPGME} itself.
1135
1136 @item GPG_ERR_SOURCE_GPG
1137 The error source is GnuPG, which is the crypto engine used for the
1138 OpenPGP protocol.
1139
1140 @item GPG_ERR_SOURCE_GPGSM
1141 The error source is GPGSM, which is the crypto engine used for the
1142 OpenPGP protocol.
1143
1144 @item GPG_ERR_SOURCE_GCRYPT
1145 The error source is @code{libgcrypt}, which is used by crypto engines
1146 to perform cryptographic operations.
1147
1148 @item GPG_ERR_SOURCE_GPGAGENT
1149 The error source is @command{gpg-agent}, which is used by crypto
1150 engines to perform operations with the secret key.
1151
1152 @item GPG_ERR_SOURCE_PINENTRY
1153 The error source is @command{pinentry}, which is used by
1154 @command{gpg-agent} to query the passphrase to unlock a secret key.
1155
1156 @item GPG_ERR_SOURCE_SCD
1157 The error source is the SmartCard Daemon, which is used by
1158 @command{gpg-agent} to delegate operations with the secret key to a
1159 SmartCard.
1160
1161 @item GPG_ERR_SOURCE_KEYBOX
1162 The error source is @code{libkbx}, a library used by the crypto
1163 engines to manage local keyrings.
1164
1165 @item GPG_ERR_SOURCE_USER_1
1166 @item GPG_ERR_SOURCE_USER_2
1167 @item GPG_ERR_SOURCE_USER_3
1168 @item GPG_ERR_SOURCE_USER_4
1169 These error sources are not used by any GnuPG component and can be
1170 used by other software.  For example, applications using
1171 Libgcrypt can use them to mark error values coming from callback
1172 handlers.  Thus @code{GPG_ERR_SOURCE_USER_1} is the default for errors
1173 created with @code{gcry_error} and @code{gcry_error_from_errno},
1174 unless you define @code{GCRY_ERR_SOURCE_DEFAULT} before including
1175 @file{gcrypt.h}.
1176 @end table
1177
1178
1179 @node Error Codes
1180 @subsection Error Codes
1181 @cindex error codes, list of
1182
1183 The library @code{libgpg-error} defines many error values.  The
1184 following list includes the most important error codes.
1185
1186 @table @code
1187 @item GPG_ERR_EOF
1188 This value indicates the end of a list, buffer or file.
1189
1190 @item GPG_ERR_NO_ERROR
1191 This value indicates success.  The value of this error code is
1192 @code{0}.  Also, it is guaranteed that an error value made from the
1193 error code @code{0} will be @code{0} itself (as a whole).  This means
1194 that the error source information is lost for this error code,
1195 however, as this error code indicates that no error occurred, this is
1196 generally not a problem.
1197
1198 @item GPG_ERR_GENERAL
1199 This value means that something went wrong, but either there is not
1200 enough information about the problem to return a more useful error
1201 value, or there is no separate error value for this type of problem.
1202
1203 @item GPG_ERR_ENOMEM
1204 This value means that an out-of-memory condition occurred.
1205
1206 @item GPG_ERR_E...
1207 System errors are mapped to GPG_ERR_EFOO where FOO is the symbol for
1208 the system error.
1209
1210 @item GPG_ERR_INV_VALUE
1211 This value means that some user provided data was out of range.
1212
1213 @item GPG_ERR_UNUSABLE_PUBKEY
1214 This value means that some recipients for a message were invalid.
1215
1216 @item GPG_ERR_UNUSABLE_SECKEY
1217 This value means that some signers were invalid.
1218
1219 @item GPG_ERR_NO_DATA
1220 This value means that data was expected where no data was found.
1221
1222 @item GPG_ERR_CONFLICT
1223 This value means that a conflict of some sort occurred.
1224
1225 @item GPG_ERR_NOT_IMPLEMENTED
1226 This value indicates that the specific function (or operation) is not
1227 implemented.  This error should never happen.  It can only occur if
1228 you use certain values or configuration options which do not work,
1229 but for which we think that they should work at some later time.
1230
1231 @item GPG_ERR_DECRYPT_FAILED
1232 This value indicates that a decryption operation was unsuccessful.
1233
1234 @item GPG_ERR_WRONG_KEY_USAGE
1235 This value indicates that a key is not used appropriately.
1236
1237 @item GPG_ERR_NO_SECKEY
1238 This value indicates that no secret key for the user ID is available.
1239
1240 @item GPG_ERR_UNSUPPORTED_ALGORITHM
1241 This value means a verification failed because the cryptographic
1242 algorithm is not supported by the crypto backend.
1243
1244 @item GPG_ERR_BAD_SIGNATURE
1245 This value means a verification failed because the signature is bad.
1246
1247 @item GPG_ERR_NO_PUBKEY
1248 This value means a verification failed because the public key is not
1249 available.
1250
1251 @item GPG_ERR_NOT_OPERATIONAL
1252 This value means that the library is not yet in state which allows to
1253 use this function.  This error code is in particular returned if
1254 Libgcrypt is operated in FIPS mode and the internal state of the
1255 library does not yet or not anymore allow the use of a service.
1256
1257 This error code is only available with newer libgpg-error versions, thus
1258 you might see ``invalid error code'' when passing this to
1259 @code{gpg_strerror}.  The numeric value of this error code is 176.
1260
1261 @item GPG_ERR_USER_1
1262 @item GPG_ERR_USER_2
1263 @item ...
1264 @item GPG_ERR_USER_16
1265 These error codes are not used by any GnuPG component and can be
1266 freely used by other software.  Applications using Libgcrypt
1267 might use them to mark specific errors returned by callback handlers
1268 if no suitable error codes (including the system errors) for these
1269 errors exist already.
1270 @end table
1271
1272
1273 @node Error Strings
1274 @subsection Error Strings
1275 @cindex error values, printing of
1276 @cindex error codes, printing of
1277 @cindex error sources, printing of
1278 @cindex error strings
1279
1280 @deftypefun {const char *} gcry_strerror (@w{gcry_error_t @var{err}})
1281 The function @code{gcry_strerror} returns a pointer to a statically
1282 allocated string containing a description of the error code contained
1283 in the error value @var{err}.  This string can be used to output a
1284 diagnostic message to the user.
1285 @end deftypefun
1286
1287
1288 @deftypefun {const char *} gcry_strsource (@w{gcry_error_t @var{err}})
1289 The function @code{gcry_strsource} returns a pointer to a statically
1290 allocated string containing a description of the error source
1291 contained in the error value @var{err}.  This string can be used to
1292 output a diagnostic message to the user.
1293 @end deftypefun
1294
1295 The following example illustrates the use of the functions described
1296 above:
1297
1298 @example
1299 @{
1300   gcry_cipher_hd_t handle;
1301   gcry_error_t err = 0;
1302
1303   err = gcry_cipher_open (&handle, GCRY_CIPHER_AES,
1304                           GCRY_CIPHER_MODE_CBC, 0);
1305   if (err)
1306     @{
1307       fprintf (stderr, "Failure: %s/%s\n",
1308                gcry_strsource (err),
1309                gcry_strerror (err));
1310     @}
1311 @}
1312 @end example
1313
1314 @c **********************************************************
1315 @c *******************  General  ****************************
1316 @c **********************************************************
1317 @node Handler Functions
1318 @chapter Handler Functions
1319
1320 Libgcrypt makes it possible to install so called `handler functions',
1321 which get called by Libgcrypt in case of certain events.
1322
1323 @menu
1324 * Progress handler::            Using a progress handler function.
1325 * Allocation handler::          Using special memory allocation functions.
1326 * Error handler::               Using error handler functions.
1327 * Logging handler::             Using a special logging function.
1328 @end menu
1329
1330 @node Progress handler
1331 @section Progress handler
1332
1333 It is often useful to retrieve some feedback while long running
1334 operations are performed.
1335
1336 @deftp {Data type} gcry_handler_progress_t
1337 Progress handler functions have to be of the type
1338 @code{gcry_handler_progress_t}, which is defined as:
1339
1340 @code{void (*gcry_handler_progress_t) (void *, const char *, int, int, int)}
1341 @end deftp
1342
1343 The following function may be used to register a handler function for
1344 this purpose.
1345
1346 @deftypefun void gcry_set_progress_handler (gcry_handler_progress_t @var{cb}, void *@var{cb_data})
1347
1348 This function installs @var{cb} as the `Progress handler' function.
1349 It may be used only during initialization.  @var{cb} must be defined
1350 as follows:
1351
1352 @example
1353 void
1354 my_progress_handler (void *@var{cb_data}, const char *@var{what},
1355                      int @var{printchar}, int @var{current}, int @var{total})
1356 @{
1357   /* Do something.  */
1358 @}
1359 @end example
1360
1361 A description of the arguments of the progress handler function follows.
1362
1363 @table @var
1364 @item cb_data
1365 The argument provided in the call to @code{gcry_set_progress_handler}.
1366 @item what
1367 A string identifying the type of the progress output.  The following
1368 values for @var{what} are defined:
1369
1370 @table @code
1371 @item need_entropy
1372 Not enough entropy is available.  @var{total} holds the number of
1373 required bytes.
1374
1375 @item wait_dev_random
1376 Waiting to re-open a random device.  @var{total} gives the number of
1377 seconds until the next try.
1378
1379 @item primegen
1380 Values for @var{printchar}:
1381 @table @code
1382 @item \n
1383 Prime generated.
1384 @item !
1385 Need to refresh the pool of prime numbers.
1386 @item <, >
1387 Number of bits adjusted.
1388 @item ^
1389 Searching for a generator.
1390 @item .
1391 Fermat test on 10 candidates failed.
1392 @item :
1393 Restart with a new random value.
1394 @item +
1395 Rabin Miller test passed.
1396 @end table
1397
1398 @end table
1399
1400 @end table
1401 @end deftypefun
1402
1403 @node Allocation handler
1404 @section Allocation handler
1405
1406 It is possible to make Libgcrypt use special memory
1407 allocation functions instead of the built-in ones.
1408
1409 Memory allocation functions are of the following types:
1410 @deftp {Data type} gcry_handler_alloc_t
1411 This type is defined as: @code{void *(*gcry_handler_alloc_t) (size_t n)}.
1412 @end deftp
1413 @deftp {Data type} gcry_handler_secure_check_t
1414 This type is defined as: @code{int *(*gcry_handler_secure_check_t) (const void *)}.
1415 @end deftp
1416 @deftp {Data type} gcry_handler_realloc_t
1417 This type is defined as: @code{void *(*gcry_handler_realloc_t) (void *p, size_t n)}.
1418 @end deftp
1419 @deftp {Data type} gcry_handler_free_t
1420 This type is defined as: @code{void *(*gcry_handler_free_t) (void *)}.
1421 @end deftp
1422
1423 Special memory allocation functions can be installed with the
1424 following function:
1425
1426 @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})
1427 Install the provided functions and use them instead of the built-in
1428 functions for doing memory allocation.  Using this function is in
1429 general not recommended because the standard Libgcrypt allocation
1430 functions are guaranteed to zeroize memory if needed.
1431
1432 This function may be used only during initialization and may not be
1433 used in fips mode.
1434
1435
1436 @end deftypefun
1437
1438 @node Error handler
1439 @section Error handler
1440
1441 The following functions may be used to register handler functions that
1442 are called by Libgcrypt in case certain error conditions occur.  They
1443 may and should be registered prior to calling @code{gcry_check_version}.
1444
1445 @deftp {Data type} gcry_handler_no_mem_t
1446 This type is defined as: @code{int (*gcry_handler_no_mem_t) (void *, size_t, unsigned int)}
1447 @end deftp
1448 @deftypefun void gcry_set_outofcore_handler (gcry_handler_no_mem_t @var{func_no_mem}, void *@var{cb_data})
1449 This function registers @var{func_no_mem} as `out-of-core handler',
1450 which means that it will be called in the case of not having enough
1451 memory available.  The handler is called with 3 arguments: The first
1452 one is the pointer @var{cb_data} as set with this function, the second
1453 is the requested memory size and the last being a flag.  If bit 0 of
1454 the flag is set, secure memory has been requested.  The handler should
1455 either return true to indicate that Libgcrypt should try again
1456 allocating memory or return false to let Libgcrypt use its default
1457 fatal error handler.
1458 @end deftypefun
1459
1460 @deftp {Data type} gcry_handler_error_t
1461 This type is defined as: @code{void (*gcry_handler_error_t) (void *, int, const char *)}
1462 @end deftp
1463
1464 @deftypefun void gcry_set_fatalerror_handler (gcry_handler_error_t @var{func_error}, void *@var{cb_data})
1465 This function registers @var{func_error} as `error handler',
1466 which means that it will be called in error conditions.
1467 @end deftypefun
1468
1469 @node Logging handler
1470 @section Logging handler
1471
1472 @deftp {Data type} gcry_handler_log_t
1473 This type is defined as: @code{void (*gcry_handler_log_t) (void *, int, const char *, va_list)}
1474 @end deftp
1475
1476 @deftypefun void gcry_set_log_handler (gcry_handler_log_t @var{func_log}, void *@var{cb_data})
1477 This function registers @var{func_log} as `logging handler', which means
1478 that it will be called in case Libgcrypt wants to log a message.  This
1479 function may and should be used prior to calling
1480 @code{gcry_check_version}.
1481 @end deftypefun
1482
1483 @c **********************************************************
1484 @c *******************  Ciphers  ****************************
1485 @c **********************************************************
1486 @c @include cipher-ref.texi
1487 @node Symmetric cryptography
1488 @chapter Symmetric cryptography
1489
1490 The cipher functions are used for symmetrical cryptography,
1491 i.e. cryptography using a shared key.  The programming model follows
1492 an open/process/close paradigm and is in that similar to other
1493 building blocks provided by Libgcrypt.
1494
1495 @menu
1496 * Available ciphers::           List of ciphers supported by the library.
1497 * Available cipher modes::      List of cipher modes supported by the library.
1498 * Working with cipher handles::  How to perform operations related to cipher handles.
1499 * General cipher functions::    General cipher functions independent of cipher handles.
1500 @end menu
1501
1502 @node Available ciphers
1503 @section Available ciphers
1504
1505 @table @code
1506 @item GCRY_CIPHER_NONE
1507 This is not a real algorithm but used by some functions as error return.
1508 The value always evaluates to false.
1509
1510 @item GCRY_CIPHER_IDEA
1511 @cindex IDEA
1512 This is the IDEA algorithm.
1513
1514 @item GCRY_CIPHER_3DES
1515 @cindex 3DES
1516 @cindex Triple-DES
1517 @cindex DES-EDE
1518 @cindex Digital Encryption Standard
1519 Triple-DES with 3 Keys as EDE.  The key size of this algorithm is 168 but
1520 you have to pass 192 bits because the most significant bits of each byte
1521 are ignored.
1522
1523 @item GCRY_CIPHER_CAST5
1524 @cindex CAST5
1525 CAST128-5 block cipher algorithm.  The key size is 128 bits.
1526
1527 @item GCRY_CIPHER_BLOWFISH
1528 @cindex Blowfish
1529 The blowfish algorithm. The current implementation allows only for a key
1530 size of 128 bits.
1531
1532 @item GCRY_CIPHER_SAFER_SK128
1533 Reserved and not currently implemented.
1534
1535 @item GCRY_CIPHER_DES_SK
1536 Reserved and not currently implemented.
1537
1538 @item  GCRY_CIPHER_AES
1539 @itemx GCRY_CIPHER_AES128
1540 @itemx GCRY_CIPHER_RIJNDAEL
1541 @itemx GCRY_CIPHER_RIJNDAEL128
1542 @cindex Rijndael
1543 @cindex AES
1544 @cindex Advanced Encryption Standard
1545 AES (Rijndael) with a 128 bit key.
1546
1547 @item  GCRY_CIPHER_AES192
1548 @itemx GCRY_CIPHER_RIJNDAEL192
1549 AES (Rijndael) with a 192 bit key.
1550
1551 @item  GCRY_CIPHER_AES256
1552 @itemx GCRY_CIPHER_RIJNDAEL256
1553 AES (Rijndael) with a 256 bit key.
1554
1555 @item  GCRY_CIPHER_TWOFISH
1556 @cindex Twofish
1557 The Twofish algorithm with a 256 bit key.
1558
1559 @item  GCRY_CIPHER_TWOFISH128
1560 The Twofish algorithm with a 128 bit key.
1561
1562 @item  GCRY_CIPHER_ARCFOUR
1563 @cindex Arcfour
1564 @cindex RC4
1565 An algorithm which is 100% compatible with RSA Inc.'s RC4 algorithm.
1566 Note that this is a stream cipher and must be used very carefully to
1567 avoid a couple of weaknesses.
1568
1569 @item  GCRY_CIPHER_DES
1570 @cindex DES
1571 Standard DES with a 56 bit key. You need to pass 64 bit but the high
1572 bits of each byte are ignored.  Note, that this is a weak algorithm
1573 which can be broken in reasonable time using a brute force approach.
1574
1575 @item  GCRY_CIPHER_SERPENT128
1576 @itemx GCRY_CIPHER_SERPENT192
1577 @itemx GCRY_CIPHER_SERPENT256
1578 @cindex Serpent
1579 The Serpent cipher from the AES contest.
1580
1581 @item  GCRY_CIPHER_RFC2268_40
1582 @itemx GCRY_CIPHER_RFC2268_128
1583 @cindex rfc-2268
1584 @cindex RC2
1585 Ron's Cipher 2 in the 40 and 128 bit variants.
1586
1587 @item GCRY_CIPHER_SEED
1588 @cindex Seed (cipher)
1589 A 128 bit cipher as described by RFC4269.
1590
1591 @item  GCRY_CIPHER_CAMELLIA128
1592 @itemx GCRY_CIPHER_CAMELLIA192
1593 @itemx GCRY_CIPHER_CAMELLIA256
1594 @cindex Camellia
1595 The Camellia cipher by NTT.  See
1596 @uref{http://info.isl.ntt.co.jp/@/crypt/@/eng/@/camellia/@/specifications.html}.
1597
1598 @item GCRY_CIPHER_SALSA20
1599 @cindex Salsa20
1600 This is the Salsa20 stream cipher.
1601
1602 @item GCRY_CIPHER_SALSA20R12
1603 @cindex Salsa20/12
1604 This is the Salsa20/12 - reduced round version of Salsa20 stream cipher.
1605
1606 @item GCRY_CIPHER_GOST28147
1607 @cindex GOST 28147-89
1608 The GOST 28147-89 cipher, defined in the respective GOST standard.
1609 Translation of this GOST into English is provided in the RFC-5830.
1610
1611 @item GCRY_CIPHER_CHACHA20
1612 @cindex ChaCha20
1613 This is the ChaCha20 stream cipher.
1614
1615 @end table
1616
1617 @node Available cipher modes
1618 @section Available cipher modes
1619
1620 @table @code
1621 @item GCRY_CIPHER_MODE_NONE
1622 No mode specified.  This should not be used.  The only exception is that
1623 if Libgcrypt is not used in FIPS mode and if any debug flag has been
1624 set, this mode may be used to bypass the actual encryption.
1625
1626 @item GCRY_CIPHER_MODE_ECB
1627 @cindex ECB, Electronic Codebook mode
1628 Electronic Codebook mode.
1629
1630 @item GCRY_CIPHER_MODE_CFB
1631 @item GCRY_CIPHER_MODE_CFB8
1632 @cindex CFB, Cipher Feedback mode
1633 Cipher Feedback mode.  For GCRY_CIPHER_MODE_CFB the shift size equals
1634 the block size of the cipher (e.g. for AES it is CFB-128).  For
1635 GCRY_CIPHER_MODE_CFB8 the shift size is 8 bit but that variant is not
1636 yet available.
1637
1638 @item  GCRY_CIPHER_MODE_CBC
1639 @cindex CBC, Cipher Block Chaining mode
1640 Cipher Block Chaining mode.
1641
1642 @item GCRY_CIPHER_MODE_STREAM
1643 Stream mode, only to be used with stream cipher algorithms.
1644
1645 @item GCRY_CIPHER_MODE_OFB
1646 @cindex OFB, Output Feedback mode
1647 Output Feedback mode.
1648
1649 @item  GCRY_CIPHER_MODE_CTR
1650 @cindex CTR, Counter mode
1651 Counter mode.
1652
1653 @item  GCRY_CIPHER_MODE_AESWRAP
1654 @cindex AES-Wrap mode
1655 This mode is used to implement the AES-Wrap algorithm according to
1656 RFC-3394.  It may be used with any 128 bit block length algorithm,
1657 however the specs require one of the 3 AES algorithms.  These special
1658 conditions apply: If @code{gcry_cipher_setiv} has not been used the
1659 standard IV is used; if it has been used the lower 64 bit of the IV
1660 are used as the Alternative Initial Value.  On encryption the provided
1661 output buffer must be 64 bit (8 byte) larger than the input buffer;
1662 in-place encryption is still allowed.  On decryption the output buffer
1663 may be specified 64 bit (8 byte) shorter than then input buffer.  As
1664 per specs the input length must be at least 128 bits and the length
1665 must be a multiple of 64 bits.
1666
1667 @item  GCRY_CIPHER_MODE_CCM
1668 @cindex CCM, Counter with CBC-MAC mode
1669 Counter with CBC-MAC mode is an Authenticated Encryption with
1670 Associated Data (AEAD) block cipher mode, which is specified in
1671 'NIST Special Publication 800-38C' and RFC 3610.
1672
1673 @item  GCRY_CIPHER_MODE_GCM
1674 @cindex GCM, Galois/Counter Mode
1675 Galois/Counter Mode (GCM) is an Authenticated Encryption with
1676 Associated Data (AEAD) block cipher mode, which is specified in
1677 'NIST Special Publication 800-38D'.
1678
1679 @item  GCRY_CIPHER_MODE_POLY1305
1680 @cindex Poly1305 based AEAD mode with ChaCha20
1681 This mode implements the Poly1305 Authenticated Encryption with Associated
1682 Data (AEAD) mode according to RFC-7539. This mode can be used with ChaCha20
1683 stream cipher.
1684
1685 @item  GCRY_CIPHER_MODE_OCB
1686 @cindex OCB, OCB3
1687 OCB is an Authenticated Encryption with Associated Data (AEAD) block
1688 cipher mode, which is specified in RFC-7253.  Supported tag lengths
1689 are 128, 96, and 64 bit with the default being 128 bit.  To switch to
1690 a different tag length @code{gcry_cipher_ctl} using the command
1691 @code{GCRYCTL_SET_TAGLEN} and the address of an @code{int} variable
1692 set to 12 (for 96 bit) or 8 (for 64 bit) provided for the
1693 @code{buffer} argument and @code{sizeof(int)} for @code{buflen}.
1694
1695 Note that the use of @code{gcry_cipher_final} is required.
1696
1697 @item  GCRY_CIPHER_MODE_XTS
1698 @cindex XTS, XTS mode
1699 XEX-based tweaked-codebook mode with ciphertext stealing (XTS) mode
1700 is used to implement the AES-XTS as specified in IEEE 1619 Standard
1701 Architecture for Encrypted Shared Storage Media and NIST SP800-38E.
1702
1703 The XTS mode requires doubling key-length, for example, using 512-bit
1704 key with AES-256 (@code{GCRY_CIPHER_AES256}). The 128-bit tweak value
1705 is feed to XTS mode as little-endian byte array using
1706 @code{gcry_cipher_setiv} function. When encrypting or decrypting,
1707 full-sized data unit buffers needs to be passed to
1708 @code{gcry_cipher_encrypt} or @code{gcry_cipher_decrypt}. The tweak
1709 value is automatically incremented after each call of
1710 @code{gcry_cipher_encrypt} and @code{gcry_cipher_decrypt}.
1711 Auto-increment allows avoiding need of setting IV between processing
1712 of sequential data units.
1713
1714 @end table
1715
1716 @node Working with cipher handles
1717 @section Working with cipher handles
1718
1719 To use a cipher algorithm, you must first allocate an according
1720 handle.  This is to be done using the open function:
1721
1722 @deftypefun gcry_error_t gcry_cipher_open (gcry_cipher_hd_t *@var{hd}, int @var{algo}, int @var{mode}, unsigned int @var{flags})
1723
1724 This function creates the context handle required for most of the
1725 other cipher functions and returns a handle to it in `hd'.  In case of
1726 an error, an according error code is returned.
1727
1728 The ID of algorithm to use must be specified via @var{algo}.  See
1729 @ref{Available ciphers}, for a list of supported ciphers and the
1730 according constants.
1731
1732 Besides using the constants directly, the function
1733 @code{gcry_cipher_map_name} may be used to convert the textual name of
1734 an algorithm into the according numeric ID.
1735
1736 The cipher mode to use must be specified via @var{mode}.  See
1737 @ref{Available cipher modes}, for a list of supported cipher modes
1738 and the according constants.  Note that some modes are incompatible
1739 with some algorithms - in particular, stream mode
1740 (@code{GCRY_CIPHER_MODE_STREAM}) only works with stream ciphers.
1741 Poly1305 AEAD mode (@code{GCRY_CIPHER_MODE_POLY1305}) only works with
1742 ChaCha20 stream cipher. The block cipher modes
1743 (@code{GCRY_CIPHER_MODE_ECB}, @code{GCRY_CIPHER_MODE_CBC},
1744 @code{GCRY_CIPHER_MODE_CFB}, @code{GCRY_CIPHER_MODE_OFB} and
1745 @code{GCRY_CIPHER_MODE_CTR}) will work with any block cipher
1746 algorithm.  GCM mode (@code{GCRY_CIPHER_MODE_CCM}), CCM mode
1747 (@code{GCRY_CIPHER_MODE_GCM}), OCB mode (@code{GCRY_CIPHER_MODE_OCB}),
1748 and XTS mode (@code{GCRY_CIPHER_MODE_XTS}) will only work
1749 with block cipher algorithms which have the block size of 16 bytes.
1750
1751 The third argument @var{flags} can either be passed as @code{0} or as
1752 the bit-wise OR of the following constants.
1753
1754 @table @code
1755 @item GCRY_CIPHER_SECURE
1756 Make sure that all operations are allocated in secure memory.  This is
1757 useful when the key material is highly confidential.
1758 @item GCRY_CIPHER_ENABLE_SYNC
1759 @cindex sync mode (OpenPGP)
1760 This flag enables the CFB sync mode, which is a special feature of
1761 Libgcrypt's CFB mode implementation to allow for OpenPGP's CFB variant.
1762 See @code{gcry_cipher_sync}.
1763 @item GCRY_CIPHER_CBC_CTS
1764 @cindex cipher text stealing
1765 Enable cipher text stealing (CTS) for the CBC mode.  Cannot be used
1766 simultaneous as GCRY_CIPHER_CBC_MAC.  CTS mode makes it possible to
1767 transform data of almost arbitrary size (only limitation is that it
1768 must be greater than the algorithm's block size).
1769 @item GCRY_CIPHER_CBC_MAC
1770 @cindex CBC-MAC
1771 Compute CBC-MAC keyed checksums.  This is the same as CBC mode, but
1772 only output the last block.  Cannot be used simultaneous as
1773 GCRY_CIPHER_CBC_CTS.
1774 @end table
1775 @end deftypefun
1776
1777 Use the following function to release an existing handle:
1778
1779 @deftypefun void gcry_cipher_close (gcry_cipher_hd_t @var{h})
1780
1781 This function releases the context created by @code{gcry_cipher_open}.
1782 It also zeroises all sensitive information associated with this cipher
1783 handle.
1784 @end deftypefun
1785
1786 In order to use a handle for performing cryptographic operations, a
1787 `key' has to be set first:
1788
1789 @deftypefun gcry_error_t gcry_cipher_setkey (gcry_cipher_hd_t @var{h}, const void *@var{k}, size_t @var{l})
1790
1791 Set the key @var{k} used for encryption or decryption in the context
1792 denoted by the handle @var{h}.  The length @var{l} (in bytes) of the
1793 key @var{k} must match the required length of the algorithm set for
1794 this context or be in the allowed range for algorithms with variable
1795 key size.  The function checks this and returns an error if there is a
1796 problem.  A caller should always check for an error.
1797
1798 @end deftypefun
1799
1800 Most crypto modes requires an initialization vector (IV), which
1801 usually is a non-secret random string acting as a kind of salt value.
1802 The CTR mode requires a counter, which is also similar to a salt
1803 value.  To set the IV or CTR, use these functions:
1804
1805 @deftypefun gcry_error_t gcry_cipher_setiv (gcry_cipher_hd_t @var{h}, const void *@var{k}, size_t @var{l})
1806
1807 Set the initialization vector used for encryption or decryption. The
1808 vector is passed as the buffer @var{K} of length @var{l} bytes and
1809 copied to internal data structures.  The function checks that the IV
1810 matches the requirement of the selected algorithm and mode.
1811
1812 This function is also used by AEAD modes and with Salsa20 and ChaCha20
1813 stream ciphers to set or update the required nonce.  In these cases it
1814 needs to be called after setting the key.
1815
1816 @end deftypefun
1817
1818 @deftypefun gcry_error_t gcry_cipher_setctr (gcry_cipher_hd_t @var{h}, const void *@var{c}, size_t @var{l})
1819
1820 Set the counter vector used for encryption or decryption. The counter
1821 is passed as the buffer @var{c} of length @var{l} bytes and copied to
1822 internal data structures.  The function checks that the counter
1823 matches the requirement of the selected algorithm (i.e., it must be
1824 the same size as the block size).
1825 @end deftypefun
1826
1827 @deftypefun gcry_error_t gcry_cipher_reset (gcry_cipher_hd_t @var{h})
1828
1829 Set the given handle's context back to the state it had after the last
1830 call to gcry_cipher_setkey and clear the initialization vector.
1831
1832 Note that gcry_cipher_reset is implemented as a macro.
1833 @end deftypefun
1834
1835 Authenticated Encryption with Associated Data (AEAD) block cipher
1836 modes require the handling of the authentication tag and the additional
1837 authenticated data, which can be done by using the following
1838 functions:
1839
1840 @deftypefun gcry_error_t gcry_cipher_authenticate (gcry_cipher_hd_t @var{h}, const void *@var{abuf}, size_t @var{abuflen})
1841
1842 Process the buffer @var{abuf} of length @var{abuflen} as the additional
1843 authenticated data (AAD) for AEAD cipher modes.
1844
1845 @end deftypefun
1846
1847 @deftypefun {gcry_error_t} gcry_cipher_gettag @
1848             (@w{gcry_cipher_hd_t @var{h}}, @
1849             @w{void *@var{tag}}, @w{size_t @var{taglen}})
1850
1851 This function is used to read the authentication tag after encryption.
1852 The function finalizes and outputs the authentication tag to the buffer
1853 @var{tag} of length @var{taglen} bytes.
1854
1855 Depending on the used mode certain restrictions for @var{taglen} are
1856 enforced:  For GCM @var{taglen} must be at least 16 or one of the
1857 allowed truncated lengths (4, 8, 12, 13, 14, or 15).
1858
1859 @end deftypefun
1860
1861 @deftypefun {gcry_error_t} gcry_cipher_checktag @
1862             (@w{gcry_cipher_hd_t @var{h}}, @
1863             @w{const void *@var{tag}}, @w{size_t @var{taglen}})
1864
1865 Check the authentication tag after decryption. The authentication
1866 tag is passed as the buffer @var{tag} of length @var{taglen} bytes
1867 and compared to internal authentication tag computed during
1868 decryption.  Error code @code{GPG_ERR_CHECKSUM} is returned if
1869 the authentication tag in the buffer @var{tag} does not match
1870 the authentication tag calculated during decryption.
1871
1872 Depending on the used mode certain restrictions for @var{taglen} are
1873 enforced: For GCM @var{taglen} must either be 16 or one of the allowed
1874 truncated lengths (4, 8, 12, 13, 14, or 15).
1875
1876 @end deftypefun
1877
1878 The actual encryption and decryption is done by using one of the
1879 following functions.  They may be used as often as required to process
1880 all the data.
1881
1882 @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})
1883
1884 @code{gcry_cipher_encrypt} is used to encrypt the data.  This function
1885 can either work in place or with two buffers.  It uses the cipher
1886 context already setup and described by the handle @var{h}.  There are 2
1887 ways to use the function: If @var{in} is passed as @code{NULL} and
1888 @var{inlen} is @code{0}, in-place encryption of the data in @var{out} of
1889 length @var{outsize} takes place.  With @var{in} being not @code{NULL},
1890 @var{inlen} bytes are encrypted to the buffer @var{out} which must have
1891 at least a size of @var{inlen}.  @var{outsize} must be set to the
1892 allocated size of @var{out}, so that the function can check that there
1893 is sufficient space. Note that overlapping buffers are not allowed.
1894
1895 Depending on the selected algorithms and encryption mode, the length of
1896 the buffers must be a multiple of the block size.
1897
1898 Some encryption modes require that @code{gcry_cipher_final} is used
1899 before the final data chunk is passed to this function.
1900
1901 The function returns @code{0} on success or an error code.
1902 @end deftypefun
1903
1904
1905 @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})
1906
1907 @code{gcry_cipher_decrypt} is used to decrypt the data.  This function
1908 can either work in place or with two buffers.  It uses the cipher
1909 context already setup and described by the handle @var{h}.  There are 2
1910 ways to use the function: If @var{in} is passed as @code{NULL} and
1911 @var{inlen} is @code{0}, in-place decryption of the data in @var{out} or
1912 length @var{outsize} takes place.  With @var{in} being not @code{NULL},
1913 @var{inlen} bytes are decrypted to the buffer @var{out} which must have
1914 at least a size of @var{inlen}.  @var{outsize} must be set to the
1915 allocated size of @var{out}, so that the function can check that there
1916 is sufficient space.  Note that overlapping buffers are not allowed.
1917
1918 Depending on the selected algorithms and encryption mode, the length of
1919 the buffers must be a multiple of the block size.
1920
1921 Some encryption modes require that @code{gcry_cipher_final} is used
1922 before the final data chunk is passed to this function.
1923
1924 The function returns @code{0} on success or an error code.
1925 @end deftypefun
1926
1927
1928 The OCB mode features integrated padding and must thus be told about
1929 the end of the input data. This is done with:
1930
1931 @deftypefun gcry_error_t gcry_cipher_final (gcry_cipher_hd_t @var{h})
1932
1933 Set a flag in the context to tell the encrypt and decrypt functions
1934 that their next call will provide the last chunk of data.  Only the
1935 first call to this function has an effect and only for modes which
1936 support it.  Checking the error is in general not necessary.  This is
1937 implemented as a macro.
1938 @end deftypefun
1939
1940
1941 OpenPGP (as defined in RFC-4880) requires a special sync operation in
1942 some places.  The following function is used for this:
1943
1944 @deftypefun gcry_error_t gcry_cipher_sync (gcry_cipher_hd_t @var{h})
1945
1946 Perform the OpenPGP sync operation on context @var{h}.  Note that this
1947 is a no-op unless the context was created with the flag
1948 @code{GCRY_CIPHER_ENABLE_SYNC}
1949 @end deftypefun
1950
1951 Some of the described functions are implemented as macros utilizing a
1952 catch-all control function.  This control function is rarely used
1953 directly but there is nothing which would inhibit it:
1954
1955 @deftypefun gcry_error_t gcry_cipher_ctl (gcry_cipher_hd_t @var{h}, int @var{cmd}, void *@var{buffer}, size_t @var{buflen})
1956
1957 @code{gcry_cipher_ctl} controls various aspects of the cipher module and
1958 specific cipher contexts.  Usually some more specialized functions or
1959 macros are used for this purpose.  The semantics of the function and its
1960 parameters depends on the the command @var{cmd} and the passed context
1961 handle @var{h}.  Please see the comments in the source code
1962 (@code{src/global.c}) for details.
1963 @end deftypefun
1964
1965 @deftypefun gcry_error_t gcry_cipher_info (gcry_cipher_hd_t @var{h}, @
1966               int @var{what}, void *@var{buffer}, size_t *@var{nbytes})
1967
1968 @code{gcry_cipher_info} is used to retrieve various
1969 information about a cipher context or the cipher module in general.
1970
1971 @c begin constants for gcry_cipher_info
1972 @table @code
1973
1974 @item GCRYCTL_GET_TAGLEN:
1975 Return the length of the tag for an AE algorithm mode.  An error is
1976 returned for modes which do not support a tag.  @var{buffer} must be
1977 given as NULL.  On success the result is stored @var{nbytes}.  The
1978 taglen is returned in bytes.
1979
1980 @end table
1981 @c end constants for gcry_cipher_info
1982
1983 @end deftypefun
1984
1985 @node General cipher functions
1986 @section General cipher functions
1987
1988 To work with the algorithms, several functions are available to map
1989 algorithm names to the internal identifiers, as well as ways to
1990 retrieve information about an algorithm or the current cipher context.
1991
1992 @deftypefun gcry_error_t gcry_cipher_algo_info (int @var{algo}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes})
1993
1994 This function is used to retrieve information on a specific algorithm.
1995 You pass the cipher algorithm ID as @var{algo} and the type of
1996 information requested as @var{what}. The result is either returned as
1997 the return code of the function or copied to the provided @var{buffer}
1998 whose allocated length must be available in an integer variable with the
1999 address passed in @var{nbytes}.  This variable will also receive the
2000 actual used length of the buffer.
2001
2002 Here is a list of supported codes for @var{what}:
2003
2004 @c begin constants for gcry_cipher_algo_info
2005 @table @code
2006 @item GCRYCTL_GET_KEYLEN:
2007 Return the length of the key. If the algorithm supports multiple key
2008 lengths, the maximum supported value is returned.  The length is
2009 returned as number of octets (bytes) and not as number of bits in
2010 @var{nbytes}; @var{buffer} must be zero.  Note that it is usually
2011 better to use the convenience function
2012 @code{gcry_cipher_get_algo_keylen}.
2013
2014 @item GCRYCTL_GET_BLKLEN:
2015 Return the block length of the algorithm.  The length is returned as a
2016 number of octets in @var{nbytes}; @var{buffer} must be zero.  Note
2017 that it is usually better to use the convenience function
2018 @code{gcry_cipher_get_algo_blklen}.
2019
2020 @item GCRYCTL_TEST_ALGO:
2021 Returns @code{0} when the specified algorithm is available for use.
2022 @var{buffer} and @var{nbytes} must be zero.
2023
2024 @end table
2025 @c end constants for gcry_cipher_algo_info
2026
2027 @end deftypefun
2028 @c end gcry_cipher_algo_info
2029
2030 @deftypefun size_t gcry_cipher_get_algo_keylen (@var{algo})
2031
2032 This function returns length of the key for algorithm @var{algo}.  If
2033 the algorithm supports multiple key lengths, the maximum supported key
2034 length is returned.  On error @code{0} is returned.  The key length is
2035 returned as number of octets.
2036
2037 This is a convenience functions which should be preferred over
2038 @code{gcry_cipher_algo_info} because it allows for proper type
2039 checking.
2040 @end deftypefun
2041 @c end gcry_cipher_get_algo_keylen
2042
2043 @deftypefun size_t gcry_cipher_get_algo_blklen (int @var{algo})
2044
2045 This functions returns the block-length of the algorithm @var{algo}
2046 counted in octets.  On error @code{0} is returned.
2047
2048 This is a convenience functions which should be preferred over
2049 @code{gcry_cipher_algo_info} because it allows for proper type
2050 checking.
2051 @end deftypefun
2052 @c end gcry_cipher_get_algo_blklen
2053
2054
2055 @deftypefun {const char *} gcry_cipher_algo_name (int @var{algo})
2056
2057 @code{gcry_cipher_algo_name} returns a string with the name of the
2058 cipher algorithm @var{algo}.  If the algorithm is not known or another
2059 error occurred, the string @code{"?"} is returned.  This function should
2060 not be used to test for the availability of an algorithm.
2061 @end deftypefun
2062
2063 @deftypefun int gcry_cipher_map_name (const char *@var{name})
2064
2065 @code{gcry_cipher_map_name} returns the algorithm identifier for the
2066 cipher algorithm described by the string @var{name}.  If this algorithm
2067 is not available @code{0} is returned.
2068 @end deftypefun
2069
2070 @deftypefun int gcry_cipher_mode_from_oid (const char *@var{string})
2071
2072 Return the cipher mode associated with an @acronym{ASN.1} object
2073 identifier.  The object identifier is expected to be in the
2074 @acronym{IETF}-style dotted decimal notation.  The function returns
2075 @code{0} for an unknown object identifier or when no mode is associated
2076 with it.
2077 @end deftypefun
2078
2079
2080 @c **********************************************************
2081 @c *******************  Public Key  *************************
2082 @c **********************************************************
2083 @node Public Key cryptography
2084 @chapter Public Key cryptography
2085
2086 Public key cryptography, also known as asymmetric cryptography, is an
2087 easy way for key management and to provide digital signatures.
2088 Libgcrypt provides two completely different interfaces to
2089 public key cryptography, this chapter explains the one based on
2090 S-expressions.
2091
2092 @menu
2093 * Available algorithms::        Algorithms supported by the library.
2094 * Used S-expressions::          Introduction into the used S-expression.
2095 * Cryptographic Functions::     Functions for performing the cryptographic actions.
2096 * General public-key related Functions::  General functions, not implementing any cryptography.
2097 @end menu
2098
2099 @node Available algorithms
2100 @section Available algorithms
2101
2102 Libgcrypt supports the RSA (Rivest-Shamir-Adleman) algorithms as well
2103 as DSA (Digital Signature Algorithm) and Elgamal.  The versatile
2104 interface allows to add more algorithms in the future.
2105
2106 @node Used S-expressions
2107 @section Used S-expressions
2108
2109 Libgcrypt's API for asymmetric cryptography is based on data structures
2110 called S-expressions (see
2111 @uref{http://people.csail.mit.edu/@/rivest/@/sexp.html}) and does not work
2112 with contexts as most of the other building blocks of Libgcrypt do.
2113
2114 @noindent
2115 The following information are stored in S-expressions:
2116
2117 @itemize
2118 @item keys
2119
2120 @item plain text data
2121
2122 @item encrypted data
2123
2124 @item signatures
2125
2126 @end itemize
2127
2128 @noindent
2129 To describe how Libgcrypt expect keys, we use examples. Note that
2130 words in
2131 @ifnottex
2132 uppercase
2133 @end ifnottex
2134 @iftex
2135 italics
2136 @end iftex
2137 indicate parameters whereas lowercase words are literals.
2138
2139 Note that all MPI (multi-precision-integers) values are expected to be in
2140 @code{GCRYMPI_FMT_USG} format.  An easy way to create S-expressions is
2141 by using @code{gcry_sexp_build} which allows to pass a string with
2142 printf-like escapes to insert MPI values.
2143
2144 @menu
2145 * RSA key parameters::  Parameters used with an RSA key.
2146 * DSA key parameters::  Parameters used with a DSA key.
2147 * ECC key parameters::  Parameters used with ECC keys.
2148 @end menu
2149
2150 @node RSA key parameters
2151 @subsection RSA key parameters
2152
2153 @noindent
2154 An RSA private key is described by this S-expression:
2155
2156 @example
2157 (private-key
2158   (rsa
2159     (n @var{n-mpi})
2160     (e @var{e-mpi})
2161     (d @var{d-mpi})
2162     (p @var{p-mpi})
2163     (q @var{q-mpi})
2164     (u @var{u-mpi})))
2165 @end example
2166
2167 @noindent
2168 An RSA public key is described by this S-expression:
2169
2170 @example
2171 (public-key
2172   (rsa
2173     (n @var{n-mpi})
2174     (e @var{e-mpi})))
2175 @end example
2176
2177
2178 @table @var
2179 @item n-mpi
2180 RSA public modulus @math{n}.
2181 @item e-mpi
2182 RSA public exponent @math{e}.
2183 @item d-mpi
2184 RSA secret exponent @math{d = e^{-1} \bmod (p-1)(q-1)}.
2185 @item p-mpi
2186 RSA secret prime @math{p}.
2187 @item q-mpi
2188 RSA secret prime @math{q} with @math{p < q}.
2189 @item u-mpi
2190 Multiplicative inverse @math{u = p^{-1} \bmod q}.
2191 @end table
2192
2193 For signing and decryption the parameters @math{(p, q, u)} are optional
2194 but greatly improve the performance.  Either all of these optional
2195 parameters must be given or none of them.  They are mandatory for
2196 gcry_pk_testkey.
2197
2198 Note that OpenSSL uses slighly different parameters: @math{q < p} and
2199  @math{u = q^{-1} \bmod p}.  To use these parameters you will need to
2200 swap the values and recompute @math{u}.  Here is example code to do this:
2201
2202 @example
2203   if (gcry_mpi_cmp (p, q) > 0)
2204     @{
2205       gcry_mpi_swap (p, q);
2206       gcry_mpi_invm (u, p, q);
2207     @}
2208 @end example
2209
2210
2211
2212
2213 @node DSA key parameters
2214 @subsection DSA key parameters
2215
2216 @noindent
2217 A DSA private key is described by this S-expression:
2218
2219 @example
2220 (private-key
2221   (dsa
2222     (p @var{p-mpi})
2223     (q @var{q-mpi})
2224     (g @var{g-mpi})
2225     (y @var{y-mpi})
2226     (x @var{x-mpi})))
2227 @end example
2228
2229 @table @var
2230 @item p-mpi
2231 DSA prime @math{p}.
2232 @item q-mpi
2233 DSA group order @math{q} (which is a prime divisor of @math{p-1}).
2234 @item g-mpi
2235 DSA group generator @math{g}.
2236 @item y-mpi
2237 DSA public key value @math{y = g^x \bmod p}.
2238 @item x-mpi
2239 DSA secret exponent x.
2240 @end table
2241
2242 The public key is similar with "private-key" replaced by "public-key"
2243 and no @var{x-mpi}.
2244
2245
2246 @node ECC key parameters
2247 @subsection ECC key parameters
2248
2249 @anchor{ecc_keyparam}
2250 @noindent
2251 An ECC private key is described by this S-expression:
2252
2253 @example
2254 (private-key
2255   (ecc
2256     (p @var{p-mpi})
2257     (a @var{a-mpi})
2258     (b @var{b-mpi})
2259     (g @var{g-point})
2260     (n @var{n-mpi})
2261     (q @var{q-point})
2262     (d @var{d-mpi})))
2263 @end example
2264
2265 @table @var
2266 @item p-mpi
2267 Prime specifying the field @math{GF(p)}.
2268 @item a-mpi
2269 @itemx b-mpi
2270 The two coefficients of the Weierstrass equation @math{y^2 = x^3 + ax + b}
2271 @item g-point
2272 Base point @math{g}.
2273 @item n-mpi
2274 Order of @math{g}
2275 @item q-point
2276 The point representing the public key @math{Q = dG}.
2277 @item d-mpi
2278 The private key @math{d}
2279 @end table
2280
2281 All point values are encoded in standard format; Libgcrypt does in
2282 general only support uncompressed points, thus the first byte needs to
2283 be @code{0x04}.  However ``EdDSA'' describes its own compression
2284 scheme which is used by default; the non-standard first byte
2285 @code{0x40} may optionally be used to explicit flag the use of the
2286 algorithm’s native compression method.
2287
2288 The public key is similar with "private-key" replaced by "public-key"
2289 and no @var{d-mpi}.
2290
2291 If the domain parameters are well-known, the name of this curve may be
2292 used.  For example
2293
2294 @example
2295 (private-key
2296   (ecc
2297     (curve "NIST P-192")
2298     (q @var{q-point})
2299     (d @var{d-mpi})))
2300 @end example
2301
2302 Note that @var{q-point} is optional for a private key.  The
2303 @code{curve} parameter may be given in any case and is used to replace
2304 missing parameters.
2305
2306 @noindent
2307 Currently implemented curves are:
2308 @table @code
2309 @item NIST P-192
2310 @itemx 1.2.840.10045.3.1.1
2311 @itemx prime192v1
2312 @itemx secp192r1
2313 The NIST 192 bit curve, its OID, X9.62 and SECP aliases.
2314
2315 @item NIST P-224
2316 @itemx secp224r1
2317 The NIST 224 bit curve and its SECP alias.
2318
2319 @item NIST P-256
2320 @itemx 1.2.840.10045.3.1.7
2321 @itemx prime256v1
2322 @itemx secp256r1
2323 The NIST 256 bit curve, its OID, X9.62 and SECP aliases.
2324
2325 @item NIST P-384
2326 @itemx secp384r1
2327 The NIST 384 bit curve and its SECP alias.
2328
2329 @item NIST P-521
2330 @itemx secp521r1
2331 The NIST 521 bit curve and its SECP alias.
2332
2333 @end table
2334 As usual the OIDs may optionally be prefixed with the string @code{OID.}
2335 or @code{oid.}.
2336
2337
2338 @node Cryptographic Functions
2339 @section Cryptographic Functions
2340
2341 @noindent
2342 Some functions operating on S-expressions support `flags' to influence
2343 the operation.  These flags have to be listed in a sub-S-expression
2344 named `flags'.  Flag names are case-sensitive.  The following flags
2345 are known:
2346
2347 @table @code
2348
2349 @item comp
2350 @itemx nocomp
2351 @cindex comp
2352 @cindex nocomp
2353 If supported by the algorithm and curve the @code{comp} flag requests
2354 that points are returned in compact (compressed) representation.  The
2355 @code{nocomp} flag requests that points are returned with full
2356 coordinates.  The default depends on the the algorithm and curve.  The
2357 compact representation requires a small overhead before a point can be
2358 used but halves the size of a to be conveyed public key.  If
2359 @code{comp} is used with the ``EdDSA'' algorithm the key generation
2360 prefix the public key with a @code{0x40} byte.
2361
2362 @item pkcs1
2363 @cindex PKCS1
2364 Use PKCS#1 block type 2 padding for encryption, block type 1 padding
2365 for signing.
2366
2367 @item oaep
2368 @cindex OAEP
2369 Use RSA-OAEP padding for encryption.
2370
2371 @item pss
2372 @cindex PSS
2373 Use RSA-PSS padding for signing.
2374
2375 @item eddsa
2376 @cindex EdDSA
2377 Use the EdDSA scheme signing instead of the default ECDSA algorithm.
2378 Note that the EdDSA uses a special form of the public key.
2379
2380 @item rfc6979
2381 @cindex RFC6979
2382 For DSA and ECDSA use a deterministic scheme for the k parameter.
2383
2384 @item no-blinding
2385 @cindex no-blinding
2386 Do not use a technique called `blinding', which is used by default in
2387 order to prevent leaking of secret information.  Blinding is only
2388 implemented by RSA, but it might be implemented by other algorithms in
2389 the future as well, when necessary.
2390
2391 @item param
2392 @cindex param
2393 For ECC key generation also return the domain parameters.  For ECC
2394 signing and verification override default parameters by provided
2395 domain parameters of the public or private key.
2396
2397 @item transient-key
2398 @cindex transient-key
2399 This flag is only meaningful for RSA, DSA, and ECC key generation.  If
2400 given the key is created using a faster and a somewhat less secure
2401 random number generator.  This flag may be used for keys which are
2402 only used for a short time or per-message and do not require full
2403 cryptographic strength.
2404
2405 @item no-keytest
2406 @cindex no-keytest
2407 This flag skips internal failsafe tests to assert that a generated key
2408 is properly working.  It currently has an effect only for standard ECC
2409 key generation.  It is mostly useful along with transient-key to
2410 achieve fastest ECC key generation.
2411
2412 @item use-x931
2413 @cindex X9.31
2414 Force the use of the ANSI X9.31 key generation algorithm instead of
2415 the default algorithm. This flag is only meaningful for RSA key
2416 generation and usually not required.  Note that this algorithm is
2417 implicitly used if either @code{derive-parms} is given or Libgcrypt is
2418 in FIPS mode.
2419
2420 @item use-fips186
2421 @cindex FIPS 186
2422 Force the use of the FIPS 186 key generation algorithm instead of the
2423 default algorithm.  This flag is only meaningful for DSA and usually
2424 not required.  Note that this algorithm is implicitly used if either
2425 @code{derive-parms} is given or Libgcrypt is in FIPS mode.  As of now
2426 FIPS 186-2 is implemented; after the approval of FIPS 186-3 the code
2427 will be changed to implement 186-3.
2428
2429 @item use-fips186-2
2430 @cindex FIPS 186-2
2431 Force the use of the FIPS 186-2 key generation algorithm instead of
2432 the default algorithm.  This algorithm is slightly different from
2433 FIPS 186-3 and allows only 1024 bit keys.  This flag is only meaningful
2434 for DSA and only required for FIPS testing backward compatibility.
2435
2436 @end table
2437
2438 @noindent
2439 Now that we know the key basics, we can carry on and explain how to
2440 encrypt and decrypt data.  In almost all cases the data is a random
2441 session key which is in turn used for the actual encryption of the real
2442 data.  There are 2 functions to do this:
2443
2444 @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}})
2445
2446 Obviously a public key must be provided for encryption.  It is
2447 expected as an appropriate S-expression (see above) in @var{pkey}.
2448 The data to be encrypted can either be in the simple old format, which
2449 is a very simple S-expression consisting only of one MPI, or it may be
2450 a more complex S-expression which also allows to specify flags for
2451 operation, like e.g. padding rules.
2452
2453 @noindent
2454 If you don't want to let Libgcrypt handle the padding, you must pass an
2455 appropriate MPI using this expression for @var{data}:
2456
2457 @example
2458 (data
2459   (flags raw)
2460   (value @var{mpi}))
2461 @end example
2462
2463 @noindent
2464 This has the same semantics as the old style MPI only way.  @var{MPI}
2465 is the actual data, already padded appropriate for your protocol.
2466 Most RSA based systems however use PKCS#1 padding and so you can use
2467 this S-expression for @var{data}:
2468
2469 @example
2470 (data
2471   (flags pkcs1)
2472   (value @var{block}))
2473 @end example
2474
2475 @noindent
2476 Here, the "flags" list has the "pkcs1" flag which let the function know
2477 that it should provide PKCS#1 block type 2 padding.  The actual data to
2478 be encrypted is passed as a string of octets in @var{block}.  The
2479 function checks that this data actually can be used with the given key,
2480 does the padding and encrypts it.
2481
2482 If the function could successfully perform the encryption, the return
2483 value will be 0 and a new S-expression with the encrypted result is
2484 allocated and assigned to the variable at the address of @var{r_ciph}.
2485 The caller is responsible to release this value using
2486 @code{gcry_sexp_release}.  In case of an error, an error code is
2487 returned and @var{r_ciph} will be set to @code{NULL}.
2488
2489 @noindent
2490 The returned S-expression has this format when used with RSA:
2491
2492 @example
2493 (enc-val
2494   (rsa
2495     (a @var{a-mpi})))
2496 @end example
2497
2498 @noindent
2499 Where @var{a-mpi} is an MPI with the result of the RSA operation.  When
2500 using the Elgamal algorithm, the return value will have this format:
2501
2502 @example
2503 (enc-val
2504   (elg
2505     (a @var{a-mpi})
2506     (b @var{b-mpi})))
2507 @end example
2508
2509 @noindent
2510 Where @var{a-mpi} and @var{b-mpi} are MPIs with the result of the
2511 Elgamal encryption operation.
2512 @end deftypefun
2513 @c end gcry_pk_encrypt
2514
2515 @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}})
2516
2517 Obviously a private key must be provided for decryption.  It is expected
2518 as an appropriate S-expression (see above) in @var{skey}.  The data to
2519 be decrypted must match the format of the result as returned by
2520 @code{gcry_pk_encrypt}, but should be enlarged with a @code{flags}
2521 element:
2522
2523 @example
2524 (enc-val
2525   (flags)
2526   (elg
2527     (a @var{a-mpi})
2528     (b @var{b-mpi})))
2529 @end example
2530
2531 @noindent
2532 This function does not remove padding from the data by default.  To
2533 let Libgcrypt remove padding, give a hint in `flags' telling which
2534 padding method was used when encrypting:
2535
2536 @example
2537 (flags @var{padding-method})
2538 @end example
2539
2540 @noindent
2541 Currently @var{padding-method} is either @code{pkcs1} for PKCS#1 block
2542 type 2 padding, or @code{oaep} for RSA-OAEP padding.
2543
2544 @noindent
2545 The function returns 0 on success or an error code.  The variable at the
2546 address of @var{r_plain} will be set to NULL on error or receive the
2547 decrypted value on success.  The format of @var{r_plain} is a
2548 simple S-expression part (i.e. not a valid one) with just one MPI if
2549 there was no @code{flags} element in @var{data}; if at least an empty
2550 @code{flags} is passed in @var{data}, the format is:
2551
2552 @example
2553 (value @var{plaintext})
2554 @end example
2555 @end deftypefun
2556 @c end gcry_pk_decrypt
2557
2558
2559 Another operation commonly performed using public key cryptography is
2560 signing data.  In some sense this is even more important than
2561 encryption because digital signatures are an important instrument for
2562 key management.  Libgcrypt supports digital signatures using
2563 2 functions, similar to the encryption functions:
2564
2565 @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}})
2566
2567 This function creates a digital signature for @var{data} using the
2568 private key @var{skey} and place it into the variable at the address of
2569 @var{r_sig}.  @var{data} may either be the simple old style S-expression
2570 with just one MPI or a modern and more versatile S-expression which
2571 allows to let Libgcrypt handle padding:
2572
2573 @example
2574  (data
2575   (flags pkcs1)
2576   (hash @var{hash-algo} @var{block}))
2577 @end example
2578
2579 @noindent
2580 This example requests to sign the data in @var{block} after applying
2581 PKCS#1 block type 1 style padding.  @var{hash-algo} is a string with the
2582 hash algorithm to be encoded into the signature, this may be any hash
2583 algorithm name as supported by Libgcrypt.  Most likely, this will be
2584 "sha256" or "sha1".  It is obvious that the length of @var{block} must
2585 match the size of that message digests; the function checks that this
2586 and other constraints are valid.
2587
2588 @noindent
2589 If PKCS#1 padding is not required (because the caller does already
2590 provide a padded value), either the old format or better the following
2591 format should be used:
2592
2593 @example
2594 (data
2595   (flags raw)
2596   (value @var{mpi}))
2597 @end example
2598
2599 @noindent
2600 Here, the data to be signed is directly given as an @var{MPI}.
2601
2602 @noindent
2603 For DSA the input data is expected in this format:
2604
2605 @example
2606 (data
2607   (flags raw)
2608   (value @var{mpi}))
2609 @end example
2610
2611 @noindent
2612 Here, the data to be signed is directly given as an @var{MPI}.  It is
2613 expect that this MPI is the the hash value.  For the standard DSA
2614 using a MPI is not a problem in regard to leading zeroes because the
2615 hash value is directly used as an MPI.  For better standard
2616 conformance it would be better to explicit use a memory string (like
2617 with pkcs1) but that is currently not supported.  However, for
2618 deterministic DSA as specified in RFC6979 this can't be used.  Instead
2619 the following input is expected.
2620
2621 @example
2622 (data
2623   (flags rfc6979)
2624   (hash @var{hash-algo} @var{block}))
2625 @end example
2626
2627 Note that the provided hash-algo is used for the internal HMAC; it
2628 should match the hash-algo used to create @var{block}.
2629
2630
2631 @noindent
2632 The signature is returned as a newly allocated S-expression in
2633 @var{r_sig} using this format for RSA:
2634
2635 @example
2636 (sig-val
2637   (rsa
2638     (s @var{s-mpi})))
2639 @end example
2640
2641 Where @var{s-mpi} is the result of the RSA sign operation.  For DSA the
2642 S-expression returned is:
2643
2644 @example
2645 (sig-val
2646   (dsa
2647     (r @var{r-mpi})
2648     (s @var{s-mpi})))
2649 @end example
2650
2651 Where @var{r-mpi} and @var{s-mpi} are the result of the DSA sign
2652 operation.
2653
2654 For Elgamal signing (which is slow, yields large numbers, hard to use
2655 correctly and probably is not as secure as the other algorithms), the
2656 same format is used with "elg" replacing "dsa"; for ECDSA signing, the
2657 same format is used with "ecdsa" replacing "dsa".
2658
2659 For the EdDSA algorithm (cf. Ed25515) the required input parameters are:
2660
2661 @example
2662 (data
2663   (flags eddsa)
2664   (hash-algo sha512)
2665   (value @var{message}))
2666 @end example
2667
2668 Note that the @var{message} may be of any length; hashing is part of
2669 the algorithm.  Using a large data block for @var{message} is not
2670 suggested; in that case the used protocol should better require that a
2671 hash of the message is used as input to the EdDSA algorithm.
2672
2673
2674 @end deftypefun
2675 @c end gcry_pk_sign
2676
2677 @noindent
2678 The operation most commonly used is definitely the verification of a
2679 signature.  Libgcrypt provides this function:
2680
2681 @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}})
2682
2683 This is used to check whether the signature @var{sig} matches the
2684 @var{data}.  The public key @var{pkey} must be provided to perform this
2685 verification.  This function is similar in its parameters to
2686 @code{gcry_pk_sign} with the exceptions that the public key is used
2687 instead of the private key and that no signature is created but a
2688 signature, in a format as created by @code{gcry_pk_sign}, is passed to
2689 the function in @var{sig}.
2690
2691 @noindent
2692 The result is 0 for success (i.e. the data matches the signature), or an
2693 error code where the most relevant code is @code{GCRY_ERR_BAD_SIGNATURE}
2694 to indicate that the signature does not match the provided data.
2695
2696 @end deftypefun
2697 @c end gcry_pk_verify
2698
2699 @node General public-key related Functions
2700 @section General public-key related Functions
2701
2702 @noindent
2703 A couple of utility functions are available to retrieve the length of
2704 the key, map algorithm identifiers and perform sanity checks:
2705
2706 @deftypefun {const char *} gcry_pk_algo_name (int @var{algo})
2707
2708 Map the public key algorithm id @var{algo} to a string representation of
2709 the algorithm name.  For unknown algorithms this functions returns the
2710 string @code{"?"}.  This function should not be used to test for the
2711 availability of an algorithm.
2712 @end deftypefun
2713
2714 @deftypefun int gcry_pk_map_name (const char *@var{name})
2715
2716 Map the algorithm @var{name} to a public key algorithm Id.  Returns 0 if
2717 the algorithm name is not known.
2718 @end deftypefun
2719
2720 @deftypefun int gcry_pk_test_algo (int @var{algo})
2721
2722 Return 0 if the public key algorithm @var{algo} is available for use.
2723 Note that this is implemented as a macro.
2724 @end deftypefun
2725
2726
2727 @deftypefun {unsigned int} gcry_pk_get_nbits (gcry_sexp_t @var{key})
2728
2729 Return what is commonly referred as the key length for the given
2730 public or private in @var{key}.
2731 @end deftypefun
2732
2733 @deftypefun {unsigned char *} gcry_pk_get_keygrip (@w{gcry_sexp_t @var{key}}, @w{unsigned char *@var{array}})
2734
2735 Return the so called "keygrip" which is the SHA-1 hash of the public key
2736 parameters expressed in a way depended on the algorithm.  @var{array}
2737 must either provide space for 20 bytes or be @code{NULL}. In the latter
2738 case a newly allocated array of that size is returned.  On success a
2739 pointer to the newly allocated space or to @var{array} is returned.
2740 @code{NULL} is returned to indicate an error which is most likely an
2741 unknown algorithm or one where a "keygrip" has not yet been defined.
2742 The function accepts public or secret keys in @var{key}.
2743 @end deftypefun
2744
2745 @deftypefun gcry_error_t gcry_pk_testkey (gcry_sexp_t @var{key})
2746
2747 Return zero if the private key @var{key} is `sane', an error code otherwise.
2748 Note that it is not possible to check the `saneness' of a public key.
2749
2750 @end deftypefun
2751
2752
2753 @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}})
2754
2755 Depending on the value of @var{what} return various information about
2756 the public key algorithm with the id @var{algo}.  Note that the
2757 function returns @code{-1} on error and the actual error code must be
2758 retrieved using the function @code{gcry_errno}.  The currently defined
2759 values for @var{what} are:
2760
2761 @table @code
2762 @item GCRYCTL_TEST_ALGO:
2763 Return 0 if the specified algorithm is available for use.
2764 @var{buffer} must be @code{NULL}, @var{nbytes} may be passed as
2765 @code{NULL} or point to a variable with the required usage of the
2766 algorithm. This may be 0 for "don't care" or the bit-wise OR of these
2767 flags:
2768
2769 @table @code
2770 @item GCRY_PK_USAGE_SIGN
2771 Algorithm is usable for signing.
2772 @item GCRY_PK_USAGE_ENCR
2773 Algorithm is usable for encryption.
2774 @end table
2775
2776 Unless you need to test for the allowed usage, it is in general better
2777 to use the macro gcry_pk_test_algo instead.
2778
2779 @item GCRYCTL_GET_ALGO_USAGE:
2780 Return the usage flags for the given algorithm.  An invalid algorithm
2781 return 0.  Disabled algorithms are ignored here because we
2782 want to know whether the algorithm is at all capable of a certain usage.
2783
2784 @item GCRYCTL_GET_ALGO_NPKEY
2785 Return the number of elements the public key for algorithm @var{algo}
2786 consist of.  Return 0 for an unknown algorithm.
2787
2788 @item GCRYCTL_GET_ALGO_NSKEY
2789 Return the number of elements the private key for algorithm @var{algo}
2790 consist of.  Note that this value is always larger than that of the
2791 public key.  Return 0 for an unknown algorithm.
2792
2793 @item GCRYCTL_GET_ALGO_NSIGN
2794 Return the number of elements a signature created with the algorithm
2795 @var{algo} consists of.  Return 0 for an unknown algorithm or for an
2796 algorithm not capable of creating signatures.
2797
2798 @item GCRYCTL_GET_ALGO_NENC
2799 Return the number of elements a encrypted message created with the algorithm
2800 @var{algo} consists of.  Return 0 for an unknown algorithm or for an
2801 algorithm not capable of encryption.
2802 @end table
2803
2804 @noindent
2805 Please note that parameters not required should be passed as @code{NULL}.
2806 @end deftypefun
2807 @c end gcry_pk_algo_info
2808
2809
2810 @deftypefun gcry_error_t gcry_pk_ctl (@w{int @var{cmd}}, @w{void *@var{buffer}}, @w{size_t @var{buflen}})
2811
2812 This is a general purpose function to perform certain control
2813 operations.  @var{cmd} controls what is to be done. The return value is
2814 0 for success or an error code.  Currently supported values for
2815 @var{cmd} are:
2816
2817 @table @code
2818 @item GCRYCTL_DISABLE_ALGO
2819 Disable the algorithm given as an algorithm id in @var{buffer}.
2820 @var{buffer} must point to an @code{int} variable with the algorithm
2821 id and @var{buflen} must have the value @code{sizeof (int)}.  This
2822 function is not thread safe and should thus be used before any other
2823 threads are started.
2824
2825 @end table
2826 @end deftypefun
2827 @c end gcry_pk_ctl
2828
2829 @noindent
2830 Libgcrypt also provides a function to generate public key
2831 pairs:
2832
2833 @deftypefun gcry_error_t gcry_pk_genkey (@w{gcry_sexp_t *@var{r_key}}, @w{gcry_sexp_t @var{parms}})
2834
2835 This function create a new public key pair using information given in
2836 the S-expression @var{parms} and stores the private and the public key
2837 in one new S-expression at the address given by @var{r_key}.  In case of
2838 an error, @var{r_key} is set to @code{NULL}.  The return code is 0 for
2839 success or an error code otherwise.
2840
2841 @noindent
2842 Here is an example for @var{parms} to create an 2048 bit RSA key:
2843
2844 @example
2845 (genkey
2846   (rsa
2847     (nbits 4:2048)))
2848 @end example
2849
2850 @noindent
2851 To create an Elgamal key, substitute "elg" for "rsa" and to create a DSA
2852 key use "dsa".  Valid ranges for the key length depend on the
2853 algorithms; all commonly used key lengths are supported.  Currently
2854 supported parameters are:
2855
2856 @table @code
2857 @item nbits
2858 This is always required to specify the length of the key.  The
2859 argument is a string with a number in C-notation.  The value should be
2860 a multiple of 8.  Note that the S-expression syntax requires that a
2861 number is prefixed with its string length; thus the @code{4:} in the
2862 above example.
2863
2864 @item curve @var{name}
2865 For ECC a named curve may be used instead of giving the number of
2866 requested bits.  This allows to request a specific curve to override a
2867 default selection Libgcrypt would have taken if @code{nbits} has been
2868 given.  The available names are listed with the description of the ECC
2869 public key parameters.
2870
2871 @item rsa-use-e @var{value}
2872 This is only used with RSA to give a hint for the public exponent. The
2873 @var{value} will be used as a base to test for a usable exponent. Some
2874 values are special:
2875
2876 @table @samp
2877 @item 0
2878 Use a secure and fast value.  This is currently the number 41.
2879 @item 1
2880 Use a value as required by some crypto policies.  This is currently
2881 the number 65537.
2882 @item 2
2883 Reserved
2884 @item > 2
2885 Use the given value.
2886 @end table
2887
2888 @noindent
2889 If this parameter is not used, Libgcrypt uses for historic reasons
2890 65537.  Note that the value must fit into a 32 bit unsigned variable
2891 and that the usual C prefixes are considered (e.g. 017 gives 15).
2892
2893
2894 @item qbits @var{n}
2895 This is only meanigful for DSA keys.  If it is given the DSA key is
2896 generated with a Q parameyer of size @var{n} bits.  If it is not given
2897 or zero Q is deduced from NBITS in this way:
2898 @table @samp
2899 @item 512 <= N <= 1024
2900 Q = 160
2901 @item N = 2048
2902 Q = 224
2903 @item N = 3072
2904 Q = 256
2905 @item N = 7680
2906 Q = 384
2907 @item N = 15360
2908 Q = 512
2909 @end table
2910 Note that in this case only the values for N, as given in the table,
2911 are allowed.  When specifying Q all values of N in the range 512 to
2912 15680 are valid as long as they are multiples of 8.
2913
2914 @item domain @var{list}
2915 This is only meaningful for DLP algorithms.  If specified keys are
2916 generated with domain parameters taken from this list.  The exact
2917 format of this parameter depends on the actual algorithm.  It is
2918 currently only implemented for DSA using this format:
2919
2920 @example
2921 (genkey
2922   (dsa
2923     (domain
2924       (p @var{p-mpi})
2925       (q @var{q-mpi})
2926       (g @var{q-mpi}))))
2927 @end example
2928
2929 @code{nbits} and @code{qbits} may not be specified because they are
2930 derived from the domain parameters.
2931
2932 @item derive-parms @var{list}
2933 This is currently only implemented for RSA and DSA keys.  It is not
2934 allowed to use this together with a @code{domain} specification.  If
2935 given, it is used to derive the keys using the given parameters.
2936
2937 If given for an RSA key the X9.31 key generation algorithm is used
2938 even if libgcrypt is not in FIPS mode.  If given for a DSA key, the
2939 FIPS 186 algorithm is used even if libgcrypt is not in FIPS mode.
2940
2941 @example
2942 (genkey
2943   (rsa
2944     (nbits 4:1024)
2945     (rsa-use-e 1:3)
2946     (derive-parms
2947       (Xp1 #1A1916DDB29B4EB7EB6732E128#)
2948       (Xp2 #192E8AAC41C576C822D93EA433#)
2949       (Xp  #D8CD81F035EC57EFE822955149D3BFF70C53520D
2950             769D6D76646C7A792E16EBD89FE6FC5B605A6493
2951             39DFC925A86A4C6D150B71B9EEA02D68885F5009
2952             B98BD984#)
2953       (Xq1 #1A5CF72EE770DE50CB09ACCEA9#)
2954       (Xq2 #134E4CAA16D2350A21D775C404#)
2955       (Xq  #CC1092495D867E64065DEE3E7955F2EBC7D47A2D
2956             7C9953388F97DDDC3E1CA19C35CA659EDC2FC325
2957             6D29C2627479C086A699A49C4C9CEE7EF7BD1B34
2958             321DE34A#))))
2959 @end example
2960
2961 @example
2962 (genkey
2963   (dsa
2964     (nbits 4:1024)
2965     (derive-parms
2966       (seed @var{seed-mpi}))))
2967 @end example
2968
2969
2970 @item flags @var{flaglist}
2971 This is preferred way to define flags.  @var{flaglist} may contain any
2972 number of flags.  See above for a specification of these flags.
2973
2974 Here is an example on how to create a key using curve Ed25519 with the
2975 ECDSA signature algorithm.  Note that the use of ECDSA with that curve
2976 is in general not recommended.
2977 @example
2978 (genkey
2979   (ecc
2980     (flags transient-key)))
2981 @end example
2982
2983 @item transient-key
2984 @itemx use-x931
2985 @itemx use-fips186
2986 @itemx use-fips186-2
2987 These are deprecated ways to set a flag with that name; see above for
2988 a description of each flag.
2989
2990
2991 @end table
2992 @c end table of parameters
2993
2994 @noindent
2995 The key pair is returned in a format depending on the algorithm.  Both
2996 private and public keys are returned in one container and may be
2997 accompanied by some miscellaneous information.
2998
2999 @noindent
3000 Here are two examples; the first for Elgamal and the second for
3001 elliptic curve key generation:
3002
3003 @example
3004 (key-data
3005   (public-key
3006     (elg
3007       (p @var{p-mpi})
3008       (g @var{g-mpi})
3009       (y @var{y-mpi})))
3010   (private-key
3011     (elg
3012       (p @var{p-mpi})
3013       (g @var{g-mpi})
3014       (y @var{y-mpi})
3015       (x @var{x-mpi})))
3016   (misc-key-info
3017     (pm1-factors @var{n1 n2 ... nn}))
3018 @end example
3019
3020 @example
3021 (key-data
3022   (public-key
3023     (ecc
3024       (curve Ed25519)
3025       (flags eddsa)
3026       (q @var{q-value})))
3027   (private-key
3028     (ecc
3029       (curve Ed25519)
3030       (flags eddsa)
3031       (q @var{q-value})
3032       (d @var{d-value}))))
3033 @end example
3034
3035 @noindent
3036 As you can see, some of the information is duplicated, but this
3037 provides an easy way to extract either the public or the private key.
3038 Note that the order of the elements is not defined, e.g. the private
3039 key may be stored before the public key. @var{n1 n2 ... nn} is a list
3040 of prime numbers used to composite @var{p-mpi}; this is in general not
3041 a very useful information and only available if the key generation
3042 algorithm provides them.
3043 @end deftypefun
3044 @c end gcry_pk_genkey
3045
3046
3047 @noindent
3048 Future versions of Libgcrypt will have extended versions of the public
3049 key interfaced which will take an additional context to allow for
3050 pre-computations, special operations, and other optimization.  As a
3051 first step a new function is introduced to help using the ECC
3052 algorithms in new ways:
3053
3054 @deftypefun gcry_error_t gcry_pubkey_get_sexp (@w{gcry_sexp_t *@var{r_sexp}}, @
3055  @w{int @var{mode}}, @w{gcry_ctx_t @var{ctx}})
3056
3057 Return an S-expression representing the context @var{ctx}.  Depending
3058 on the state of that context, the S-expression may either be a public
3059 key, a private key or any other object used with public key
3060 operations.  On success 0 is returned and a new S-expression is stored
3061 at @var{r_sexp}; on error an error code is returned and NULL is stored
3062 at @var{r_sexp}.  @var{mode} must be one of:
3063
3064 @table @code
3065 @item 0
3066 Decide what to return depending on the context.  For example if the
3067 private key parameter is available a private key is returned, if not a
3068 public key is returned.
3069
3070 @item GCRY_PK_GET_PUBKEY
3071 Return the public key even if the context has the private key
3072 parameter.
3073
3074 @item GCRY_PK_GET_SECKEY
3075 Return the private key or the error @code{GPG_ERR_NO_SECKEY} if it is
3076 not possible.
3077 @end table
3078
3079 As of now this function supports only certain ECC operations because a
3080 context object is right now only defined for ECC.  Over time this
3081 function will be extended to cover more algorithms.
3082
3083 @end deftypefun
3084 @c end gcry_pubkey_get_sexp
3085
3086
3087
3088
3089
3090 @c **********************************************************
3091 @c *******************  Hash Functions  *********************
3092 @c **********************************************************
3093 @node Hashing
3094 @chapter Hashing
3095
3096 Libgcrypt provides an easy and consistent to use interface for hashing.
3097 Hashing is buffered and several hash algorithms can be updated at once.
3098 It is possible to compute a HMAC using the same routines.  The
3099 programming model follows an open/process/close paradigm and is in that
3100 similar to other building blocks provided by Libgcrypt.
3101
3102 For convenience reasons, a few cyclic redundancy check value operations
3103 are also supported.
3104
3105 @menu
3106 * Available hash algorithms::   List of hash algorithms supported by the library.
3107 * Working with hash algorithms::  List of functions related to hashing.
3108 @end menu
3109
3110 @node Available hash algorithms
3111 @section Available hash algorithms
3112
3113 @c begin table of hash algorithms
3114 @cindex SHA-1
3115 @cindex SHA-224, SHA-256, SHA-384, SHA-512
3116 @cindex SHA3-224, SHA3-256, SHA3-384, SHA3-512, SHAKE128, SHAKE256
3117 @cindex RIPE-MD-160
3118 @cindex MD2, MD4, MD5
3119 @cindex TIGER, TIGER1, TIGER2
3120 @cindex HAVAL
3121 @cindex Whirlpool
3122 @cindex BLAKE2b-512, BLAKE2b-384, BLAKE2b-256, BLAKE2b-160
3123 @cindex BLAKE2s-256, BLAKE2s-224, BLAKE2s-160, BLAKE2s-128
3124 @cindex CRC32
3125 @table @code
3126 @item GCRY_MD_NONE
3127 This is not a real algorithm but used by some functions as an error
3128 return value.  This constant is guaranteed to have the value @code{0}.
3129
3130 @item GCRY_MD_SHA1
3131 This is the SHA-1 algorithm which yields a message digest of 20 bytes.
3132 Note that SHA-1 begins to show some weaknesses and it is suggested to
3133 fade out its use if strong cryptographic properties are required.
3134
3135 @item GCRY_MD_RMD160
3136 This is the 160 bit version of the RIPE message digest (RIPE-MD-160).
3137 Like SHA-1 it also yields a digest of 20 bytes.  This algorithm share a
3138 lot of design properties with SHA-1 and thus it is advisable not to use
3139 it for new protocols.
3140
3141 @item GCRY_MD_MD5
3142 This is the well known MD5 algorithm, which yields a message digest of
3143 16 bytes.  Note that the MD5 algorithm has severe weaknesses, for
3144 example it is easy to compute two messages yielding the same hash
3145 (collision attack).  The use of this algorithm is only justified for
3146 non-cryptographic application.
3147
3148
3149 @item GCRY_MD_MD4
3150 This is the MD4 algorithm, which yields a message digest of 16 bytes.
3151 This algorithm has severe weaknesses and should not be used.
3152
3153 @item GCRY_MD_MD2
3154 This is an reserved identifier for MD-2; there is no implementation yet.
3155 This algorithm has severe weaknesses and should not be used.
3156
3157 @item GCRY_MD_TIGER
3158 This is the TIGER/192 algorithm which yields a message digest of 24
3159 bytes.  Actually this is a variant of TIGER with a different output
3160 print order as used by GnuPG up to version 1.3.2.
3161
3162 @item GCRY_MD_TIGER1
3163 This is the TIGER variant as used by the NESSIE project.  It uses the
3164 most commonly used output print order.
3165
3166 @item GCRY_MD_TIGER2
3167 This is another variant of TIGER with a different padding scheme.
3168
3169
3170 @item GCRY_MD_HAVAL
3171 This is an reserved value for the HAVAL algorithm with 5 passes and 160
3172 bit. It yields a message digest of 20 bytes.  Note that there is no
3173 implementation yet available.
3174
3175 @item GCRY_MD_SHA224
3176 This is the SHA-224 algorithm which yields a message digest of 28 bytes.
3177 See Change Notice 1 for FIPS 180-2 for the specification.
3178
3179 @item GCRY_MD_SHA256
3180 This is the SHA-256 algorithm which yields a message digest of 32 bytes.
3181 See FIPS 180-2 for the specification.
3182
3183 @item GCRY_MD_SHA384
3184 This is the SHA-384 algorithm which yields a message digest of 48 bytes.
3185 See FIPS 180-2 for the specification.
3186
3187 @item GCRY_MD_SHA512
3188 This is the SHA-384 algorithm which yields a message digest of 64 bytes.
3189 See FIPS 180-2 for the specification.
3190
3191 @item GCRY_MD_SHA3_224
3192 This is the SHA3-224 algorithm which yields a message digest of 28 bytes.
3193 See FIPS 202 for the specification.
3194
3195 @item GCRY_MD_SHA3_256
3196 This is the SHA3-256 algorithm which yields a message digest of 32 bytes.
3197 See FIPS 202 for the specification.
3198
3199 @item GCRY_MD_SHA3_384
3200 This is the SHA3-384 algorithm which yields a message digest of 48 bytes.
3201 See FIPS 202 for the specification.
3202
3203 @item GCRY_MD_SHA3_512
3204 This is the SHA3-384 algorithm which yields a message digest of 64 bytes.
3205 See FIPS 202 for the specification.
3206
3207 @item GCRY_MD_SHAKE128
3208 This is the SHAKE128 extendable-output function (XOF) algorithm with 128 bit
3209 security strength.
3210 See FIPS 202 for the specification.
3211
3212 @item GCRY_MD_SHAKE256
3213 This is the SHAKE256 extendable-output function (XOF) algorithm with 256 bit
3214 security strength.
3215 See FIPS 202 for the specification.
3216
3217 @item GCRY_MD_CRC32
3218 This is the ISO 3309 and ITU-T V.42 cyclic redundancy check.  It yields
3219 an output of 4 bytes.  Note that this is not a hash algorithm in the
3220 cryptographic sense.
3221
3222 @item GCRY_MD_CRC32_RFC1510
3223 This is the above cyclic redundancy check function, as modified by RFC
3224 1510.  It yields an output of 4 bytes.  Note that this is not a hash
3225 algorithm in the cryptographic sense.
3226
3227 @item GCRY_MD_CRC24_RFC2440
3228 This is the OpenPGP cyclic redundancy check function.  It yields an
3229 output of 3 bytes.  Note that this is not a hash algorithm in the
3230 cryptographic sense.
3231
3232 @item GCRY_MD_WHIRLPOOL
3233 This is the Whirlpool algorithm which yields a message digest of 64
3234 bytes.
3235
3236 @item GCRY_MD_GOSTR3411_94
3237 This is the hash algorithm described in GOST R 34.11-94 which yields a
3238 message digest of 32 bytes.
3239
3240 @item GCRY_MD_STRIBOG256
3241 This is the 256-bit version of hash algorithm described in GOST R 34.11-2012
3242 which yields a message digest of 32 bytes.
3243
3244 @item GCRY_MD_STRIBOG512
3245 This is the 512-bit version of hash algorithm described in GOST R 34.11-2012
3246 which yields a message digest of 64 bytes.
3247
3248 @item GCRY_MD_BLAKE2B_512
3249 This is the BLAKE2b-512 algorithm which yields a message digest of 64 bytes.
3250 See RFC 7693 for the specification.
3251
3252 @item GCRY_MD_BLAKE2B_384
3253 This is the BLAKE2b-384 algorithm which yields a message digest of 48 bytes.
3254 See RFC 7693 for the specification.
3255
3256 @item GCRY_MD_BLAKE2B_256
3257 This is the BLAKE2b-256 algorithm which yields a message digest of 32 bytes.
3258 See RFC 7693 for the specification.
3259
3260 @item GCRY_MD_BLAKE2B_160
3261 This is the BLAKE2b-160 algorithm which yields a message digest of 20 bytes.
3262 See RFC 7693 for the specification.
3263
3264 @item GCRY_MD_BLAKE2S_256
3265 This is the BLAKE2s-256 algorithm which yields a message digest of 32 bytes.
3266 See RFC 7693 for the specification.
3267
3268 @item GCRY_MD_BLAKE2S_224
3269 This is the BLAKE2s-224 algorithm which yields a message digest of 28 bytes.
3270 See RFC 7693 for the specification.
3271
3272 @item GCRY_MD_BLAKE2S_160
3273 This is the BLAKE2s-160 algorithm which yields a message digest of 20 bytes.
3274 See RFC 7693 for the specification.
3275
3276 @item GCRY_MD_BLAKE2S_128
3277 This is the BLAKE2s-128 algorithm which yields a message digest of 16 bytes.
3278 See RFC 7693 for the specification.
3279
3280 @end table
3281 @c end table of hash algorithms
3282
3283 @node Working with hash algorithms
3284 @section Working with hash algorithms
3285
3286 To use most of these function it is necessary to create a context;
3287 this is done using:
3288
3289 @deftypefun gcry_error_t gcry_md_open (gcry_md_hd_t *@var{hd}, int @var{algo}, unsigned int @var{flags})
3290
3291 Create a message digest object for algorithm @var{algo}.  @var{flags}
3292 may be given as an bitwise OR of constants described below.  @var{algo}
3293 may be given as @code{0} if the algorithms to use are later set using
3294 @code{gcry_md_enable}. @var{hd} is guaranteed to either receive a valid
3295 handle or NULL.
3296
3297 For a list of supported algorithms, see @ref{Available hash
3298 algorithms}.
3299
3300 The flags allowed for @var{mode} are:
3301
3302 @c begin table of hash flags
3303 @table @code
3304 @item GCRY_MD_FLAG_SECURE
3305 Allocate all buffers and the resulting digest in "secure memory".  Use
3306 this is the hashed data is highly confidential.
3307
3308 @item GCRY_MD_FLAG_HMAC
3309 @cindex HMAC
3310 Turn the algorithm into a HMAC message authentication algorithm.  This
3311 only works if just one algorithm is enabled for the handle and that
3312 algorithm is not an extendable-output function.  Note that the function
3313 @code{gcry_md_setkey} must be used to set the MAC key.  The size of the
3314 MAC is equal to the message digest of the underlying hash algorithm.
3315 If you want CBC message authentication codes based on a cipher,
3316 see @ref{Working with cipher handles}.
3317
3318 @item GCRY_MD_FLAG_BUGEMU1
3319 @cindex bug emulation
3320 Versions of Libgcrypt before 1.6.0 had a bug in the Whirlpool code
3321 which led to a wrong result for certain input sizes and write
3322 patterns.  Using this flag emulates that bug.  This may for example be
3323 useful for applications which use Whirlpool as part of their key
3324 generation.  It is strongly suggested to use this flag only if really
3325 needed and if possible to the data should be re-processed using the
3326 regular Whirlpool algorithm.
3327
3328 Note that this flag works for the entire hash context.  If needed
3329 arises it may be used to enable bug emulation for other hash
3330 algorithms.  Thus you should not use this flag for a multi-algorithm
3331 hash context.
3332
3333
3334 @end table
3335 @c begin table of hash flags
3336
3337 You may use the function @code{gcry_md_is_enabled} to later check
3338 whether an algorithm has been enabled.
3339
3340 @end deftypefun
3341 @c end function gcry_md_open
3342
3343 If you want to calculate several hash algorithms at the same time, you
3344 have to use the following function right after the @code{gcry_md_open}:
3345
3346 @deftypefun gcry_error_t gcry_md_enable (gcry_md_hd_t @var{h}, int @var{algo})
3347
3348 Add the message digest algorithm @var{algo} to the digest object
3349 described by handle @var{h}.  Duplicated enabling of algorithms is
3350 detected and ignored.
3351 @end deftypefun
3352
3353 If the flag @code{GCRY_MD_FLAG_HMAC} was used, the key for the MAC must
3354 be set using the function:
3355
3356 @deftypefun gcry_error_t gcry_md_setkey (gcry_md_hd_t @var{h}, const void *@var{key}, size_t @var{keylen})
3357
3358 For use with the HMAC feature or BLAKE2 keyed hash, set the MAC key to
3359 the value of @var{key} of length @var{keylen} bytes.  For HMAC, there
3360 is no restriction on the length of the key.  For keyed BLAKE2b hash,
3361 length of the key must be 64 bytes or less.  For keyed BLAKE2s hash,
3362 length of the key must be 32 bytes or less.
3363
3364 @end deftypefun
3365
3366
3367 After you are done with the hash calculation, you should release the
3368 resources by using:
3369
3370 @deftypefun void gcry_md_close (gcry_md_hd_t @var{h})
3371
3372 Release all resources of hash context @var{h}.  @var{h} should not be
3373 used after a call to this function.  A @code{NULL} passed as @var{h} is
3374 ignored.  The function also zeroises all sensitive information
3375 associated with this handle.
3376
3377
3378 @end deftypefun
3379
3380 Often you have to do several hash operations using the same algorithm.
3381 To avoid the overhead of creating and releasing context, a reset function
3382 is provided:
3383
3384 @deftypefun void gcry_md_reset (gcry_md_hd_t @var{h})
3385
3386 Reset the current context to its initial state.  This is effectively
3387 identical to a close followed by an open and enabling all currently
3388 active algorithms.
3389 @end deftypefun
3390
3391
3392 Often it is necessary to start hashing some data and then continue to
3393 hash different data.  To avoid hashing the same data several times (which
3394 might not even be possible if the data is received from a pipe), a
3395 snapshot of the current hash context can be taken and turned into a new
3396 context:
3397
3398 @deftypefun gcry_error_t gcry_md_copy (gcry_md_hd_t *@var{handle_dst}, gcry_md_hd_t @var{handle_src})
3399
3400 Create a new digest object as an exact copy of the object described by
3401 handle @var{handle_src} and store it in @var{handle_dst}.  The context
3402 is not reset and you can continue to hash data using this context and
3403 independently using the original context.
3404 @end deftypefun
3405
3406
3407 Now that we have prepared everything to calculate hashes, it is time to
3408 see how it is actually done.  There are two ways for this, one to
3409 update the hash with a block of memory and one macro to update the hash
3410 by just one character.  Both methods can be used on the same hash context.
3411
3412 @deftypefun void gcry_md_write (gcry_md_hd_t @var{h}, const void *@var{buffer}, size_t @var{length})
3413
3414 Pass @var{length} bytes of the data in @var{buffer} to the digest object
3415 with handle @var{h} to update the digest values. This
3416 function should be used for large blocks of data.  If this function is
3417 used after the context has been finalized, it will keep on pushing
3418 the data through the algorithm specific transform function and change
3419 the context; however the results are not meaningful and this feature
3420 is only available to mitigate timing attacks.
3421 @end deftypefun
3422
3423 @deftypefun void gcry_md_putc (gcry_md_hd_t @var{h}, int @var{c})
3424
3425 Pass the byte in @var{c} to the digest object with handle @var{h} to
3426 update the digest value.  This is an efficient function, implemented as
3427 a macro to buffer the data before an actual update.
3428 @end deftypefun
3429
3430 The semantics of the hash functions do not provide for reading out intermediate
3431 message digests because the calculation must be finalized first.  This
3432 finalization may for example include the number of bytes hashed in the
3433 message digest or some padding.
3434
3435 @deftypefun void gcry_md_final (gcry_md_hd_t @var{h})
3436
3437 Finalize the message digest calculation.  This is not really needed
3438 because @code{gcry_md_read} and @code{gcry_md_extract} do this implicitly.
3439 After this has been done no further updates (by means of @code{gcry_md_write}
3440 or @code{gcry_md_putc} should be done; However, to mitigate timing
3441 attacks it is sometimes useful to keep on updating the context after
3442 having stored away the actual digest.  Only the first call to this function
3443 has an effect. It is implemented as a macro.
3444 @end deftypefun
3445
3446 The way to read out the calculated message digest is by using the
3447 function:
3448
3449 @deftypefun {unsigned char *} gcry_md_read (gcry_md_hd_t @var{h}, int @var{algo})
3450
3451 @code{gcry_md_read} returns the message digest after finalizing the
3452 calculation.  This function may be used as often as required but it will
3453 always return the same value for one handle.  The returned message digest
3454 is allocated within the message context and therefore valid until the
3455 handle is released or reset-ed (using @code{gcry_md_close} or
3456 @code{gcry_md_reset} or it has been updated as a mitigation measure
3457 against timing attacks.  @var{algo} may be given as 0 to return the only
3458 enabled message digest or it may specify one of the enabled algorithms.
3459 The function does return @code{NULL} if the requested algorithm has not
3460 been enabled.
3461 @end deftypefun
3462
3463 The way to read output of extendable-output function is by using the
3464 function:
3465
3466 @deftypefun gpg_err_code_t gcry_md_extract (gcry_md_hd_t @var{h}, @
3467   int @var{algo}, void *@var{buffer}, size_t @var{length})
3468
3469 @code{gcry_mac_read} returns output from extendable-output function.
3470 This function may be used as often as required to generate more output
3471 byte stream from the algorithm.  Function extracts the new output bytes
3472 to @var{buffer} of the length @var{length}.  Buffer will be fully
3473 populated with new output.  @var{algo} may be given as 0 to return the only
3474 enabled message digest or it may specify one of the enabled algorithms.
3475 The function does return non-zero value if the requested algorithm has not
3476 been enabled.
3477 @end deftypefun
3478
3479 Because it is often necessary to get the message digest of blocks of
3480 memory, two fast convenience function are available for this task:
3481
3482 @deftypefun gpg_err_code_t gcry_md_hash_buffers ( @
3483   @w{int @var{algo}}, @w{unsigned int @var{flags}}, @
3484   @w{void *@var{digest}}, @
3485   @w{const gcry_buffer_t *@var{iov}}, @w{int @var{iovcnt}} )
3486
3487 @code{gcry_md_hash_buffers} is a shortcut function to calculate a
3488 message digest from several buffers.  This function does not require a
3489 context and immediately returns the message digest of the data
3490 described by @var{iov} and @var{iovcnt}.  @var{digest} must be
3491 allocated by the caller, large enough to hold the message digest
3492 yielded by the the specified algorithm @var{algo}.  This required size
3493 may be obtained by using the function @code{gcry_md_get_algo_dlen}.
3494
3495 @var{iov} is an array of buffer descriptions with @var{iovcnt} items.
3496 The caller should zero out the structures in this array and for each
3497 array item set the fields @code{.data} to the address of the data to
3498 be hashed, @code{.len} to number of bytes to be hashed.  If @var{.off}
3499 is also set, the data is taken starting at @var{.off} bytes from the
3500 begin of the buffer.  The field @code{.size} is not used.
3501
3502 The only supported flag value for @var{flags} is
3503 @var{GCRY_MD_FLAG_HMAC} which turns this function into a HMAC
3504 function; the first item in @var{iov} is then used as the key.
3505
3506 On success the function returns 0 and stores the resulting hash or MAC
3507 at @var{digest}.
3508 @end deftypefun
3509
3510 @deftypefun void gcry_md_hash_buffer (int @var{algo}, void *@var{digest}, const void *@var{buffer}, size_t @var{length});
3511
3512 @code{gcry_md_hash_buffer} is a shortcut function to calculate a message
3513 digest of a buffer.  This function does not require a context and
3514 immediately returns the message digest of the @var{length} bytes at
3515 @var{buffer}.  @var{digest} must be allocated by the caller, large
3516 enough to hold the message digest yielded by the the specified algorithm
3517 @var{algo}.  This required size may be obtained by using the function
3518 @code{gcry_md_get_algo_dlen}.
3519
3520 Note that in contrast to @code{gcry_md_hash_buffers} this function
3521 will abort the process if an unavailable algorithm is used.
3522 @end deftypefun
3523
3524 @c ***********************************
3525 @c ***** MD info functions ***********
3526 @c ***********************************
3527
3528 Hash algorithms are identified by internal algorithm numbers (see
3529 @code{gcry_md_open} for a list).  However, in most applications they are
3530 used by names, so two functions are available to map between string
3531 representations and hash algorithm identifiers.
3532
3533 @deftypefun {const char *} gcry_md_algo_name (int @var{algo})
3534
3535 Map the digest algorithm id @var{algo} to a string representation of the
3536 algorithm name.  For unknown algorithms this function returns the
3537 string @code{"?"}.  This function should not be used to test for the
3538 availability of an algorithm.
3539 @end deftypefun
3540
3541 @deftypefun int gcry_md_map_name (const char *@var{name})
3542
3543 Map the algorithm with @var{name} to a digest algorithm identifier.
3544 Returns 0 if the algorithm name is not known.  Names representing
3545 @acronym{ASN.1} object identifiers are recognized if the @acronym{IETF}
3546 dotted format is used and the OID is prefixed with either "@code{oid.}"
3547 or "@code{OID.}".  For a list of supported OIDs, see the source code at
3548 @file{cipher/md.c}. This function should not be used to test for the
3549 availability of an algorithm.
3550 @end deftypefun
3551
3552 @deftypefun gcry_error_t gcry_md_get_asnoid (int @var{algo}, void *@var{buffer}, size_t *@var{length})
3553
3554 Return an DER encoded ASN.1 OID for the algorithm @var{algo} in the
3555 user allocated @var{buffer}. @var{length} must point to variable with
3556 the available size of @var{buffer} and receives after return the
3557 actual size of the returned OID.  The returned error code may be
3558 @code{GPG_ERR_TOO_SHORT} if the provided buffer is to short to receive
3559 the OID; it is possible to call the function with @code{NULL} for
3560 @var{buffer} to have it only return the required size.  The function
3561 returns 0 on success.
3562
3563 @end deftypefun
3564
3565
3566 To test whether an algorithm is actually available for use, the
3567 following macro should be used:
3568
3569 @deftypefun gcry_error_t gcry_md_test_algo (int @var{algo})
3570
3571 The macro returns 0 if the algorithm @var{algo} is available for use.
3572 @end deftypefun
3573
3574 If the length of a message digest is not known, it can be retrieved
3575 using the following function:
3576
3577 @deftypefun {unsigned int} gcry_md_get_algo_dlen (int @var{algo})
3578
3579 Retrieve the length in bytes of the digest yielded by algorithm
3580 @var{algo}.  This is often used prior to @code{gcry_md_read} to allocate
3581 sufficient memory for the digest.
3582 @end deftypefun
3583
3584
3585 In some situations it might be hard to remember the algorithm used for
3586 the ongoing hashing. The following function might be used to get that
3587 information:
3588
3589 @deftypefun int gcry_md_get_algo (gcry_md_hd_t @var{h})
3590
3591 Retrieve the algorithm used with the handle @var{h}.  Note that this
3592 does not work reliable if more than one algorithm is enabled in @var{h}.
3593 @end deftypefun
3594
3595 The following macro might also be useful:
3596
3597 @deftypefun int gcry_md_is_secure (gcry_md_hd_t @var{h})
3598
3599 This function returns true when the digest object @var{h} is allocated
3600 in "secure memory"; i.e. @var{h} was created with the
3601 @code{GCRY_MD_FLAG_SECURE}.
3602 @end deftypefun
3603
3604 @deftypefun int gcry_md_is_enabled (gcry_md_hd_t @var{h}, int @var{algo})
3605
3606 This function returns true when the algorithm @var{algo} has been
3607 enabled for the digest object @var{h}.
3608 @end deftypefun
3609
3610
3611
3612 Tracking bugs related to hashing is often a cumbersome task which
3613 requires to add a lot of printf statements into the code.
3614 Libgcrypt provides an easy way to avoid this.  The actual data
3615 hashed can be written to files on request.
3616
3617 @deftypefun void gcry_md_debug (gcry_md_hd_t @var{h}, const char *@var{suffix})
3618
3619 Enable debugging for the digest object with handle @var{h}.  This
3620 creates files named @file{dbgmd-<n>.<string>} while doing the
3621 actual hashing.  @var{suffix} is the string part in the filename.  The
3622 number is a counter incremented for each new hashing.  The data in the
3623 file is the raw data as passed to @code{gcry_md_write} or
3624 @code{gcry_md_putc}.  If @code{NULL} is used for @var{suffix}, the
3625 debugging is stopped and the file closed.  This is only rarely required
3626 because @code{gcry_md_close} implicitly stops debugging.
3627 @end deftypefun
3628
3629
3630
3631 @c **********************************************************
3632 @c *******************  MAC Functions  **********************
3633 @c **********************************************************
3634 @node Message Authentication Codes
3635 @chapter Message Authentication Codes
3636
3637 Libgcrypt provides an easy and consistent to use interface for generating
3638 Message Authentication Codes (MAC). MAC generation is buffered and interface
3639 similar to the one used with hash algorithms. The programming model follows
3640 an open/process/close paradigm and is in that similar to other building blocks
3641 provided by Libgcrypt.
3642
3643 @menu
3644 * Available MAC algorithms::   List of MAC algorithms supported by the library.
3645 * Working with MAC algorithms::  List of functions related to MAC algorithms.
3646 @end menu
3647
3648 @node Available MAC algorithms
3649 @section Available MAC algorithms
3650
3651 @c begin table of MAC algorithms
3652 @cindex HMAC-SHA-1
3653 @cindex HMAC-SHA-224, HMAC-SHA-256, HMAC-SHA-384, HMAC-SHA-512
3654 @cindex HMAC-SHA3-224, HMAC-SHA3-256, HMAC-SHA3-384, HMAC-SHA3-512
3655 @cindex HMAC-RIPE-MD-160
3656 @cindex HMAC-MD2, HMAC-MD4, HMAC-MD5
3657 @cindex HMAC-TIGER1
3658 @cindex HMAC-Whirlpool
3659 @cindex HMAC-Stribog-256, HMAC-Stribog-512
3660 @cindex HMAC-GOSTR-3411-94
3661 @table @code
3662 @item GCRY_MAC_NONE
3663 This is not a real algorithm but used by some functions as an error
3664 return value.  This constant is guaranteed to have the value @code{0}.
3665
3666 @item GCRY_MAC_HMAC_SHA256
3667 This is keyed-hash message authentication code (HMAC) message authentication
3668 algorithm based on the SHA-256 hash algorithm.
3669
3670 @item GCRY_MAC_HMAC_SHA224
3671 This is HMAC message authentication algorithm based on the SHA-224 hash
3672 algorithm.
3673
3674 @item GCRY_MAC_HMAC_SHA512
3675 This is HMAC message authentication algorithm based on the SHA-512 hash
3676 algorithm.
3677
3678 @item GCRY_MAC_HMAC_SHA384
3679 This is HMAC message authentication algorithm based on the SHA-384 hash
3680 algorithm.
3681
3682 @item GCRY_MAC_HMAC_SHA3_256
3683 This is HMAC message authentication algorithm based on the SHA3-384 hash
3684 algorithm.
3685
3686 @item GCRY_MAC_HMAC_SHA3_224
3687 This is HMAC message authentication algorithm based on the SHA3-224 hash
3688 algorithm.
3689
3690 @item GCRY_MAC_HMAC_SHA3_512
3691 This is HMAC message authentication algorithm based on the SHA3-512 hash
3692 algorithm.
3693
3694 @item GCRY_MAC_HMAC_SHA3_384
3695 This is HMAC message authentication algorithm based on the SHA3-384 hash
3696 algorithm.
3697
3698 @item GCRY_MAC_HMAC_SHA1
3699 This is HMAC message authentication algorithm based on the SHA-1 hash
3700 algorithm.
3701
3702 @item GCRY_MAC_HMAC_MD5
3703 This is HMAC message authentication algorithm based on the MD5 hash
3704 algorithm.
3705
3706 @item GCRY_MAC_HMAC_MD4
3707 This is HMAC message authentication algorithm based on the MD4 hash
3708 algorithm.
3709
3710 @item GCRY_MAC_HMAC_RMD160
3711 This is HMAC message authentication algorithm based on the RIPE-MD-160 hash
3712 algorithm.
3713
3714 @item GCRY_MAC_HMAC_WHIRLPOOL
3715 This is HMAC message authentication algorithm based on the WHIRLPOOL hash
3716 algorithm.
3717
3718 @item GCRY_MAC_HMAC_GOSTR3411_94
3719 This is HMAC message authentication algorithm based on the GOST R 34.11-94 hash
3720 algorithm.
3721
3722 @item GCRY_MAC_HMAC_STRIBOG256
3723 This is HMAC message authentication algorithm based on the 256-bit hash
3724 algorithm described in GOST R 34.11-2012.
3725
3726 @item GCRY_MAC_HMAC_STRIBOG512
3727 This is HMAC message authentication algorithm based on the 512-bit hash
3728 algorithm described in GOST R 34.11-2012.
3729
3730 @item GCRY_MAC_CMAC_AES
3731 This is CMAC (Cipher-based MAC) message authentication algorithm based on
3732 the AES block cipher algorithm.
3733
3734 @item GCRY_MAC_CMAC_3DES
3735 This is CMAC message authentication algorithm based on the three-key EDE
3736 Triple-DES block cipher algorithm.
3737
3738 @item GCRY_MAC_CMAC_CAMELLIA
3739 This is CMAC message authentication algorithm based on the Camellia block cipher
3740 algorithm.
3741
3742 @item GCRY_MAC_CMAC_CAST5
3743 This is CMAC message authentication algorithm based on the CAST128-5
3744 block cipher algorithm.
3745
3746 @item GCRY_MAC_CMAC_BLOWFISH
3747 This is CMAC message authentication algorithm based on the Blowfish
3748 block cipher algorithm.
3749
3750 @item GCRY_MAC_CMAC_TWOFISH
3751 This is CMAC message authentication algorithm based on the Twofish
3752 block cipher algorithm.
3753
3754 @item GCRY_MAC_CMAC_SERPENT
3755 This is CMAC message authentication algorithm based on the Serpent
3756 block cipher algorithm.
3757
3758 @item GCRY_MAC_CMAC_SEED
3759 This is CMAC message authentication algorithm based on the SEED
3760 block cipher algorithm.
3761
3762 @item GCRY_MAC_CMAC_RFC2268
3763 This is CMAC message authentication algorithm based on the Ron's Cipher 2
3764 block cipher algorithm.
3765
3766 @item GCRY_MAC_CMAC_IDEA
3767 This is CMAC message authentication algorithm based on the IDEA
3768 block cipher algorithm.
3769
3770 @item GCRY_MAC_CMAC_GOST28147
3771 This is CMAC message authentication algorithm based on the GOST 28147-89
3772 block cipher algorithm.
3773
3774 @item GCRY_MAC_GMAC_AES
3775 This is GMAC (GCM mode based MAC) message authentication algorithm based on
3776 the AES block cipher algorithm.
3777
3778 @item GCRY_MAC_GMAC_CAMELLIA
3779 This is GMAC message authentication algorithm based on the Camellia
3780 block cipher algorithm.
3781
3782 @item GCRY_MAC_GMAC_TWOFISH
3783 This is GMAC message authentication algorithm based on the Twofish
3784 block cipher algorithm.
3785
3786 @item GCRY_MAC_GMAC_SERPENT
3787 This is GMAC message authentication algorithm based on the Serpent
3788 block cipher algorithm.
3789
3790 @item GCRY_MAC_GMAC_SEED
3791 This is GMAC message authentication algorithm based on the SEED
3792 block cipher algorithm.
3793
3794 @item GCRY_MAC_POLY1305
3795 This is plain Poly1305 message authentication algorithm, used with
3796 one-time key.
3797
3798 @item GCRY_MAC_POLY1305_AES
3799 This is Poly1305-AES message authentication algorithm, used with
3800 key and one-time nonce.
3801
3802 @item GCRY_MAC_POLY1305_CAMELLIA
3803 This is Poly1305-Camellia message authentication algorithm, used with
3804 key and one-time nonce.
3805
3806 @item GCRY_MAC_POLY1305_TWOFISH
3807 This is Poly1305-Twofish message authentication algorithm, used with
3808 key and one-time nonce.
3809
3810 @item GCRY_MAC_POLY1305_SERPENT
3811 This is Poly1305-Serpent message authentication algorithm, used with
3812 key and one-time nonce.
3813
3814 @item GCRY_MAC_POLY1305_SEED
3815 This is Poly1305-SEED message authentication algorithm, used with
3816 key and one-time nonce.
3817
3818 @end table
3819 @c end table of MAC algorithms
3820
3821 @node Working with MAC algorithms
3822 @section Working with MAC algorithms
3823
3824 To use most of these function it is necessary to create a context;
3825 this is done using:
3826
3827 @deftypefun gcry_error_t gcry_mac_open (gcry_mac_hd_t *@var{hd}, int @var{algo}, unsigned int @var{flags}, gcry_ctx_t @var{ctx})
3828
3829 Create a MAC object for algorithm @var{algo}. @var{flags} may be given as an
3830 bitwise OR of constants described below. @var{hd} is guaranteed to either
3831 receive a valid handle or NULL. @var{ctx} is context object to associate MAC
3832 object with. @var{ctx} maybe set to NULL.
3833
3834 For a list of supported algorithms, see @ref{Available MAC algorithms}.
3835
3836 The flags allowed for @var{mode} are:
3837
3838 @c begin table of MAC flags
3839 @table @code
3840 @item GCRY_MAC_FLAG_SECURE
3841 Allocate all buffers and the resulting MAC in "secure memory".  Use this if the
3842 MAC data is highly confidential.
3843
3844 @end table
3845 @c begin table of MAC flags
3846
3847 @end deftypefun
3848 @c end function gcry_mac_open
3849
3850
3851 In order to use a handle for performing MAC algorithm operations, a
3852 `key' has to be set first:
3853
3854 @deftypefun gcry_error_t gcry_mac_setkey (gcry_mac_hd_t @var{h}, const void *@var{key}, size_t @var{keylen})
3855
3856 Set the MAC key to the value of @var{key} of length @var{keylen} bytes. With
3857 HMAC algorithms, there is no restriction on the length of the key. With CMAC
3858 algorithms, the length of the key is restricted to those supported by the
3859 underlying block cipher.
3860 @end deftypefun
3861
3862
3863 GMAC algorithms and Poly1305-with-cipher algorithms need initialization vector to be set,
3864 which can be performed with function:
3865
3866 @deftypefun gcry_error_t gcry_mac_setiv (gcry_mac_hd_t @var{h}, const void *@var{iv}, size_t @var{ivlen})
3867
3868 Set the IV to the value of @var{iv} of length @var{ivlen} bytes.
3869 @end deftypefun
3870
3871
3872 After you are done with the MAC calculation, you should release the resources
3873 by using:
3874
3875 @deftypefun void gcry_mac_close (gcry_mac_hd_t @var{h})
3876
3877 Release all resources of MAC context @var{h}.  @var{h} should not be
3878 used after a call to this function.  A @code{NULL} passed as @var{h} is
3879 ignored.  The function also clears all sensitive information associated
3880 with this handle.
3881 @end deftypefun
3882
3883
3884 Often you have to do several MAC operations using the same algorithm.
3885 To avoid the overhead of creating and releasing context, a reset function
3886 is provided:
3887
3888 @deftypefun gcry_error_t gcry_mac_reset (gcry_mac_hd_t @var{h})
3889
3890 Reset the current context to its initial state. This is effectively identical
3891 to a close followed by an open and setting same key.
3892
3893 Note that gcry_mac_reset is implemented as a macro.
3894 @end deftypefun
3895
3896
3897 Now that we have prepared everything to calculate MAC, it is time to
3898 see how it is actually done.
3899
3900 @deftypefun gcry_error_t gcry_mac_write (gcry_mac_hd_t @var{h}, const void *@var{buffer}, size_t @var{length})
3901
3902 Pass @var{length} bytes of the data in @var{buffer} to the MAC object
3903 with handle @var{h} to update the MAC values.  If this function is
3904 used after the context has been finalized, it will keep on pushing the
3905 data through the algorithm specific transform function and thereby
3906 change the context; however the results are not meaningful and this
3907 feature is only available to mitigate timing attacks.
3908 @end deftypefun
3909
3910 The way to read out the calculated MAC is by using the function:
3911
3912 @deftypefun gcry_error_t gcry_mac_read (gcry_mac_hd_t @var{h}, void *@var{buffer}, size_t *@var{length})
3913
3914 @code{gcry_mac_read} returns the MAC after finalizing the calculation.
3915 Function copies the resulting MAC value to @var{buffer} of the length
3916 @var{length}. If @var{length} is larger than length of resulting MAC value,
3917 then length of MAC is returned through @var{length}.
3918 @end deftypefun
3919
3920 To compare existing MAC value with recalculated MAC, one is to use the function:
3921
3922 @deftypefun gcry_error_t gcry_mac_verify (gcry_mac_hd_t @var{h}, void *@var{buffer}, size_t @var{length})
3923
3924 @code{gcry_mac_verify} finalizes MAC calculation and compares result with
3925 @var{length} bytes of data in @var{buffer}. Error code @code{GPG_ERR_CHECKSUM}
3926 is returned if the MAC value in the buffer @var{buffer} does not match
3927 the MAC calculated in object @var{h}.
3928 @end deftypefun
3929
3930
3931 In some situations it might be hard to remember the algorithm used for
3932 the MAC calculation. The following function might be used to get that
3933 information:
3934
3935 @deftypefun {int} gcry_mac_get_algo (gcry_mac_hd_t @var{h})
3936
3937 Retrieve the algorithm used with the handle @var{h}.
3938 @end deftypefun
3939
3940
3941 @c ***********************************
3942 @c ***** MAC info functions **********
3943 @c ***********************************
3944
3945 MAC algorithms are identified by internal algorithm numbers (see
3946 @code{gcry_mac_open} for a list).  However, in most applications they are
3947 used by names, so two functions are available to map between string
3948 representations and MAC algorithm identifiers.
3949
3950 @deftypefun {const char *} gcry_mac_algo_name (int @var{algo})
3951
3952 Map the MAC algorithm id @var{algo} to a string representation of the
3953 algorithm name.  For unknown algorithms this function returns the
3954 string @code{"?"}.  This function should not be used to test for the
3955 availability of an algorithm.
3956 @end deftypefun
3957
3958 @deftypefun int gcry_mac_map_name (const char *@var{name})
3959
3960 Map the algorithm with @var{name} to a MAC algorithm identifier.
3961 Returns 0 if the algorithm name is not known. This function should not
3962 be used to test for the availability of an algorithm.
3963 @end deftypefun
3964
3965
3966 To test whether an algorithm is actually available for use, the
3967 following macro should be used:
3968
3969 @deftypefun gcry_error_t gcry_mac_test_algo (int @var{algo})
3970
3971 The macro returns 0 if the MAC algorithm @var{algo} is available for use.
3972 @end deftypefun
3973
3974
3975 If the length of a message digest is not known, it can be retrieved
3976 using the following function:
3977
3978 @deftypefun {unsigned int} gcry_mac_get_algo_maclen (int @var{algo})
3979
3980 Retrieve the length in bytes of the MAC yielded by algorithm @var{algo}.
3981 This is often used prior to @code{gcry_mac_read} to allocate sufficient memory
3982 for the MAC value. On error @code{0} is returned.
3983 @end deftypefun
3984
3985
3986 @deftypefun {unsigned int} gcry_mac_get_algo_keylen (@var{algo})
3987
3988 This function returns length of the key for MAC algorithm @var{algo}.  If
3989 the algorithm supports multiple key lengths, the default supported key
3990 length is returned.  On error @code{0} is returned.  The key length is
3991 returned as number of octets.
3992 @end deftypefun
3993
3994
3995
3996 @c *******************************************************
3997 @c *******************  KDF  *****************************
3998 @c *******************************************************
3999 @node Key Derivation
4000 @chapter Key Derivation
4001
4002 @acronym{Libgcypt} provides a general purpose function to derive keys
4003 from strings.
4004
4005 @deftypefun gpg_error_t gcry_kdf_derive ( @
4006             @w{const void *@var{passphrase}}, @w{size_t @var{passphraselen}}, @
4007             @w{int @var{algo}}, @w{int @var{subalgo}}, @
4008             @w{const void *@var{salt}}, @w{size_t @var{saltlen}}, @
4009             @w{unsigned long @var{iterations}}, @
4010             @w{size_t @var{keysize}}, @w{void *@var{keybuffer}} )
4011
4012
4013 Derive a key from a passphrase.  @var{keysize} gives the requested
4014 size of the keys in octets.  @var{keybuffer} is a caller provided
4015 buffer filled on success with the derived key.  The input passphrase
4016 is taken from @var{passphrase} which is an arbitrary memory buffer of
4017 @var{passphraselen} octets.  @var{algo} specifies the KDF algorithm to
4018 use; see below.  @var{subalgo} specifies an algorithm used internally
4019 by the KDF algorithms; this is usually a hash algorithm but certain
4020 KDF algorithms may use it differently.  @var{salt} is a salt of length
4021 @var{saltlen} octets, as needed by most KDF algorithms.
4022 @var{iterations} is a positive integer parameter to most KDFs.
4023
4024 @noindent
4025 On success 0 is returned; on failure an error code.
4026
4027 @noindent
4028 Currently supported KDFs (parameter @var{algo}):
4029
4030 @table @code
4031 @item GCRY_KDF_SIMPLE_S2K
4032 The OpenPGP simple S2K algorithm (cf. RFC4880).  Its use is strongly
4033 deprecated.  @var{salt} and @var{iterations} are not needed and may be
4034 passed as @code{NULL}/@code{0}.
4035
4036 @item GCRY_KDF_SALTED_S2K
4037 The OpenPGP salted S2K algorithm (cf. RFC4880).  Usually not used.
4038 @var{iterations} is not needed and may be passed as @code{0}.  @var{saltlen}
4039 must be given as 8.
4040
4041 @item GCRY_KDF_ITERSALTED_S2K
4042 The OpenPGP iterated+salted S2K algorithm (cf. RFC4880).  This is the
4043 default for most OpenPGP applications.  @var{saltlen} must be given as
4044 8.  Note that OpenPGP defines a special encoding of the
4045 @var{iterations}; however this function takes the plain decoded
4046 iteration count.
4047
4048 @item GCRY_KDF_PBKDF2
4049 The PKCS#5 Passphrase Based Key Derivation Function number 2.
4050
4051 @item GCRY_KDF_SCRYPT
4052 The SCRYPT Key Derivation Function.  The subalgorithm is used to specify
4053 the CPU/memory cost parameter N, and the number of iterations
4054 is used for the parallelization parameter p.  The block size is fixed
4055 at 8 in the current implementation.
4056
4057 @end table
4058 @end deftypefun
4059
4060
4061 @c **********************************************************
4062 @c *******************  Random  *****************************
4063 @c **********************************************************
4064 @node Random Numbers
4065 @chapter Random Numbers
4066
4067 @menu
4068 * Quality of random numbers::   Libgcrypt uses different quality levels.
4069 * Retrieving random numbers::   How to retrieve random numbers.
4070 @end menu
4071
4072 @node Quality of random numbers
4073 @section Quality of random numbers
4074
4075 @acronym{Libgcypt} offers random numbers of different quality levels:
4076
4077 @deftp {Data type} gcry_random_level_t
4078 The constants for the random quality levels are of this enum type.
4079 @end deftp
4080
4081 @table @code
4082 @item GCRY_WEAK_RANDOM
4083 For all functions, except for @code{gcry_mpi_randomize}, this level maps
4084 to GCRY_STRONG_RANDOM.  If you do not want this, consider using
4085 @code{gcry_create_nonce}.
4086 @item GCRY_STRONG_RANDOM
4087 Use this level for session keys and similar purposes.
4088 @item GCRY_VERY_STRONG_RANDOM
4089 Use this level for long term key material.
4090 @end table
4091
4092 @node Retrieving random numbers
4093 @section Retrieving random numbers
4094
4095 @deftypefun void gcry_randomize (unsigned char *@var{buffer}, size_t @var{length}, enum gcry_random_level @var{level})
4096
4097 Fill @var{buffer} with @var{length} random bytes using a random quality
4098 as defined by @var{level}.
4099 @end deftypefun
4100
4101 @deftypefun {void *} gcry_random_bytes (size_t @var{nbytes}, enum gcry_random_level @var{level})
4102
4103 Convenience function to allocate a memory block consisting of
4104 @var{nbytes} fresh random bytes using a random quality as defined by
4105 @var{level}.
4106 @end deftypefun
4107
4108 @deftypefun {void *} gcry_random_bytes_secure (size_t @var{nbytes}, enum gcry_random_level @var{level})
4109
4110 Convenience function to allocate a memory block consisting of
4111 @var{nbytes} fresh random bytes using a random quality as defined by
4112 @var{level}.  This function differs from @code{gcry_random_bytes} in
4113 that the returned buffer is allocated in a ``secure'' area of the
4114 memory.
4115 @end deftypefun
4116
4117 @deftypefun void gcry_create_nonce (unsigned char *@var{buffer}, size_t @var{length})
4118
4119 Fill @var{buffer} with @var{length} unpredictable bytes.  This is
4120 commonly called a nonce and may also be used for initialization
4121 vectors and padding.  This is an extra function nearly independent of
4122 the other random function for 3 reasons: It better protects the
4123 regular random generator's internal state, provides better performance
4124 and does not drain the precious entropy pool.
4125
4126 @end deftypefun
4127
4128
4129
4130 @c **********************************************************
4131 @c *******************  S-Expressions ***********************
4132 @c **********************************************************
4133 @node S-expressions
4134 @chapter S-expressions
4135
4136 S-expressions are used by the public key functions to pass complex data
4137 structures around.  These LISP like objects are used by some
4138 cryptographic protocols (cf. RFC-2692) and Libgcrypt provides functions
4139 to parse and construct them.  For detailed information, see
4140 @cite{Ron Rivest, code and description of S-expressions,
4141 @uref{http://theory.lcs.mit.edu/~rivest/sexp.html}}.
4142
4143 @menu
4144 * Data types for S-expressions::  Data types related with S-expressions.
4145 * Working with S-expressions::  How to work with S-expressions.
4146 @end menu
4147
4148 @node Data types for S-expressions
4149 @section Data types for S-expressions
4150
4151 @deftp {Data type} gcry_sexp_t
4152 The @code{gcry_sexp_t} type describes an object with the Libgcrypt internal
4153 representation of an S-expression.
4154 @end deftp
4155
4156 @node Working with S-expressions
4157 @section Working with S-expressions
4158
4159 @noindent
4160 There are several functions to create an Libgcrypt S-expression object
4161 from its external representation or from a string template.  There is
4162 also a function to convert the internal representation back into one of
4163 the external formats:
4164
4165
4166 @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}})
4167
4168 This is the generic function to create an new S-expression object from
4169 its external representation in @var{buffer} of @var{length} bytes.  On
4170 success the result is stored at the address given by @var{r_sexp}.
4171 With @var{autodetect} set to 0, the data in @var{buffer} is expected to
4172 be in canonized format, with @var{autodetect} set to 1 the parses any of
4173 the defined external formats.  If @var{buffer} does not hold a valid
4174 S-expression an error code is returned and @var{r_sexp} set to
4175 @code{NULL}.
4176 Note that the caller is responsible for releasing the newly allocated
4177 S-expression using @code{gcry_sexp_release}.
4178 @end deftypefun
4179
4180 @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*)})
4181
4182 This function is identical to @code{gcry_sexp_new} but has an extra
4183 argument @var{freefnc}, which, when not set to @code{NULL}, is expected
4184 to be a function to release the @var{buffer}; most likely the standard
4185 @code{free} function is used for this argument.  This has the effect of
4186 transferring the ownership of @var{buffer} to the created object in
4187 @var{r_sexp}.  The advantage of using this function is that Libgcrypt
4188 might decide to directly use the provided buffer and thus avoid extra
4189 copying.
4190 @end deftypefun
4191
4192 @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}})
4193
4194 This is another variant of the above functions.  It behaves nearly
4195 identical but provides an @var{erroff} argument which will receive the
4196 offset into the buffer where the parsing stopped on error.
4197 @end deftypefun
4198
4199 @deftypefun gcry_error_t gcry_sexp_build (@w{gcry_sexp_t *@var{r_sexp}}, @w{size_t *@var{erroff}}, @w{const char *@var{format}, ...})
4200
4201 This function creates an internal S-expression from the string template
4202 @var{format} and stores it at the address of @var{r_sexp}. If there is a
4203 parsing error, the function returns an appropriate error code and stores
4204 the offset into @var{format} where the parsing stopped in @var{erroff}.
4205 The function supports a couple of printf-like formatting characters and
4206 expects arguments for some of these escape sequences right after
4207 @var{format}.  The following format characters are defined:
4208
4209 @table @samp
4210 @item %m
4211 The next argument is expected to be of type @code{gcry_mpi_t} and a copy of
4212 its value is inserted into the resulting S-expression.  The MPI is
4213 stored as a signed integer.
4214 @item %M
4215 The next argument is expected to be of type @code{gcry_mpi_t} and a copy of
4216 its value is inserted into the resulting S-expression.  The MPI is
4217 stored as an unsigned integer.
4218 @item %s
4219 The next argument is expected to be of type @code{char *} and that
4220 string is inserted into the resulting S-expression.
4221 @item %d
4222 The next argument is expected to be of type @code{int} and its value is
4223 inserted into the resulting S-expression.
4224 @item %u
4225 The next argument is expected to be of type @code{unsigned int} and
4226 its value is inserted into the resulting S-expression.
4227 @item %b
4228 The next argument is expected to be of type @code{int} directly
4229 followed by an argument of type @code{char *}.  This represents a
4230 buffer of given length to be inserted into the resulting S-expression.
4231 @item %S
4232 The next argument is expected to be of type @code{gcry_sexp_t} and a
4233 copy of that S-expression is embedded in the resulting S-expression.
4234 The argument needs to be a regular S-expression, starting with a
4235 parenthesis.
4236
4237 @end table
4238
4239 @noindent
4240 No other format characters are defined and would return an error.  Note
4241 that the format character @samp{%%} does not exists, because a percent
4242 sign is not a valid character in an S-expression.
4243 @end deftypefun
4244
4245 @deftypefun void gcry_sexp_release (@w{gcry_sexp_t @var{sexp}})
4246
4247 Release the S-expression object @var{sexp}.  If the S-expression is
4248 stored in secure memory it explicitly zeroises that memory; note that
4249 this is done in addition to the zeroisation always done when freeing
4250 secure memory.
4251 @end deftypefun
4252
4253
4254 @noindent
4255 The next 2 functions are used to convert the internal representation
4256 back into a regular external S-expression format and to show the
4257 structure for debugging.
4258
4259 @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}})
4260
4261 Copies the S-expression object @var{sexp} into @var{buffer} using the
4262 format specified in @var{mode}.  @var{maxlength} must be set to the
4263 allocated length of @var{buffer}.  The function returns the actual
4264 length of valid bytes put into @var{buffer} or 0 if the provided buffer
4265 is too short.  Passing @code{NULL} for @var{buffer} returns the required
4266 length for @var{buffer}.  For convenience reasons an extra byte with
4267 value 0 is appended to the buffer.
4268
4269 @noindent
4270 The following formats are supported:
4271
4272 @table @code
4273 @item GCRYSEXP_FMT_DEFAULT
4274 Returns a convenient external S-expression representation.
4275
4276 @item GCRYSEXP_FMT_CANON
4277 Return the S-expression in canonical format.
4278
4279 @item GCRYSEXP_FMT_BASE64
4280 Not currently supported.
4281
4282 @item GCRYSEXP_FMT_ADVANCED
4283 Returns the S-expression in advanced format.
4284 @end table
4285 @end deftypefun
4286
4287 @deftypefun void gcry_sexp_dump (@w{gcry_sexp_t @var{sexp}})
4288
4289 Dumps @var{sexp} in a format suitable for debugging to Libgcrypt's
4290 logging stream.
4291 @end deftypefun
4292
4293 @noindent
4294 Often canonical encoding is used in the external representation.  The
4295 following function can be used to check for valid encoding and to learn
4296 the length of the S-expression.
4297
4298 @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}})
4299
4300 Scan the canonical encoded @var{buffer} with implicit length values and
4301 return the actual length this S-expression uses.  For a valid S-expression
4302 it should never return 0.  If @var{length} is not 0, the maximum
4303 length to scan is given; this can be used for syntax checks of
4304 data passed from outside.  @var{errcode} and @var{erroff} may both be
4305 passed as @code{NULL}.
4306
4307 @end deftypefun
4308
4309
4310 @noindent
4311 There are functions to parse S-expressions and retrieve elements:
4312
4313 @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}})
4314
4315 Scan the S-expression for a sublist with a type (the car of the list)
4316 matching the string @var{token}.  If @var{toklen} is not 0, the token is
4317 assumed to be raw memory of this length.  The function returns a newly
4318 allocated S-expression consisting of the found sublist or @code{NULL}
4319 when not found.
4320 @end deftypefun
4321
4322
4323 @deftypefun int gcry_sexp_length (@w{const gcry_sexp_t @var{list}})
4324
4325 Return the length of the @var{list}.  For a valid S-expression this
4326 should be at least 1.
4327 @end deftypefun
4328
4329
4330 @deftypefun gcry_sexp_t gcry_sexp_nth (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}})
4331
4332 Create and return a new S-expression from the element with index @var{number} in
4333 @var{list}.  Note that the first element has the index 0.  If there is
4334 no such element, @code{NULL} is returned.
4335 @end deftypefun
4336
4337 @deftypefun gcry_sexp_t gcry_sexp_car (@w{const gcry_sexp_t @var{list}})
4338
4339 Create and return a new S-expression from the first element in
4340 @var{list}; this is called the "type" and should always exist per
4341 S-expression specification and in general be a string.  @code{NULL} is
4342 returned in case of a problem.
4343 @end deftypefun
4344
4345 @deftypefun gcry_sexp_t gcry_sexp_cdr (@w{const gcry_sexp_t @var{list}})
4346
4347 Create and return a new list form all elements except for the first one.
4348 Note that this function may return an invalid S-expression because it
4349 is not guaranteed, that the type exists and is a string.  However, for
4350 parsing a complex S-expression it might be useful for intermediate
4351 lists.  Returns @code{NULL} on error.
4352 @end deftypefun
4353
4354
4355 @deftypefun {const char *} gcry_sexp_nth_data (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{size_t *@var{datalen}})
4356
4357 This function is used to get data from a @var{list}.  A pointer to the
4358 actual data with index @var{number} is returned and the length of this
4359 data will be stored to @var{datalen}.  If there is no data at the given
4360 index or the index represents another list, @code{NULL} is returned.
4361 @strong{Caution:} The returned pointer is valid as long as @var{list} is
4362 not modified or released.
4363
4364 @noindent
4365 Here is an example on how to extract and print the surname (Meier) from
4366 the S-expression @samp{(Name Otto Meier (address Burgplatz 3))}:
4367
4368 @example
4369 size_t len;
4370 const char *name;
4371
4372 name = gcry_sexp_nth_data (list, 2, &len);
4373 printf ("my name is %.*s\n", (int)len, name);
4374 @end example
4375 @end deftypefun
4376
4377 @deftypefun {void *} gcry_sexp_nth_buffer (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{size_t *@var{rlength}})
4378
4379 This function is used to get data from a @var{list}.  A malloced
4380 buffer with the actual data at list index @var{number} is returned and
4381 the length of this buffer will be stored to @var{rlength}.  If there
4382 is no data at the given index or the index represents another list,
4383 @code{NULL} is returned.  The caller must release the result using
4384 @code{gcry_free}.
4385
4386 @noindent
4387 Here is an example on how to extract and print the CRC value from the
4388 S-expression @samp{(hash crc32 #23ed00d7)}:
4389
4390 @example
4391 size_t len;
4392 char *value;
4393
4394 value = gcry_sexp_nth_buffer (list, 2, &len);
4395 if (value)
4396   fwrite (value, len, 1, stdout);
4397 gcry_free (value);
4398 @end example
4399 @end deftypefun
4400
4401 @deftypefun {char *} gcry_sexp_nth_string (@w{gcry_sexp_t @var{list}}, @w{int @var{number}})
4402
4403 This function is used to get and convert data from a @var{list}. The
4404 data is assumed to be a Nul terminated string.  The caller must
4405 release this returned value using @code{gcry_free}.  If there is
4406 no data at the given index, the index represents a list or the value
4407 can't be converted to a string, @code{NULL} is returned.
4408 @end deftypefun
4409
4410 @deftypefun gcry_mpi_t gcry_sexp_nth_mpi (@w{gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{int @var{mpifmt}})
4411
4412 This function is used to get and convert data from a @var{list}. This
4413 data is assumed to be an MPI stored in the format described by
4414 @var{mpifmt} and returned as a standard Libgcrypt MPI.  The caller must
4415 release this returned value using @code{gcry_mpi_release}.  If there is
4416 no data at the given index, the index represents a list or the value
4417 can't be converted to an MPI, @code{NULL} is returned.  If you use
4418 this function to parse results of a public key function, you most
4419 likely want to use @code{GCRYMPI_FMT_USG}.
4420 @end deftypefun
4421
4422 @deftypefun gpg_error_t gcry_sexp_extract_param ( @
4423   @w{gcry_sexp_t @var{sexp}}, @
4424   @w{const char *@var{path}}, @
4425   @w{const char *@var{list}}, ...)
4426
4427 Extract parameters from an S-expression using a list of parameter
4428 names.  The names of these parameters are specified in LIST.  White
4429 space between the parameter names are ignored. Some special characters
4430 may be given to control the conversion:
4431
4432 @table @samp
4433 @item +
4434 Switch to unsigned integer format (GCRYMPI_FMT_USG).  This is the
4435 default mode.
4436 @item -
4437 Switch to standard signed format (GCRYMPI_FMT_STD).
4438 @item /
4439 Switch to opaque MPI format.  The resulting MPIs may not be used for
4440 computations; see @code{gcry_mpi_get_opaque} for details.
4441 @item &
4442 Switch to buffer descriptor mode.  See below for details.
4443 @item ?
4444 If immediately following a parameter letter (no white space allowed),
4445 that parameter is considered optional.
4446 @end table
4447
4448 In general parameter names are single letters.  To use a string for a
4449 parameter name, enclose the name in single quotes.
4450
4451 Unless in buffer descriptor mode for each parameter name a pointer to
4452 an @code{gcry_mpi_t} variable is expected that must be set to
4453 @code{NULL} prior to invoking this function, and finally a @code{NULL}
4454 is expected.  For example
4455
4456 @example
4457   gcry_sexp_extract_param (key, NULL, "n/x+e d-'foo'",
4458                            &mpi_n, &mpi_x, &mpi_e, &mpi_d, &mpi_foo, NULL)
4459 @end example
4460
4461 stores the parameter 'n' from @var{key} as an unsigned MPI into
4462 @var{mpi_n}, the parameter 'x' as an opaque MPI into @var{mpi_x}, the
4463 parameters 'e' and 'd' again as an unsigned MPI into @var{mpi_e} and
4464 @var{mpi_d} and finally the parameter 'foo' as a signed MPI into
4465 @var{mpi_foo}.
4466
4467 @var{path} is an optional string used to locate a token.  The
4468 exclamation mark separated tokens are used via
4469 @code{gcry_sexp_find_token} to find a start point inside the
4470 S-expression.
4471
4472 In buffer descriptor mode a pointer to a @code{gcry_buffer_t}
4473 descriptor is expected instead of a pointer to an MPI.  The caller may
4474 use two different operation modes here: If the @var{data} field of the
4475 provided descriptor is @code{NULL}, the function allocates a new
4476 buffer and stores it at @var{data}; the other fields are set
4477 accordingly with @var{off} set to 0.  If @var{data} is not
4478 @code{NULL}, the function assumes that the @var{data}, @var{size}, and
4479 @var{off} fields specify a buffer where to but the value of the
4480 respective parameter; on return the @var{len} field receives the
4481 number of bytes copied to that buffer; in case the buffer is too
4482 small, the function immediately returns with an error code (and
4483 @var{len} is set to 0).
4484
4485 The function returns 0 on success.  On error an error code is
4486 returned, all passed MPIs that might have been allocated up to this
4487 point are deallocated and set to @code{NULL}, and all passed buffers
4488 are either truncated if the caller supplied the buffer, or deallocated
4489 if the function allocated the buffer.
4490 @end deftypefun
4491
4492
4493 @c **********************************************************
4494 @c *******************  MPIs ******** ***********************
4495 @c **********************************************************
4496 @node MPI library
4497 @chapter MPI library
4498
4499 @menu
4500 * Data types::                  MPI related data types.
4501 * Basic functions::             First steps with MPI numbers.
4502 * MPI formats::                 External representation of MPIs.
4503 * Calculations::                Performing MPI calculations.
4504 * Comparisons::                 How to compare MPI values.
4505 * Bit manipulations::           How to access single bits of MPI values.
4506 * EC functions::                Elliptic curve related functions.
4507 * Miscellaneous::               Miscellaneous MPI functions.
4508 @end menu
4509
4510 Public key cryptography is based on mathematics with large numbers.  To
4511 implement the public key functions, a library for handling these large
4512 numbers is required.  Because of the general usefulness of such a
4513 library, its interface is exposed by Libgcrypt.
4514 In the context of Libgcrypt and in most other applications, these large
4515 numbers are called MPIs (multi-precision-integers).
4516
4517 @node Data types
4518 @section Data types
4519
4520 @deftp {Data type} {gcry_mpi_t}
4521 This type represents an object to hold an MPI.
4522 @end deftp
4523
4524 @deftp {Data type} {gcry_mpi_point_t}
4525 This type represents an object to hold a point for elliptic curve math.
4526 @end deftp
4527
4528 @node Basic functions
4529 @section Basic functions
4530
4531 @noindent
4532 To work with MPIs, storage must be allocated and released for the
4533 numbers.  This can be done with one of these functions:
4534
4535 @deftypefun gcry_mpi_t gcry_mpi_new (@w{unsigned int @var{nbits}})
4536
4537 Allocate a new MPI object, initialize it to 0 and initially allocate
4538 enough memory for a number of at least @var{nbits}.  This pre-allocation is
4539 only a small performance issue and not actually necessary because
4540 Libgcrypt automatically re-allocates the required memory.
4541 @end deftypefun
4542
4543 @deftypefun gcry_mpi_t gcry_mpi_snew (@w{unsigned int @var{nbits}})
4544
4545 This is identical to @code{gcry_mpi_new} but allocates the MPI in the so
4546 called "secure memory" which in turn will take care that all derived
4547 values will also be stored in this "secure memory".  Use this for highly
4548 confidential data like private key parameters.
4549 @end deftypefun
4550
4551 @deftypefun gcry_mpi_t gcry_mpi_copy (@w{const gcry_mpi_t @var{a}})
4552
4553 Create a new MPI as the exact copy of @var{a} but with the constant
4554 and immutable flags cleared.
4555 @end deftypefun
4556
4557
4558 @deftypefun void gcry_mpi_release (@w{gcry_mpi_t @var{a}})
4559
4560 Release the MPI @var{a} and free all associated resources.  Passing
4561 @code{NULL} is allowed and ignored.  When a MPI stored in the "secure
4562 memory" is released, that memory gets wiped out immediately.
4563 @end deftypefun
4564
4565 @noindent
4566 The simplest operations are used to assign a new value to an MPI:
4567
4568 @deftypefun gcry_mpi_t gcry_mpi_set (@w{gcry_mpi_t @var{w}}, @w{const gcry_mpi_t @var{u}})
4569
4570 Assign the value of @var{u} to @var{w} and return @var{w}.  If
4571 @code{NULL} is passed for @var{w}, a new MPI is allocated, set to the
4572 value of @var{u} and returned.
4573 @end deftypefun
4574
4575 @deftypefun gcry_mpi_t gcry_mpi_set_ui (@w{gcry_mpi_t @var{w}}, @w{unsigned long @var{u}})
4576
4577 Assign the value of @var{u} to @var{w} and return @var{w}.  If
4578 @code{NULL} is passed for @var{w}, a new MPI is allocated, set to the
4579 value of @var{u} and returned.  This function takes an @code{unsigned
4580 int} as type for @var{u} and thus it is only possible to set @var{w} to
4581 small values (usually up to the word size of the CPU).
4582 @end deftypefun
4583
4584 @deftypefun void gcry_mpi_swap (@w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}})
4585
4586 Swap the values of @var{a} and @var{b}.
4587 @end deftypefun
4588
4589 @deftypefun void gcry_mpi_snatch (@w{gcry_mpi_t @var{w}}, @
4590                                   @w{const gcry_mpi_t @var{u}})
4591
4592 Set @var{u} into @var{w} and release @var{u}.  If @var{w} is
4593 @code{NULL} only @var{u} will be released.
4594 @end deftypefun
4595
4596 @deftypefun void gcry_mpi_neg (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}})
4597
4598 Set the sign of @var{w} to the negative of @var{u}.
4599 @end deftypefun
4600
4601 @deftypefun void gcry_mpi_abs (@w{gcry_mpi_t @var{w}})
4602
4603 Clear the sign of @var{w}.
4604 @end deftypefun
4605
4606
4607 @node MPI formats
4608 @section MPI formats
4609
4610 @noindent
4611 The following functions are used to convert between an external
4612 representation of an MPI and the internal one of Libgcrypt.
4613
4614 @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}})
4615
4616 Convert the external representation of an integer stored in @var{buffer}
4617 with a length of @var{buflen} into a newly created MPI returned which
4618 will be stored at the address of @var{r_mpi}.  For certain formats the
4619 length argument is not required and should be passed as @code{0}. A
4620 @var{buflen} larger than 16 MiByte will be rejected.  After a
4621 successful operation the variable @var{nscanned} receives the number of
4622 bytes actually scanned unless @var{nscanned} was given as
4623 @code{NULL}. @var{format} describes the format of the MPI as stored in
4624 @var{buffer}:
4625
4626 @table @code
4627 @item GCRYMPI_FMT_STD
4628 2-complement stored without a length header.  Note that
4629 @code{gcry_mpi_print} stores a @code{0} as a string of zero length.
4630
4631 @item GCRYMPI_FMT_PGP
4632 As used by OpenPGP (only defined as unsigned). This is basically
4633 @code{GCRYMPI_FMT_STD} with a 2 byte big endian length header.
4634 A length header indicating a length of more than 16384 is not allowed.
4635
4636 @item GCRYMPI_FMT_SSH
4637 As used in the Secure Shell protocol.  This is @code{GCRYMPI_FMT_STD}
4638 with a 4 byte big endian header.
4639
4640 @item GCRYMPI_FMT_HEX
4641 Stored as a string with each byte of the MPI encoded as 2 hex digits.
4642 Negative numbers are prefix with a minus sign and in addition the
4643 high bit is always zero to make clear that an explicit sign ist used.
4644 When using this format, @var{buflen} must be zero.
4645
4646 @item GCRYMPI_FMT_USG
4647 Simple unsigned integer.
4648 @end table
4649
4650 @noindent
4651 Note that all of the above formats store the integer in big-endian
4652 format (MSB first).
4653 @end deftypefun
4654
4655
4656 @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}})
4657
4658 Convert the MPI @var{a} into an external representation described by
4659 @var{format} (see above) and store it in the provided @var{buffer}
4660 which has a usable length of at least the @var{buflen} bytes. If
4661 @var{nwritten} is not NULL, it will receive the number of bytes
4662 actually stored in @var{buffer} after a successful operation.
4663 @end deftypefun
4664
4665 @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}})
4666
4667 Convert the MPI @var{a} into an external representation described by
4668 @var{format} (see above) and store it in a newly allocated buffer which
4669 address will be stored in the variable @var{buffer} points to.  The
4670 number of bytes stored in this buffer will be stored in the variable
4671 @var{nbytes} points to, unless @var{nbytes} is @code{NULL}.
4672
4673 Even if @var{nbytes} is zero, the function allocates at least one byte
4674 and store a zero there.  Thus with formats @code{GCRYMPI_FMT_STD} and
4675 @code{GCRYMPI_FMT_USG} the caller may safely set a returned length of
4676 0 to 1 to represent a zero as a 1 byte string.
4677
4678 @end deftypefun
4679
4680 @deftypefun void gcry_mpi_dump (@w{const gcry_mpi_t @var{a}})
4681
4682 Dump the value of @var{a} in a format suitable for debugging to
4683 Libgcrypt's logging stream.  Note that one leading space but no trailing
4684 space or linefeed will be printed.  It is okay to pass @code{NULL} for
4685 @var{a}.
4686 @end deftypefun
4687
4688
4689 @node Calculations
4690 @section Calculations
4691
4692 @noindent
4693 Basic arithmetic operations:
4694
4695 @deftypefun void gcry_mpi_add (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
4696
4697 @math{@var{w} = @var{u} + @var{v}}.
4698 @end deftypefun
4699
4700
4701 @deftypefun void gcry_mpi_add_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4702
4703 @math{@var{w} = @var{u} + @var{v}}.  Note that @var{v} is an unsigned integer.
4704 @end deftypefun
4705
4706
4707 @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}})
4708
4709 @math{@var{w} = @var{u} + @var{v} \bmod @var{m}}.
4710 @end deftypefun
4711
4712 @deftypefun void gcry_mpi_sub (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
4713
4714 @math{@var{w} = @var{u} - @var{v}}.
4715 @end deftypefun
4716
4717 @deftypefun void gcry_mpi_sub_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4718
4719 @math{@var{w} = @var{u} - @var{v}}.  @var{v} is an unsigned integer.
4720 @end deftypefun
4721
4722 @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}})
4723
4724 @math{@var{w} = @var{u} - @var{v} \bmod @var{m}}.
4725 @end deftypefun
4726
4727 @deftypefun void gcry_mpi_mul (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
4728
4729 @math{@var{w} = @var{u} * @var{v}}.
4730 @end deftypefun
4731
4732 @deftypefun void gcry_mpi_mul_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4733
4734 @math{@var{w} = @var{u} * @var{v}}.  @var{v} is an unsigned integer.
4735 @end deftypefun
4736
4737 @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}})
4738
4739 @math{@var{w} = @var{u} * @var{v} \bmod @var{m}}.
4740 @end deftypefun
4741
4742 @deftypefun void gcry_mpi_mul_2exp (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{e}})
4743
4744 @c FIXME: I am in need for a real TeX{info} guru:
4745 @c I don't know why TeX can grok @var{e} here.
4746 @math{@var{w} = @var{u} * 2^e}.
4747 @end deftypefun
4748
4749 @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}})
4750
4751 @math{@var{q} = @var{dividend} / @var{divisor}}, @math{@var{r} =
4752 @var{dividend} \bmod @var{divisor}}.  @var{q} and @var{r} may be passed
4753 as @code{NULL}.  @var{round} should be negative or 0.
4754 @end deftypefun
4755
4756 @deftypefun void gcry_mpi_mod (@w{gcry_mpi_t @var{r}}, @w{gcry_mpi_t @var{dividend}}, @w{gcry_mpi_t @var{divisor}})
4757
4758 @math{@var{r} = @var{dividend} \bmod @var{divisor}}.
4759 @end deftypefun
4760
4761 @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}})
4762
4763 @c I don't know why TeX can grok @var{e} here.
4764 @math{@var{w} = @var{b}^e \bmod @var{m}}.
4765 @end deftypefun
4766
4767 @deftypefun int gcry_mpi_gcd (@w{gcry_mpi_t @var{g}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}})
4768
4769 Set @var{g} to the greatest common divisor of @var{a} and @var{b}.
4770 Return true if the @var{g} is 1.
4771 @end deftypefun
4772
4773 @deftypefun int gcry_mpi_invm (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{m}})
4774
4775 Set @var{x} to the multiplicative inverse of @math{@var{a} \bmod @var{m}}.
4776 Return true if the inverse exists.
4777 @end deftypefun
4778
4779
4780 @node Comparisons
4781 @section Comparisons
4782
4783 @noindent
4784 The next 2 functions are used to compare MPIs:
4785
4786
4787 @deftypefun int gcry_mpi_cmp (@w{const gcry_mpi_t @var{u}}, @w{const gcry_mpi_t @var{v}})
4788
4789 Compare the multi-precision-integers number @var{u} and @var{v}
4790 returning 0 for equality, a positive value for @var{u} > @var{v} and a
4791 negative for @var{u} < @var{v}.  If both numbers are opaque values
4792 (cf, gcry_mpi_set_opaque) the comparison is done by checking the bit
4793 sizes using memcmp.  If only one number is an opaque value, the opaque
4794 value is less than the other number.
4795 @end deftypefun
4796
4797 @deftypefun int gcry_mpi_cmp_ui (@w{const gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
4798
4799 Compare the multi-precision-integers number @var{u} with the unsigned
4800 integer @var{v} returning 0 for equality, a positive value for @var{u} >
4801 @var{v} and a negative for @var{u} < @var{v}.
4802 @end deftypefun
4803
4804 @deftypefun int gcry_mpi_is_neg (@w{const gcry_mpi_t @var{a}})
4805
4806 Return 1 if @var{a} is less than zero; return 0 if zero or positive.
4807 @end deftypefun
4808
4809
4810 @node Bit manipulations
4811 @section Bit manipulations
4812
4813 @noindent
4814 There are a couple of functions to get information on arbitrary bits
4815 in an MPI and to set or clear them:
4816
4817 @deftypefun {unsigned int} gcry_mpi_get_nbits (@w{gcry_mpi_t @var{a}})
4818
4819 Return the number of bits required to represent @var{a}.
4820 @end deftypefun
4821
4822 @deftypefun int gcry_mpi_test_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4823
4824 Return true if bit number @var{n} (counting from 0) is set in @var{a}.
4825 @end deftypefun
4826
4827 @deftypefun void gcry_mpi_set_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4828
4829 Set bit number @var{n} in @var{a}.
4830 @end deftypefun
4831
4832 @deftypefun void gcry_mpi_clear_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4833
4834 Clear bit number @var{n} in @var{a}.
4835 @end deftypefun
4836
4837 @deftypefun void gcry_mpi_set_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4838
4839 Set bit number @var{n} in @var{a} and clear all bits greater than @var{n}.
4840 @end deftypefun
4841
4842 @deftypefun void gcry_mpi_clear_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4843
4844 Clear bit number @var{n} in @var{a} and all bits greater than @var{n}.
4845 @end deftypefun
4846
4847 @deftypefun void gcry_mpi_rshift (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4848
4849 Shift the value of @var{a} by @var{n} bits to the right and store the
4850 result in @var{x}.
4851 @end deftypefun
4852
4853 @deftypefun void gcry_mpi_lshift (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
4854
4855 Shift the value of @var{a} by @var{n} bits to the left and store the
4856 result in @var{x}.
4857 @end deftypefun
4858
4859 @node EC functions
4860 @section EC functions
4861
4862 @noindent
4863 Libgcrypt provides an API to access low level functions used by its
4864 elliptic curve implementation.  These functions allow to implement
4865 elliptic curve methods for which no explicit support is available.
4866
4867 @deftypefun gcry_mpi_point_t gcry_mpi_point_new (@w{unsigned int @var{nbits}})
4868
4869 Allocate a new point object, initialize it to 0, and allocate enough
4870 memory for a points of at least @var{nbits}.  This pre-allocation
4871 yields only a small performance win and is not really necessary
4872 because Libgcrypt automatically re-allocates the required memory.
4873 Using 0 for @var{nbits} is usually the right thing to do.
4874 @end deftypefun
4875
4876 @deftypefun void gcry_mpi_point_release (@w{gcry_mpi_point_t @var{point}})
4877
4878 Release @var{point} and free all associated resources.  Passing
4879 @code{NULL} is allowed and ignored.
4880 @end deftypefun
4881
4882 @deftypefun gcry_mpi_point_t gcry_mpi_point_copy (@w{gcry_mpi_point_t @var{point}})
4883
4884 Allocate and return a new point object and initialize it with
4885 @var{point}.  If @var{point} is NULL the function is identical to
4886 @code{gcry_mpi_point_new(0)}.
4887 @end deftypefun
4888
4889 @deftypefun void gcry_mpi_point_get (@w{gcry_mpi_t @var{x}}, @
4890  @w{gcry_mpi_t @var{y}}, @w{gcry_mpi_t @var{z}}, @
4891  @w{gcry_mpi_point_t @var{point}})
4892
4893 Store the projective coordinates from @var{point} into the MPIs
4894 @var{x}, @var{y}, and @var{z}.  If a coordinate is not required,
4895 @code{NULL} may be used for @var{x}, @var{y}, or @var{z}.
4896 @end deftypefun
4897
4898 @deftypefun void gcry_mpi_point_snatch_get (@w{gcry_mpi_t @var{x}}, @
4899  @w{gcry_mpi_t @var{y}}, @w{gcry_mpi_t @var{z}}, @
4900  @w{gcry_mpi_point_t @var{point}})
4901
4902 Store the projective coordinates from @var{point} into the MPIs
4903 @var{x}, @var{y}, and @var{z}.  If a coordinate is not required,
4904 @code{NULL} may be used for @var{x}, @var{y}, or @var{z}.  The object
4905 @var{point} is then released.  Using this function instead of
4906 @code{gcry_mpi_point_get} and @code{gcry_mpi_point_release} has the
4907 advantage of avoiding some extra memory allocations and copies.
4908 @end deftypefun
4909
4910 @deftypefun gcry_mpi_point_t gcry_mpi_point_set ( @
4911  @w{gcry_mpi_point_t @var{point}}, @
4912  @w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{y}}, @w{gcry_mpi_t @var{z}})
4913
4914 Store the projective coordinates from @var{x}, @var{y}, and @var{z}
4915 into @var{point}.  If a coordinate is given as @code{NULL}, the value
4916 0 is used.  If @code{NULL} is used for @var{point} a new point object
4917 is allocated and returned.  Returns @var{point} or the newly allocated
4918 point object.
4919 @end deftypefun
4920
4921 @deftypefun gcry_mpi_point_t gcry_mpi_point_snatch_set ( @
4922  @w{gcry_mpi_point_t @var{point}}, @
4923  @w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{y}}, @w{gcry_mpi_t @var{z}})
4924
4925 Store the projective coordinates from @var{x}, @var{y}, and @var{z}
4926 into @var{point}.  If a coordinate is given as @code{NULL}, the value
4927 0 is used.  If @code{NULL} is used for @var{point} a new point object
4928 is allocated and returned.  The MPIs @var{x}, @var{y}, and @var{z} are
4929 released.  Using this function instead of @code{gcry_mpi_point_set}
4930 and 3 calls to @code{gcry_mpi_release} has the advantage of avoiding
4931 some extra memory allocations and copies.  Returns @var{point} or the
4932 newly allocated point object.
4933 @end deftypefun
4934
4935 @anchor{gcry_mpi_ec_new}
4936 @deftypefun gpg_error_t gcry_mpi_ec_new (@w{gcry_ctx_t *@var{r_ctx}}, @
4937  @w{gcry_sexp_t @var{keyparam}}, @w{const char *@var{curvename}})
4938
4939 Allocate a new context for elliptic curve operations.  If
4940 @var{keyparam} is given it specifies the parameters of the curve
4941 (@pxref{ecc_keyparam}).  If @var{curvename} is given in addition to
4942 @var{keyparam} and the key parameters do not include a named curve
4943 reference, the string @var{curvename} is used to fill in missing
4944 parameters.  If only @var{curvename} is given, the context is
4945 initialized for this named curve.
4946
4947 If a parameter specifying a point (e.g. @code{g} or @code{q}) is not
4948 found, the parser looks for a non-encoded point by appending
4949 @code{.x}, @code{.y}, and @code{.z} to the parameter name and looking
4950 them all up to create a point.  A parameter with the suffix @code{.z}
4951 is optional and defaults to 1.
4952
4953 On success the function returns 0 and stores the new context object at
4954 @var{r_ctx}; this object eventually needs to be released
4955 (@pxref{gcry_ctx_release}).  On error the function stores @code{NULL} at
4956 @var{r_ctx} and returns an error code.
4957 @end deftypefun
4958
4959 @deftypefun gcry_mpi_t gcry_mpi_ec_get_mpi ( @
4960  @w{const char *@var{name}}, @w{gcry_ctx_t @var{ctx}}, @w{int @var{copy}})
4961
4962 Return the MPI with @var{name} from the context @var{ctx}.  If not
4963 found @code{NULL} is returned.  If the returned MPI may later be
4964 modified, it is suggested to pass @code{1} to @var{copy}, so that the
4965 function guarantees that a modifiable copy of the MPI is returned.  If
4966 @code{0} is used for @var{copy}, this function may return a constant
4967 flagged MPI.  In any case @code{gcry_mpi_release} needs to be called
4968 to release the result.  For valid names @ref{ecc_keyparam}.  If the
4969 public key @code{q} is requested but only the private key @code{d} is
4970 available, @code{q} will be recomputed on the fly.  If a point
4971 parameter is requested it is returned as an uncompressed
4972 encoded point unless these special names are used:
4973 @table @var
4974 @item q@@eddsa
4975 Return an EdDSA style compressed point.  This is only supported for
4976 Twisted Edwards curves.
4977 @end table
4978 @end deftypefun
4979
4980 @deftypefun gcry_mpi_point_t gcry_mpi_ec_get_point ( @
4981  @w{const char *@var{name}}, @w{gcry_ctx_t @var{ctx}}, @w{int @var{copy}})
4982
4983 Return the point with @var{name} from the context @var{ctx}.  If not
4984 found @code{NULL} is returned.  If the returned MPI may later be
4985 modified, it is suggested to pass @code{1} to @var{copy}, so that the
4986 function guarantees that a modifiable copy of the MPI is returned.  If
4987 @code{0} is used for @var{copy}, this function may return a constant
4988 flagged point.  In any case @code{gcry_mpi_point_release} needs to be
4989 called to release the result.  If the public key @code{q} is requested
4990 but only the private key @code{d} is available, @code{q} will be
4991 recomputed on the fly.
4992 @end deftypefun
4993
4994 @deftypefun gpg_error_t gcry_mpi_ec_set_mpi ( @
4995  @w{const char *@var{name}}, @w{gcry_mpi_t @var{newvalue}}, @
4996  @w{gcry_ctx_t @var{ctx}})
4997
4998 Store the MPI @var{newvalue} at @var{name} into the context @var{ctx}.
4999 On success @code{0} is returned; on error an error code.  Valid names
5000 are the MPI parameters of an elliptic curve (@pxref{ecc_keyparam}).
5001 @end deftypefun
5002
5003 @deftypefun gpg_error_t gcry_mpi_ec_set_point ( @
5004  @w{const char *@var{name}}, @w{gcry_mpi_point_t @var{newvalue}}, @
5005  @w{gcry_ctx_t @var{ctx}})
5006
5007 Store the point @var{newvalue} at @var{name} into the context
5008 @var{ctx}.  On success @code{0} is returned; on error an error code.
5009 Valid names are the point parameters of an elliptic curve
5010 (@pxref{ecc_keyparam}).
5011 @end deftypefun
5012
5013 @deftypefun gpg_err_code_t gcry_mpi_ec_decode_point ( @
5014  @w{mpi_point_t @var{result}}, @w{gcry_mpi_t @var{value}}, @
5015  @w{gcry_ctx_t @var{ctx}})
5016
5017 Decode the point given as an MPI in @var{value} and store at
5018 @var{result}.  To decide which encoding is used the function takes a
5019 context @var{ctx} which can be created with @code{gcry_mpi_ec_new}.
5020 If @code{NULL} is given for the context the function assumes a 0x04
5021 prefixed uncompressed encoding.  On error an error code is returned
5022 and @var{result} might be changed.
5023 @end deftypefun
5024
5025
5026 @deftypefun int gcry_mpi_ec_get_affine ( @
5027  @w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{y}}, @
5028  @w{gcry_mpi_point_t @var{point}}, @w{gcry_ctx_t @var{ctx}})
5029
5030 Compute the affine coordinates from the projective coordinates in
5031 @var{point} and store them into @var{x} and @var{y}.  If one
5032 coordinate is not required, @code{NULL} may be passed to @var{x} or
5033 @var{y}.  @var{ctx} is the context object which has been created using
5034 @code{gcry_mpi_ec_new}. Returns 0 on success or not 0 if @var{point}
5035 is at infinity.
5036
5037 Note that you can use @code{gcry_mpi_ec_set_point} with the value
5038 @code{GCRYMPI_CONST_ONE} for @var{z} to convert affine coordinates
5039 back into projective coordinates.
5040
5041 @end deftypefun
5042
5043 @deftypefun void gcry_mpi_ec_dup ( @
5044  @w{gcry_mpi_point_t @var{w}}, @w{gcry_mpi_point_t @var{u}}, @
5045  @w{gcry_ctx_t @var{ctx}})
5046
5047 Double the point @var{u} of the elliptic curve described by @var{ctx}
5048 and store the result into @var{w}.
5049 @end deftypefun
5050
5051 @deftypefun void gcry_mpi_ec_add ( @
5052  @w{gcry_mpi_point_t @var{w}}, @w{gcry_mpi_point_t @var{u}}, @
5053  @w{gcry_mpi_point_t @var{v}}, @w{gcry_ctx_t @var{ctx}})
5054
5055 Add the points @var{u} and @var{v} of the elliptic curve described by
5056 @var{ctx} and store the result into @var{w}.
5057 @end deftypefun
5058
5059 @deftypefun void gcry_mpi_ec_sub ( @
5060  @w{gcry_mpi_point_t @var{w}}, @w{gcry_mpi_point_t @var{u}}, @
5061  @w{gcry_mpi_point_t @var{v}}, @w{gcry_ctx_t @var{ctx}})
5062
5063 Subtracts the point @var{v} from the point @var{u} of the elliptic
5064 curve described by @var{ctx} and store the result into @var{w}. Only
5065 Twisted Edwards curves are supported for now.
5066 @end deftypefun
5067
5068 @deftypefun void gcry_mpi_ec_mul ( @
5069  @w{gcry_mpi_point_t @var{w}}, @w{gcry_mpi_t @var{n}}, @
5070  @w{gcry_mpi_point_t @var{u}}, @w{gcry_ctx_t @var{ctx}})
5071
5072 Multiply the point @var{u} of the elliptic curve described by
5073 @var{ctx} by @var{n} and store the result into @var{w}.
5074 @end deftypefun
5075
5076 @deftypefun int gcry_mpi_ec_curve_point ( @
5077  @w{gcry_mpi_point_t @var{point}}, @w{gcry_ctx_t @var{ctx}})
5078
5079 Return true if @var{point} is on the elliptic curve described by
5080 @var{ctx}.
5081 @end deftypefun
5082
5083
5084 @node Miscellaneous
5085 @section Miscellaneous
5086
5087 An MPI data type is allowed to be ``misused'' to store an arbitrary
5088 value.  Two functions implement this kludge:
5089
5090 @deftypefun gcry_mpi_t gcry_mpi_set_opaque (@w{gcry_mpi_t @var{a}}, @w{void *@var{p}}, @w{unsigned int @var{nbits}})
5091
5092 Store @var{nbits} of the value @var{p} points to in @var{a} and mark
5093 @var{a} as an opaque value (i.e. an value that can't be used for any
5094 math calculation and is only used to store an arbitrary bit pattern in
5095 @var{a}).  Ownership of @var{p} is taken by this function and thus the
5096 user may not use dereference the passed value anymore.  It is required
5097 that them memory referenced by @var{p} has been allocated in a way
5098 that @code{gcry_free} is able to release it.
5099
5100 WARNING: Never use an opaque MPI for actual math operations.  The only
5101 valid functions are gcry_mpi_get_opaque and gcry_mpi_release.  Use
5102 gcry_mpi_scan to convert a string of arbitrary bytes into an MPI.
5103 @end deftypefun
5104
5105 @deftypefun gcry_mpi_t gcry_mpi_set_opaque_copy (@w{gcry_mpi_t @var{a}}, @w{const void *@var{p}}, @w{unsigned int @var{nbits}})
5106
5107 Same as @code{gcry_mpi_set_opaque} but ownership of @var{p} is not
5108 taken instead a copy of @var{p} is used.
5109 @end deftypefun
5110
5111
5112 @deftypefun {void *} gcry_mpi_get_opaque (@w{gcry_mpi_t @var{a}}, @w{unsigned int *@var{nbits}})
5113
5114 Return a pointer to an opaque value stored in @var{a} and return its
5115 size in @var{nbits}.  Note that the returned pointer is still owned by
5116 @var{a} and that the function should never be used for an non-opaque
5117 MPI.
5118 @end deftypefun
5119
5120 Each MPI has an associated set of flags for special purposes.  The
5121 currently defined flags are:
5122
5123 @table @code
5124 @item GCRYMPI_FLAG_SECURE
5125 Setting this flag converts @var{a} into an MPI stored in "secure
5126 memory".  Clearing this flag is not allowed.
5127 @item GCRYMPI_FLAG_OPAQUE
5128 This is an interanl flag, indicating the an opaque valuue and not an
5129 integer is stored.  This is an read-only flag; it may not be set or
5130 cleared.
5131 @item GCRYMPI_FLAG_IMMUTABLE
5132 If this flag is set, the MPI is marked as immutable.  Setting or
5133 changing the value of that MPI is ignored and an error message is
5134 logged.  The flag is sometimes useful for debugging.
5135 @item GCRYMPI_FLAG_CONST
5136 If this flag is set, the MPI is marked as a constant and as immutable
5137 Setting or changing the value of that MPI is ignored and an error
5138 message is logged.  Such an MPI will never be deallocated and may thus
5139 be used without copying.  Note that using gcry_mpi_copy will return a
5140 copy of that constant with this and the immutable flag cleared.  A few
5141 commonly used constants are pre-defined and accessible using the
5142 macros @code{GCRYMPI_CONST_ONE}, @code{GCRYMPI_CONST_TWO},
5143 @code{GCRYMPI_CONST_THREE}, @code{GCRYMPI_CONST_FOUR}, and
5144 @code{GCRYMPI_CONST_EIGHT}.
5145 @item GCRYMPI_FLAG_USER1
5146 @itemx GCRYMPI_FLAG_USER2
5147 @itemx GCRYMPI_FLAG_USER3
5148 @itemx GCRYMPI_FLAG_USER4
5149 These flags are reserved for use by the application.
5150 @end table
5151
5152 @deftypefun void gcry_mpi_set_flag (@w{gcry_mpi_t @var{a}}, @
5153  @w{enum gcry_mpi_flag @var{flag}})
5154
5155 Set the @var{flag} for the MPI @var{a}.  The only allowed flags are
5156 @code{GCRYMPI_FLAG_SECURE}, @code{GCRYMPI_FLAG_IMMUTABLE}, and
5157 @code{GCRYMPI_FLAG_CONST}.
5158 @end deftypefun
5159
5160 @deftypefun void gcry_mpi_clear_flag (@w{gcry_mpi_t @var{a}}, @
5161  @w{enum gcry_mpi_flag @var{flag}})
5162
5163 Clear @var{flag} for the multi-precision-integers @var{a}.  The only
5164 allowed flag is @code{GCRYMPI_FLAG_IMMUTABLE} but only if
5165 @code{GCRYMPI_FLAG_CONST} is not set.  If @code{GCRYMPI_FLAG_CONST} is
5166 set, clearing @code{GCRYMPI_FLAG_IMMUTABLE} will simply be ignored.
5167 @end deftypefun
5168 o
5169 @deftypefun int gcry_mpi_get_flag (@w{gcry_mpi_t @var{a}}, @
5170  @w{enum gcry_mpi_flag @var{flag}})
5171
5172 Return true if @var{flag} is set for @var{a}.
5173 @end deftypefun
5174
5175
5176 To put a random value into an MPI, the following convenience function
5177 may be used:
5178
5179 @deftypefun void gcry_mpi_randomize (@w{gcry_mpi_t @var{w}}, @w{unsigned int @var{nbits}}, @w{enum gcry_random_level @var{level}})
5180
5181 Set the multi-precision-integers @var{w} to a random non-negative number of
5182 @var{nbits}, using random data quality of level @var{level}.  In case
5183 @var{nbits} is not a multiple of a byte, @var{nbits} is rounded up to
5184 the next byte boundary.  When using a @var{level} of
5185 @code{GCRY_WEAK_RANDOM} this function makes use of
5186 @code{gcry_create_nonce}.
5187 @end deftypefun
5188
5189 @c **********************************************************
5190 @c ******************** Prime numbers ***********************
5191 @c **********************************************************
5192 @node Prime numbers
5193 @chapter Prime numbers
5194
5195 @menu
5196 * Generation::                  Generation of new prime numbers.
5197 * Checking::                    Checking if a given number is prime.
5198 @end menu
5199
5200 @node Generation
5201 @section Generation
5202
5203 @deftypefun gcry_error_t gcry_prime_generate (gcry_mpi_t *@var{prime},unsigned int @var{prime_bits}, unsigned int @var{factor_bits}, gcry_mpi_t **@var{factors}, gcry_prime_check_func_t @var{cb_func}, void *@var{cb_arg}, gcry_random_level_t @var{random_level}, unsigned int @var{flags})
5204
5205 Generate a new prime number of @var{prime_bits} bits and store it in
5206 @var{prime}.  If @var{factor_bits} is non-zero, one of the prime factors
5207 of (@var{prime} - 1) / 2 must be @var{factor_bits} bits long.  If
5208 @var{factors} is non-zero, allocate a new, @code{NULL}-terminated array
5209 holding the prime factors and store it in @var{factors}.  @var{flags}
5210 might be used to influence the prime number generation process.
5211 @end deftypefun
5212
5213 @deftypefun gcry_error_t gcry_prime_group_generator (gcry_mpi_t *@var{r_g}, gcry_mpi_t @var{prime}, gcry_mpi_t *@var{factors}, gcry_mpi_t @var{start_g})
5214
5215 Find a generator for @var{prime} where the factorization of
5216 (@var{prime}-1) is in the @code{NULL} terminated array @var{factors}.
5217 Return the generator as a newly allocated MPI in @var{r_g}.  If
5218 @var{start_g} is not NULL, use this as the start for the search.
5219 @end deftypefun
5220
5221 @deftypefun void gcry_prime_release_factors (gcry_mpi_t *@var{factors})
5222
5223 Convenience function to release the @var{factors} array.
5224 @end deftypefun
5225
5226 @node Checking
5227 @section Checking
5228
5229 @deftypefun gcry_error_t gcry_prime_check (gcry_mpi_t @var{p}, unsigned int @var{flags})
5230
5231 Check whether the number @var{p} is prime.  Returns zero in case @var{p}
5232 is indeed a prime, returns @code{GPG_ERR_NO_PRIME} in case @var{p} is
5233 not a prime and a different error code in case something went horribly
5234 wrong.
5235 @end deftypefun
5236
5237 @c **********************************************************
5238 @c ******************** Utilities ***************************
5239 @c **********************************************************
5240 @node Utilities
5241 @chapter Utilities
5242
5243 @menu
5244 * Memory allocation::   Functions related with memory allocation.
5245 * Context management::  Functions related with context management.
5246 * Buffer description::  A data type to describe buffers.
5247 * Config reporting::    How to return Libgcrypt's configuration.
5248 @end menu
5249
5250
5251 @node Memory allocation
5252 @section Memory allocation
5253
5254 @deftypefun {void *} gcry_malloc (size_t @var{n})
5255
5256 This function tries to allocate @var{n} bytes of memory.  On success
5257 it returns a pointer to the memory area, in an out-of-core condition,
5258 it returns NULL.
5259 @end deftypefun
5260
5261 @deftypefun {void *} gcry_malloc_secure (size_t @var{n})
5262 Like @code{gcry_malloc}, but uses secure memory.
5263 @end deftypefun
5264
5265 @deftypefun {void *} gcry_calloc (size_t @var{n}, size_t @var{m})
5266
5267 This function allocates a cleared block of memory (i.e. initialized with
5268 zero bytes) long enough to contain a vector of @var{n} elements, each of
5269 size @var{m} bytes.  On success it returns a pointer to the memory
5270 block; in an out-of-core condition, it returns NULL.
5271 @end deftypefun
5272
5273 @deftypefun {void *} gcry_calloc_secure (size_t @var{n}, size_t @var{m})
5274 Like @code{gcry_calloc}, but uses secure memory.
5275 @end deftypefun
5276
5277 @deftypefun {void *} gcry_realloc (void *@var{p}, size_t @var{n})
5278
5279 This function tries to resize the memory area pointed to by @var{p} to
5280 @var{n} bytes.  On success it returns a pointer to the new memory
5281 area, in an out-of-core condition, it returns NULL.  Depending on
5282 whether the memory pointed to by @var{p} is secure memory or not,
5283 gcry_realloc tries to use secure memory as well.
5284 @end deftypefun
5285
5286 @deftypefun void gcry_free (void *@var{p})
5287 Release the memory area pointed to by @var{p}.
5288 @end deftypefun
5289
5290
5291 @node Context management
5292 @section Context management
5293
5294 Some function make use of a context object.  As of now there are only
5295 a few math functions. However, future versions of Libgcrypt may make
5296 more use of this context object.
5297
5298 @deftp {Data type} {gcry_ctx_t}
5299 This type is used to refer to the general purpose context object.
5300 @end deftp
5301
5302 @anchor{gcry_ctx_release}
5303 @deftypefun void gcry_ctx_release (gcry_ctx_t @var{ctx})
5304 Release the context object @var{ctx} and all associated resources.  A
5305 @code{NULL} passed as @var{ctx} is ignored.
5306 @end deftypefun
5307
5308 @node Buffer description
5309 @section Buffer description
5310
5311 To help hashing non-contiguous areas of memory a general purpose data
5312 type is defined:
5313
5314 @deftp {Data type} {gcry_buffer_t}
5315 This type is a structure to describe a buffer.  The user should make
5316 sure that this structure is initialized to zero.  The available fields
5317 of this structure are:
5318
5319 @table @code
5320   @item .size
5321   This is either 0 for no information available or indicates the
5322   allocated length of the buffer.
5323   @item .off
5324   This is the offset into the buffer.
5325   @item .len
5326   This is the valid length of the buffer starting at @code{.off}.
5327   @item .data
5328   This is the address of the buffer.
5329   @end table
5330 @end deftp
5331
5332 @node Config reporting
5333 @section How to return Libgcrypt's configuration.
5334
5335 Although @code{GCRYCTL_PRINT_CONFIG} can be used to print
5336 configuration options, it is sometimes necessary to check them in a
5337 program.  This can be accomplished by using this function:
5338
5339 @deftypefun {char *} gcry_get_config @
5340              (@w{int @var{mode}}, @
5341              @w{const char *@var{what}})
5342
5343 This function returns a malloced string with colon delimited configure
5344 options.  With a value of 0 for @var{mode} this string resembles the
5345 output of @code{GCRYCTL_PRINT_CONFIG}.  However, if @var{what} is not
5346 NULL, only the line where the first field (e.g. "cpu-arch") matches
5347 @var{what} is returned.
5348
5349 Other values than 0 for @var{mode} are not defined.  The caller shall
5350 free the string using @code{gcry_free}.  On error NULL is returned and
5351 ERRNO is set; if a value for WHAT is unknow ERRNO will be set to 0.
5352 @end deftypefun
5353
5354
5355 @c **********************************************************
5356 @c *********************  Tools  ****************************
5357 @c **********************************************************
5358 @node Tools
5359 @chapter Tools
5360
5361 @menu
5362 * hmac256:: A standalone HMAC-SHA-256 implementation
5363 @end menu
5364
5365 @manpage hmac256.1
5366 @node hmac256
5367 @section A HMAC-SHA-256 tool
5368 @ifset manverb
5369 .B hmac256
5370 \- Compute an HMAC-SHA-256 MAC
5371 @end ifset
5372
5373 @mansect synopsis
5374 @ifset manverb
5375 .B  hmac256
5376 .RB [ \-\-binary ]
5377 .I key
5378 .I [FILENAME]
5379 @end ifset
5380
5381 @mansect description
5382 This is a standalone HMAC-SHA-256 implementation used to compute an
5383 HMAC-SHA-256 message authentication code.  The tool has originally
5384 been developed as a second implementation for Libgcrypt to allow
5385 comparing against the primary implementation and to be used for
5386 internal consistency checks.  It should not be used for sensitive data
5387 because no mechanisms to clear the stack etc are used.
5388
5389 The code has been written in a highly portable manner and requires
5390 only a few standard definitions to be provided in a config.h file.
5391
5392 @noindent
5393 @command{hmac256} is commonly invoked as
5394
5395 @example
5396 hmac256 "This is my key" foo.txt
5397 @end example
5398
5399 @noindent
5400 This compute the MAC on the file @file{foo.txt} using the key given on
5401 the command line.
5402
5403 @mansect options
5404 @noindent
5405 @command{hmac256} understands these options:
5406
5407 @table @gnupgtabopt
5408
5409 @item --binary
5410 Print the MAC as a binary string.  The default is to print the MAC
5411 encoded has lower case hex digits.
5412
5413 @item --version
5414 Print version of the program and exit.
5415
5416 @end table
5417
5418 @mansect see also
5419 @ifset isman
5420 @command{sha256sum}(1)
5421 @end ifset
5422 @manpause
5423
5424 @c **********************************************************
5425 @c ****************  Environment Variables  *****************
5426 @c **********************************************************
5427 @node Configuration
5428 @chapter Configuration files and environment variables
5429
5430 This chapter describes which files and environment variables can be
5431 used to change the behaviour of Libgcrypt.
5432
5433 @noindent
5434 The environment variables considered by Libgcrypt are:
5435
5436 @table @code
5437
5438 @item GCRYPT_BARRETT
5439 @cindex GCRYPT_BARRETT
5440 By setting this variable to any value a different algorithm for
5441 modular reduction is used for ECC.
5442
5443 @item GCRYPT_RNDUNIX_DBG
5444 @item GCRYPT_RNDUNIX_DBGALL
5445 @cindex GCRYPT_RNDUNIX_DBG
5446 @cindex GCRYPT_RNDUNIX_DBGALL
5447 These two environment variables are used to enable debug output for
5448 the rndunix entropy gatherer, which is used on systems lacking a
5449 /dev/random device.  The value of @code{GCRYPT_RNDUNIX_DBG} is a file
5450 name or @code{-} for stdout.  Debug output is the written to this
5451 file.  By setting @code{GCRYPT_RNDUNIX_DBGALL} to any value the debug
5452 output will be more verbose.
5453
5454 @item GCRYPT_RNDW32_NOPERF
5455 @cindex GCRYPT_RNDW32_NOPERF
5456 Setting this environment variable on Windows to any value disables
5457 the use of performance data (@code{HKEY_PERFORMANCE_DATA}) as source
5458 for entropy.  On some older Windows systems this could help to speed
5459 up the creation of random numbers but also decreases the amount of
5460 data used to init the random number generator.
5461
5462 @item GCRYPT_RNDW32_DBG
5463 @cindex GCRYPT_RNDW32_DBG
5464 Setting the value of this variable to a positive integer logs
5465 information about the Windows entropy gatherer using the standard log
5466 interface.
5467
5468
5469 @item HOME
5470 @cindex HOME
5471 This is used to locate the socket to connect to the EGD random
5472 daemon.  The EGD can be used on system without a /dev/random to speed
5473 up the random number generator.  It is not needed on the majority of
5474 today's operating systems and support for EGD requires the use of a
5475 configure option at build time.
5476
5477 @end table
5478
5479 @noindent
5480 The files which Libgcrypt uses to retrieve system information and the
5481 files which can be created by the user to modify Libgcrypt's behavior
5482 are:
5483
5484 @table @file
5485
5486 @item /etc/gcrypt/hwf.deny
5487 @cindex /etc/gcrypt/hwf.deny
5488 This file can be used to disable the use of hardware based
5489 optimizations, @pxref{hardware features}.
5490
5491
5492 @item /etc/gcrypt/random.conf
5493 @cindex /etc/gcrypt/random.conf
5494 This file can be used to globally change parameters of the random
5495 generator.  The file is a simple text file where empty lines and
5496 lines with the first non white-space character being '#' are
5497 ignored.  Supported options are
5498
5499 @table @file
5500 @item disable-jent
5501 @cindex disable-jent
5502 Disable the use of the jitter based entropy generator.
5503
5504 @item only-urandom
5505 @cindex only-urandom
5506 Always use the non-blocking /dev/urandom or the respective system call
5507 instead of the blocking /dev/random.  If Libgcrypt is used early in
5508 the boot process of the system, this option should only be used if the
5509 system also supports the getrandom system call.
5510
5511 @end table
5512
5513 @item /etc/gcrypt/fips_enabled
5514 @itemx /proc/sys/crypto/fips_enabled
5515 @cindex /etc/gcrypt/fips_enabled
5516 @cindex fips_enabled
5517 On Linux these files are used to enable FIPS mode, @pxref{enabling fips mode}.
5518
5519 @item /proc/cpuinfo
5520 @itemx /proc/self/auxv
5521 @cindex /proc/cpuinfo
5522 @cindex /proc/self/auxv
5523 On Linux running on the ARM architecture, these files are used to read
5524 hardware capabilities of the CPU.
5525
5526 @end table
5527
5528
5529 @c **********************************************************
5530 @c *****************  Architecure Overview  *****************
5531 @c **********************************************************
5532 @node Architecture
5533 @chapter Architecture
5534
5535 This chapter describes the internal architecture of Libgcrypt.
5536
5537 Libgcrypt is a function library written in ISO C-90.  Any compliant
5538 compiler should be able to build Libgcrypt as long as the target is
5539 either a POSIX platform or compatible to the API used by Windows NT.
5540 Provisions have been take so that the library can be directly used from
5541 C++ applications; however building with a C++ compiler is not supported.
5542
5543 Building Libgcrypt is done by using the common @code{./configure && make}
5544 approach.  The configure command is included in the source distribution
5545 and as a portable shell script it works on any Unix-alike system.  The
5546 result of running the configure script are a C header file
5547 (@file{config.h}), customized Makefiles, the setup of symbolic links and
5548 a few other things.  After that the make tool builds and optionally
5549 installs the library and the documentation.  See the files
5550 @file{INSTALL} and @file{README} in the source distribution on how to do
5551 this.
5552
5553 Libgcrypt is developed using a Subversion@footnote{A version control
5554 system available for many platforms} repository.  Although all released
5555 versions are tagged in this repository, they should not be used to build
5556 production versions of Libgcrypt.  Instead released tarballs should be
5557 used.  These tarballs are available from several places with the master
5558 copy at @indicateurl{ftp://ftp.gnupg.org/gcrypt/libgcrypt/}.
5559 Announcements of new releases are posted to the
5560 @indicateurl{gnupg-announce@@gnupg.org} mailing list@footnote{See
5561 @url{http://www.gnupg.org/documentation/mailing-lists.en.html} for
5562 details.}.
5563
5564
5565 @float Figure,fig:subsystems
5566 @caption{Libgcrypt subsystems}
5567 @center @image{libgcrypt-modules, 150mm,,Libgcrypt subsystems}
5568 @end float
5569
5570 Libgcrypt consists of several subsystems (@pxref{fig:subsystems}) and
5571 all these subsystems provide a public API; this includes the helper
5572 subsystems like the one for S-expressions.  The API style depends on the
5573 subsystem; in general an open-use-close approach is implemented.  The
5574 open returns a handle to a context used for all further operations on
5575 this handle, several functions may then be used on this handle and a
5576 final close function releases all resources associated with the handle.
5577
5578 @menu
5579 * Public-Key Subsystem Architecture::              About public keys.
5580 * Symmetric Encryption Subsystem Architecture::    About standard ciphers.
5581 * Hashing and MACing Subsystem Architecture::      About hashing.
5582 * Multi-Precision-Integer Subsystem Architecture:: About big integers.
5583 * Prime-Number-Generator Subsystem Architecture::  About prime numbers.
5584 * Random-Number Subsystem Architecture::           About random stuff.
5585 @c * Helper Subsystems Architecture::                 About other stuff.
5586 @end menu
5587
5588
5589
5590 @node Public-Key Subsystem Architecture
5591 @section Public-Key Architecture
5592
5593 Because public key cryptography is almost always used to process small
5594 amounts of data (hash values or session keys), the interface is not
5595 implemented using the open-use-close paradigm, but with single
5596 self-contained functions.  Due to the wide variety of parameters
5597 required by different algorithms S-expressions, as flexible way to
5598 convey these parameters, are used.  There is a set of helper functions
5599 to work with these S-expressions.
5600 @c see @ref{S-expression Subsystem Architecture}.
5601
5602 Aside of functions to register new algorithms, map algorithms names to
5603 algorithms identifiers and to lookup properties of a key, the
5604 following main functions are available:
5605
5606 @table @code
5607
5608 @item gcry_pk_encrypt
5609 Encrypt data using a public key.
5610
5611 @item gcry_pk_decrypt
5612 Decrypt data using a private key.
5613
5614 @item gcry_pk_sign
5615 Sign data using a private key.
5616
5617 @item gcry_pk_verify
5618 Verify that a signature matches the data.
5619
5620 @item gcry_pk_testkey
5621 Perform a consistency over a public or private key.
5622
5623 @item gcry_pk_genkey
5624 Create a new public/private key pair.
5625
5626 @end table
5627
5628 All these functions
5629 lookup the module implementing the algorithm and pass the actual work
5630 to that module.  The parsing of the S-expression input and the
5631 construction of S-expression for the return values is done by the high
5632 level code (@file{cipher/pubkey.c}).  Thus the internal interface
5633 between the algorithm modules and the high level functions passes data
5634 in a custom format.
5635
5636 By default Libgcrypt uses a blinding technique for RSA decryption to
5637 mitigate real world timing attacks over a network: Instead of using
5638 the RSA decryption directly, a blinded value @math{y = x r^{e} \bmod n}
5639 is decrypted and the unblinded value @math{x' = y' r^{-1} \bmod n}
5640 returned.  The blinding value @math{r} is a random value with the size
5641 of the modulus @math{n} and generated with @code{GCRY_WEAK_RANDOM}
5642 random level.
5643
5644 @cindex X9.31
5645 @cindex FIPS 186
5646 The algorithm used for RSA and DSA key generation depends on whether
5647 Libgcrypt is operated in standard or in FIPS mode.  In standard mode
5648 an algorithm based on the Lim-Lee prime number generator is used.  In
5649 FIPS mode RSA keys are generated as specified in ANSI X9.31 (1998) and
5650 DSA keys as specified in FIPS 186-2.
5651
5652
5653
5654 @node Symmetric Encryption Subsystem Architecture
5655 @section Symmetric Encryption Subsystem Architecture
5656
5657 The interface to work with symmetric encryption algorithms is made up
5658 of functions from the @code{gcry_cipher_} name space.  The
5659 implementation follows the open-use-close paradigm and uses registered
5660 algorithm modules for the actual work.  Unless a module implements
5661 optimized cipher mode implementations, the high level code
5662 (@file{cipher/cipher.c}) implements the modes and calls the core
5663 algorithm functions to process each block.
5664
5665 The most important functions are:
5666
5667 @table @code
5668
5669 @item gcry_cipher_open
5670 Create a new instance to encrypt or decrypt using a specified
5671 algorithm and mode.
5672
5673 @item gcry_cipher_close
5674 Release an instance.
5675
5676 @item gcry_cipher_setkey
5677 Set a key to be used for encryption or decryption.
5678
5679 @item gcry_cipher_setiv
5680 Set an initialization vector to be used for encryption or decryption.
5681
5682 @item gcry_cipher_encrypt
5683 @itemx gcry_cipher_decrypt
5684 Encrypt or decrypt data.  These functions may be called with arbitrary
5685 amounts of data and as often as needed to encrypt or decrypt all data.
5686
5687 @end table
5688
5689 There are also functions to query properties of algorithms or context,
5690 like block length, key length, map names or to enable features like
5691 padding methods.
5692
5693
5694
5695 @node Hashing and MACing Subsystem Architecture
5696 @section Hashing and MACing Subsystem Architecture
5697
5698 The interface to work with message digests and CRC algorithms is made
5699 up of functions from the @code{gcry_md_} name space.  The
5700 implementation follows the open-use-close paradigm and uses registered
5701 algorithm modules for the actual work.  Although CRC algorithms are
5702 not considered cryptographic hash algorithms, they share enough
5703 properties so that it makes sense to handle them in the same way.
5704 It is possible to use several algorithms at once with one context and
5705 thus compute them all on the same data.
5706
5707 The most important functions are:
5708
5709 @table @code
5710 @item gcry_md_open
5711 Create a new message digest instance and optionally enable one
5712 algorithm.  A flag may be used to turn the message digest algorithm
5713 into a HMAC algorithm.
5714
5715 @item gcry_md_enable
5716 Enable an additional algorithm for the instance.
5717
5718 @item gcry_md_setkey
5719 Set the key for the MAC.
5720
5721 @item gcry_md_write
5722 Pass more data for computing the message digest to an instance.
5723
5724 @item gcry_md_putc
5725 Buffered version of @code{gcry_md_write} implemented as a macro.
5726
5727 @item gcry_md_read
5728 Finalize the computation of the message digest or HMAC and return the
5729 result.
5730
5731 @item gcry_md_close
5732 Release an instance
5733
5734 @item gcry_md_hash_buffer
5735 Convenience function to directly compute a message digest over a
5736 memory buffer without the need to create an instance first.
5737
5738 @end table
5739
5740 There are also functions to query properties of algorithms or the
5741 instance, like enabled algorithms, digest length, map algorithm names.
5742 it is also possible to reset an instance or to copy the current state
5743 of an instance at any time.  Debug functions to write the hashed data
5744 to files are available as well.
5745
5746
5747
5748 @node Multi-Precision-Integer Subsystem Architecture
5749 @section Multi-Precision-Integer Subsystem Architecture
5750
5751 The implementation of Libgcrypt's big integer computation code is
5752 based on an old release of GNU Multi-Precision Library (GMP).  The
5753 decision not to use the GMP library directly was due to stalled
5754 development at that time and due to security requirements which could
5755 not be provided by the code in GMP.  As GMP does, Libgcrypt provides
5756 high performance assembler implementations of low level code for
5757 several CPUS to gain much better performance than with a generic C
5758 implementation.
5759
5760 @noindent
5761 Major features of Libgcrypt's multi-precision-integer code compared to
5762 GMP are:
5763
5764 @itemize
5765 @item
5766 Avoidance of stack based allocations to allow protection against
5767 swapping out of sensitive data and for easy zeroing of sensitive
5768 intermediate results.
5769
5770 @item
5771 Optional use of secure memory and tracking of its use so that results
5772 are also put into secure memory.
5773
5774 @item
5775 MPIs are identified by a handle (implemented as a pointer) to give
5776 better control over allocations and to augment them with extra
5777 properties like opaque data.
5778
5779 @item
5780 Removal of unnecessary code to reduce complexity.
5781
5782 @item
5783 Functions specialized for public key cryptography.
5784
5785 @end itemize
5786
5787
5788
5789 @node Prime-Number-Generator Subsystem Architecture
5790 @section Prime-Number-Generator Subsystem Architecture
5791
5792 Libgcrypt provides an interface to its prime number generator.  These
5793 functions make use of the internal prime number generator which is
5794 required for the generation for public key key pairs.  The plain prime
5795 checking function is exported as well.
5796
5797 The generation of random prime numbers is based on the Lim and Lee
5798 algorithm to create practically save primes.@footnote{Chae Hoon Lim
5799 and Pil Joong Lee. A key recovery attack on discrete log-based schemes
5800 using a prime order subgroup. In Burton S. Kaliski Jr., editor,
5801 Advances in Cryptology: Crypto '97, pages 249­-263, Berlin /
5802 Heidelberg / New York, 1997. Springer-Verlag.  Described on page 260.}
5803 This algorithm creates a pool of smaller primes, select a few of them
5804 to create candidate primes of the form @math{2 * p_0 * p_1 * ... * p_n
5805 + 1}, tests the candidate for primality and permutates the pool until
5806 a prime has been found.  It is possible to clamp one of the small
5807 primes to a certain size to help DSA style algorithms.  Because most
5808 of the small primes in the pool are not used for the resulting prime
5809 number, they are saved for later use (see @code{save_pool_prime} and
5810 @code{get_pool_prime} in @file{cipher/primegen.c}).  The prime
5811 generator optionally supports the finding of an appropriate generator.
5812
5813 @noindent
5814 The primality test works in three steps:
5815
5816 @enumerate
5817 @item
5818 The standard sieve algorithm using the primes up to 4999 is used as a
5819 quick first check.
5820
5821 @item
5822 A Fermat test filters out almost all non-primes.
5823
5824 @item
5825 A 5 round Rabin-Miller test is finally used.  The first round uses a
5826 witness of 2, whereas the next rounds use a random witness.
5827
5828 @end enumerate
5829
5830 To support the generation of RSA and DSA keys in FIPS mode according
5831 to X9.31 and FIPS 186-2, Libgcrypt implements two additional prime
5832 generation functions: @code{_gcry_derive_x931_prime} and
5833 @code{_gcry_generate_fips186_2_prime}.  These functions are internal
5834 and not available through the public API.
5835
5836
5837
5838 @node Random-Number Subsystem Architecture
5839 @section Random-Number Subsystem Architecture
5840
5841 Libgcrypt provides 3 levels or random quality: The level
5842 @code{GCRY_VERY_STRONG_RANDOM} usually used for key generation, the
5843 level @code{GCRY_STRONG_RANDOM} for all other strong random
5844 requirements and the function @code{gcry_create_nonce} which is used
5845 for weaker usages like nonces.  There is also a level
5846 @code{GCRY_WEAK_RANDOM} which in general maps to
5847 @code{GCRY_STRONG_RANDOM} except when used with the function
5848 @code{gcry_mpi_randomize}, where it randomizes an
5849 multi-precision-integer using the @code{gcry_create_nonce} function.
5850
5851 @noindent
5852 There are two distinct random generators available:
5853
5854 @itemize
5855 @item
5856 The Continuously Seeded Pseudo Random Number Generator (CSPRNG), which
5857 is based on the classic GnuPG derived big pool implementation.
5858 Implemented in @code{random/random-csprng.c} and used by default.
5859 @item
5860 A FIPS approved ANSI X9.31 PRNG using AES with a 128 bit key. Implemented in
5861 @code{random/random-fips.c} and used if Libgcrypt is in FIPS mode.
5862 @end itemize
5863
5864 @noindent
5865 Both generators make use of so-called entropy gathering modules:
5866
5867 @table @asis
5868 @item rndlinux
5869 Uses the operating system provided @file{/dev/random} and
5870 @file{/dev/urandom} devices.  The @file{/dev/gcrypt/random.conf}
5871 config option @option{only-urandom} can be used to inhibit the use of
5872 the blocking @file{/dev/random} device.
5873
5874 @item rndunix
5875 Runs several operating system commands to collect entropy from sources
5876 like virtual machine and process statistics.  It is a kind of
5877 poor-man's @code{/dev/random} implementation. It is not available in
5878 FIPS mode.
5879
5880 @item rndegd
5881 Uses the operating system provided Entropy Gathering Daemon (EGD).
5882 The EGD basically uses the same algorithms as rndunix does.  However
5883 as a system daemon it keeps on running and thus can serve several
5884 processes requiring entropy input and does not waste collected entropy
5885 if the application does not need all the collected entropy. It is not
5886 available in FIPS mode.
5887
5888 @item rndw32
5889 Targeted for the Microsoft Windows OS.  It uses certain properties of
5890 that system and is the only gathering module available for that OS.
5891
5892 @item rndhw
5893 Extra module to collect additional entropy by utilizing a hardware
5894 random number generator.  As of now the supported hardware RNG is
5895 the Padlock engine of VIA (Centaur) CPUs and x86 CPUs with the RDRAND
5896 instruction.  It is not available in FIPS mode.
5897
5898 @item rndjent
5899 Extra module to collect additional entropy using a CPU jitter based
5900 approach.  This is only used on X86 hardware where the RDTSC opcode is
5901 available.  The @file{/dev/gcrypt/random.conf} config option
5902 @option{disable-jent} can be used to inhibit the use of this module.
5903
5904 @end table
5905
5906
5907 @menu
5908 * CSPRNG Description::      Description of the CSPRNG.
5909 * FIPS PRNG Description::   Description of the FIPS X9.31 PRNG.
5910 @end menu
5911
5912
5913 @node CSPRNG Description
5914 @subsection Description of the CSPRNG
5915
5916 This random number generator is loosely modelled after the one
5917 described in Peter Gutmann's paper: "Software Generation of
5918 Practically Strong Random Numbers".@footnote{Also described in chapter
5919 6 of his book "Cryptographic Security Architecture", New York, 2004,
5920 ISBN 0-387-95387-6.}
5921
5922 A pool of 600 bytes is used and mixed using the core SHA-1 hash
5923 transform function.  Several extra features are used to make the
5924 robust against a wide variety of attacks and to protect against
5925 failures of subsystems.  The state of the generator may be saved to a
5926 file and initially seed form a file.
5927
5928 Depending on how Libgcrypt was build the generator is able to select
5929 the best working entropy gathering module.  It makes use of the slow
5930 and fast collection methods and requires the pool to initially seeded
5931 form the slow gatherer or a seed file.  An entropy estimation is used
5932 to mix in enough data from the gather modules before returning the
5933 actual random output.  Process fork detection and protection is
5934 implemented.
5935
5936 @c FIXME:  The design and implementation needs a more verbose description.
5937
5938 The implementation of the nonce generator (for
5939 @code{gcry_create_nonce}) is a straightforward repeated hash design: A
5940 28 byte buffer is initially seeded with the PID and the time in
5941 seconds in the first 20 bytes and with 8 bytes of random taken from
5942 the @code{GCRY_STRONG_RANDOM} generator.  Random numbers are then
5943 created by hashing all the 28 bytes with SHA-1 and saving that again
5944 in the first 20 bytes.  The hash is also returned as result.
5945
5946
5947 @node FIPS PRNG Description
5948 @subsection Description of the FIPS X9.31 PRNG
5949
5950 The core of this deterministic random number generator is implemented
5951 according to the document ``NIST-Recommended Random Number Generator
5952 Based on ANSI X9.31 Appendix A.2.4 Using the 3-Key Triple DES and AES
5953 Algorithms'', dated 2005-01-31.  This implementation uses the AES
5954 variant.
5955
5956 The generator is based on contexts to utilize the same core functions
5957 for all random levels as required by the high-level interface.  All
5958 random generators return their data in 128 bit blocks.  If the caller
5959 requests less bits, the extra bits are not used.  The key for each
5960 generator is only set once at the first time a generator context is
5961 used.  The seed value is set along with the key and again after 1000
5962 output blocks.
5963
5964 On Unix like systems the @code{GCRY_VERY_STRONG_RANDOM} and
5965 @code{GCRY_STRONG_RANDOM} generators are keyed and seeded using the
5966 rndlinux module with the @file{/dev/random} device. Thus these
5967 generators may block until the OS kernel has collected enough entropy.
5968 When used with Microsoft Windows the rndw32 module is used instead.
5969
5970 The generator used for @code{gcry_create_nonce} is keyed and seeded
5971 from the @code{GCRY_STRONG_RANDOM} generator.  Thus is may also block
5972 if the @code{GCRY_STRONG_RANDOM} generator has not yet been used
5973 before and thus gets initialized on the first use by
5974 @code{gcry_create_nonce}.  This special treatment is justified by the
5975 weaker requirements for a nonce generator and to save precious kernel
5976 entropy for use by the ``real'' random generators.
5977
5978 A self-test facility uses a separate context to check the
5979 functionality of the core X9.31 functions using a known answers test.
5980 During runtime each output block is compared to the previous one to
5981 detect a stuck generator.
5982
5983 The DT value for the generator is made up of the current time down to
5984 microseconds (if available) and a free running 64 bit counter.  When
5985 used with the test context the DT value is taken from the context and
5986 incremented on each use.
5987
5988 @c @node Helper Subsystems Architecture
5989 @c @section Helper Subsystems Architecture
5990 @c
5991 @c There are a few smaller subsystems which are mainly used internally by
5992 @c Libgcrypt but also available to applications.
5993 @c
5994 @c @menu
5995 @c * S-expression Subsystem Architecture::   Details about the S-expression architecture.
5996 @c * Memory Subsystem Architecture::         Details about the memory allocation architecture.
5997 @c * Miscellaneous Subsystems Architecture:: Details about other subsystems.
5998 @c @end menu
5999 @c
6000 @c @node S-expression Subsystem Architecture
6001 @c @subsection S-expression Subsystem Architecture
6002 @c
6003 @c Libgcrypt provides an interface to S-expression to create and parse
6004 @c them.  To use an S-expression with Libgcrypt it needs first be
6005 @c converted into the internal representation used by Libgcrypt (the type
6006 @c @code{gcry_sexp_t}).  The conversion functions support a large subset
6007 @c of the S-expression specification and further feature a printf like
6008 @c function to convert a list of big integers or other binary data into
6009 @c an S-expression.
6010 @c
6011 @c Libgcrypt currently implements S-expressions using a tagged linked
6012 @c list.  However this is not exposed to an application and may be
6013 @c changed in future releases to reduce overhead when already working
6014 @c with canonically encoded S-expressions.  Secure memory is supported by
6015 @c this S-expressions implementation.
6016 @c
6017 @c @node Memory Subsystem Architecture
6018 @c @subsection Memory Subsystem Architecture
6019 @c
6020 @c TBD.
6021 @c
6022 @c
6023 @c @node Miscellaneous Subsystems Architecture
6024 @c @subsection Miscellaneous Subsystems Architecture
6025 @c
6026 @c TBD.
6027 @c
6028 @c
6029
6030
6031
6032 @c **********************************************************
6033 @c *******************  Appendices  *************************
6034 @c **********************************************************
6035
6036 @c ********************************************
6037 @node Self-Tests
6038 @appendix Description of the Self-Tests
6039
6040 In addition to the build time regression test suite, Libgcrypt
6041 implements self-tests to be performed at runtime.  Which self-tests
6042 are actually used depends on the mode Libgcrypt is used in.  In
6043 standard mode a limited set of self-tests is run at the time an
6044 algorithm is first used.  Note that not all algorithms feature a
6045 self-test in standard mode.  The @code{GCRYCTL_SELFTEST} control
6046 command may be used to run all implemented self-tests at any time;
6047 this will even run more tests than those run in FIPS mode.
6048
6049 If any of the self-tests fails, the library immediately returns an
6050 error code to the caller.  If Libgcrypt is in FIPS mode the self-tests
6051 will be performed within the ``Self-Test'' state and any failure puts
6052 the library into the ``Error'' state.
6053
6054 @c --------------------------------
6055 @section Power-Up Tests
6056
6057 Power-up tests are only performed if Libgcrypt is in FIPS mode.
6058
6059 @subsection Symmetric Cipher Algorithm Power-Up Tests
6060
6061 The following symmetric encryption algorithm tests are run during
6062 power-up:
6063
6064 @table @asis
6065 @item 3DES
6066 To test the 3DES 3-key EDE encryption in ECB mode these tests are
6067 run:
6068 @enumerate
6069 @item
6070 A known answer test is run on a 64 bit test vector processed by 64
6071 rounds of Single-DES block encryption and decryption using a key
6072 changed with each round.
6073 @item
6074 A known answer test is run on a 64 bit test vector processed by 16
6075 rounds of 2-key and 3-key Triple-DES block encryption and decryptions
6076 using a key changed with each round.
6077 @item
6078 10 known answer tests using 3-key Triple-DES EDE encryption, comparing
6079 the ciphertext to the known value, then running a decryption and
6080 comparing it to the initial plaintext.
6081 @end enumerate
6082 (@code{cipher/des.c:selftest})
6083
6084 @item AES-128
6085 A known answer tests is run using one test vector and one test
6086 key with AES in ECB mode. (@code{cipher/rijndael.c:selftest_basic_128})
6087
6088 @item AES-192
6089 A known answer tests is run using one test vector and one test
6090 key with AES in ECB mode. (@code{cipher/rijndael.c:selftest_basic_192})
6091
6092 @item AES-256
6093 A known answer tests is run using one test vector and one test key
6094 with AES in ECB mode. (@code{cipher/rijndael.c:selftest_basic_256})
6095 @end table
6096
6097 @subsection Hash Algorithm Power-Up Tests
6098
6099 The following hash algorithm tests are run during power-up:
6100
6101 @table @asis
6102 @item SHA-1
6103 A known answer test using the string @code{"abc"} is run.
6104 (@code{cipher/@/sha1.c:@/selftests_sha1})
6105 @item SHA-224
6106 A known answer test using the string @code{"abc"} is run.
6107 (@code{cipher/@/sha256.c:@/selftests_sha224})
6108 @item SHA-256
6109 A known answer test using the string @code{"abc"} is run.
6110 (@code{cipher/@/sha256.c:@/selftests_sha256})
6111 @item SHA-384
6112 A known answer test using the string @code{"abc"} is run.
6113 (@code{cipher/@/sha512.c:@/selftests_sha384})
6114 @item SHA-512
6115 A known answer test using the string @code{"abc"} is run.
6116 (@code{cipher/@/sha512.c:@/selftests_sha512})
6117 @end table
6118
6119 @subsection MAC Algorithm Power-Up Tests
6120
6121 The following MAC algorithm tests are run during power-up:
6122
6123 @table @asis
6124 @item HMAC SHA-1
6125 A known answer test using 9 byte of data and a 64 byte key is run.
6126 (@code{cipher/hmac-tests.c:selftests_sha1})
6127 @item HMAC SHA-224
6128 A known answer test using 28 byte of data and a 4 byte key is run.
6129 (@code{cipher/hmac-tests.c:selftests_sha224})
6130 @item HMAC SHA-256
6131 A known answer test using 28 byte of data and a 4 byte key is run.
6132 (@code{cipher/hmac-tests.c:selftests_sha256})
6133 @item HMAC SHA-384
6134 A known answer test using 28 byte of data and a 4 byte key is run.
6135 (@code{cipher/hmac-tests.c:selftests_sha384})
6136 @item HMAC SHA-512
6137 A known answer test using 28 byte of data and a 4 byte key is run.
6138 (@code{cipher/hmac-tests.c:selftests_sha512})
6139 @end table
6140
6141 @subsection Random Number Power-Up Test
6142
6143 The DRNG is tested during power-up this way:
6144
6145 @enumerate
6146 @item
6147 Requesting one block of random using the public interface to check
6148 general working and the duplicated block detection.
6149 @item
6150 3 know answer tests using pre-defined keys, seed and initial DT
6151 values.  For each test 3 blocks of 16 bytes are requested and compared
6152 to the expected result.  The DT value is incremented for each block.
6153 @end enumerate
6154
6155 @subsection Public Key Algorithm Power-Up Tests
6156
6157 The public key algorithms are tested during power-up:
6158
6159 @table @asis
6160 @item RSA
6161 A pre-defined 1024 bit RSA key is used and these tests are run
6162 in turn:
6163 @enumerate
6164 @item
6165 Conversion of S-expression to internal format.
6166 (@code{cipher/@/rsa.c:@/selftests_rsa})
6167 @item
6168 Private key consistency check.
6169 (@code{cipher/@/rsa.c:@/selftests_rsa})
6170 @item
6171 A pre-defined 20 byte value is signed with PKCS#1 padding for SHA-1.
6172 The result is verified using the public key against the original data
6173 and against modified data.  (@code{cipher/@/rsa.c:@/selftest_sign_1024})
6174 @item
6175 A 1000 bit random value is encrypted and checked that it does not
6176 match the original random value.  The encrypted result is then
6177 decrypted and checked that it matches the original random value.
6178 (@code{cipher/@/rsa.c:@/selftest_encr_1024})
6179 @end enumerate
6180
6181 @item DSA
6182 A pre-defined 1024 bit DSA key is used and these tests are run in turn:
6183 @enumerate
6184 @item
6185 Conversion of S-expression to internal format.
6186 (@code{cipher/@/dsa.c:@/selftests_dsa})
6187 @item
6188 Private key consistency check.
6189 (@code{cipher/@/dsa.c:@/selftests_dsa})
6190 @item
6191 A pre-defined 20 byte value is signed with PKCS#1 padding for
6192 SHA-1.  The result is verified using the public key against the
6193 original data and against modified data.
6194 (@code{cipher/@/dsa.c:@/selftest_sign_1024})
6195 @end enumerate
6196 @end table
6197
6198 @subsection Integrity Power-Up Tests
6199
6200 The integrity of the Libgcrypt is tested during power-up but only if
6201 checking has been enabled at build time.  The check works by computing
6202 a HMAC SHA-256 checksum over the file used to load Libgcrypt into
6203 memory.  That checksum is compared against a checksum stored in a file
6204 of the same name but with a single dot as a prefix and a suffix of
6205 @file{.hmac}.
6206
6207
6208 @subsection Critical Functions Power-Up Tests
6209
6210 The 3DES weak key detection is tested during power-up by calling the
6211 detection function with keys taken from a table listening all weak
6212 keys.  The table itself is protected using a SHA-1 hash.
6213 (@code{cipher/@/des.c:@/selftest})
6214
6215
6216
6217 @c --------------------------------
6218 @section Conditional Tests
6219
6220 The conditional tests are performed if a certain condition is met.
6221 This may occur at any time; the library does not necessary enter the
6222 ``Self-Test'' state to run these tests but will transit to the
6223 ``Error'' state if a test failed.
6224
6225 @subsection Key-Pair Generation Tests
6226
6227 After an asymmetric key-pair has been generated, Libgcrypt runs a
6228 pair-wise consistency tests on the generated key.  On failure the
6229 generated key is not used, an error code is returned and, if in FIPS
6230 mode, the library is put into the ``Error'' state.
6231
6232 @table @asis
6233 @item RSA
6234 The test uses a random number 64 bits less the size of the modulus as
6235 plaintext and runs an encryption and decryption operation in turn.  The
6236 encrypted value is checked to not match the plaintext and the result
6237 of the decryption is checked to match the plaintext.
6238
6239 A new random number of the same size is generated, signed and verified
6240 to test the correctness of the signing operation.  As a second signing
6241 test, the signature is modified by incrementing its value and then
6242 verified with the expected result that the verification fails.
6243 (@code{cipher/@/rsa.c:@/test_keys})
6244 @item DSA
6245 The test uses a random number of the size of the Q parameter to create
6246 a signature and then checks that the signature verifies.  As a second
6247 signing test, the data is modified by incrementing its value and then
6248 verified against the signature with the expected result that the
6249 verification fails.  (@code{cipher/@/dsa.c:@/test_keys})
6250 @end table
6251
6252
6253 @subsection Software Load Tests
6254
6255 No code is loaded at runtime.
6256
6257 @subsection Manual Key Entry Tests
6258
6259 A manual key entry feature is not implemented in Libgcrypt.
6260
6261
6262 @subsection Continuous RNG Tests
6263
6264 The continuous random number test is only used in FIPS mode.  The RNG
6265 generates blocks of 128 bit size; the first block generated per
6266 context is saved in the context and another block is generated to be
6267 returned to the caller.  Each block is compared against the saved
6268 block and then stored in the context.  If a duplicated block is
6269 detected an error is signaled and the library is put into the
6270 ``Fatal-Error'' state.
6271 (@code{random/@/random-fips.c:@/x931_aes_driver})
6272
6273
6274
6275 @c --------------------------------
6276 @section Application Requested Tests
6277
6278 The application may requests tests at any time by means of the
6279 @code{GCRYCTL_SELFTEST} control command.  Note that using these tests
6280 is not FIPS conform: Although Libgcrypt rejects all application
6281 requests for services while running self-tests, it does not ensure
6282 that no other operations of Libgcrypt are still being executed.  Thus,
6283 in FIPS mode an application requesting self-tests needs to power-cycle
6284 Libgcrypt instead.
6285
6286 When self-tests are requested, Libgcrypt runs all the tests it does
6287 during power-up as well as a few extra checks as described below.
6288
6289 @subsection Symmetric Cipher Algorithm Tests
6290
6291 The following symmetric encryption algorithm tests are run in addition
6292 to the power-up tests:
6293
6294 @table @asis
6295 @item AES-128
6296 A known answer tests with test vectors taken from NIST SP800-38a and
6297 using the high level functions is run for block modes CFB and OFB.
6298
6299 @end table
6300
6301 @subsection Hash Algorithm Tests
6302
6303 The following hash algorithm tests are run in addition to the
6304 power-up tests:
6305
6306 @table @asis
6307 @item SHA-1
6308 @itemx SHA-224
6309 @itemx SHA-256
6310 @enumerate
6311 @item
6312 A known answer test using a 56 byte string is run.
6313 @item
6314 A known answer test using a string of one million letters "a" is run.
6315 @end enumerate
6316 (@code{cipher/@/sha1.c:@/selftests_sha1},
6317 @code{cipher/@/sha256.c:@/selftests_sha224},
6318 @code{cipher/@/sha256.c:@/selftests_sha256})
6319 @item SHA-384
6320 @item SHA-512
6321 @enumerate
6322 @item
6323 A known answer test using a 112 byte string is run.
6324 @item
6325 A known answer test using a string of one million letters "a" is run.
6326 @end enumerate
6327 (@code{cipher/@/sha512.c:@/selftests_sha384},
6328 @code{cipher/@/sha512.c:@/selftests_sha512})
6329 @end table
6330
6331 @subsection MAC Algorithm Tests
6332
6333 The following MAC algorithm tests are run in addition to the power-up
6334 tests:
6335
6336 @table @asis
6337 @item HMAC SHA-1
6338 @enumerate
6339 @item
6340 A known answer test using 9 byte of data and a 20 byte key is run.
6341 @item
6342 A known answer test using 9 byte of data and a 100 byte key is run.
6343 @item
6344 A known answer test using 9 byte of data and a 49 byte key is run.
6345 @end enumerate
6346 (@code{cipher/hmac-tests.c:selftests_sha1})
6347 @item HMAC SHA-224
6348 @itemx HMAC SHA-256
6349 @itemx HMAC SHA-384
6350 @itemx HMAC SHA-512
6351 @enumerate
6352 @item
6353 A known answer test using 9 byte of data and a 20 byte key is run.
6354 @item
6355 A known answer test using 50 byte of data and a 20 byte key is run.
6356 @item
6357 A known answer test using 50 byte of data and a 26 byte key is run.
6358 @item
6359 A known answer test using 54 byte of data and a 131 byte key is run.
6360 @item
6361 A known answer test using 152 byte of data and a 131 byte key is run.
6362 @end enumerate
6363 (@code{cipher/@/hmac-tests.c:@/selftests_sha224},
6364 @code{cipher/@/hmac-tests.c:@/selftests_sha256},
6365 @code{cipher/@/hmac-tests.c:@/selftests_sha384},
6366 @code{cipher/@/hmac-tests.c:@/selftests_sha512})
6367 @end table
6368
6369
6370 @c ********************************************
6371 @node FIPS Mode
6372 @appendix Description of the FIPS Mode
6373
6374 This appendix gives detailed information pertaining to the FIPS mode.
6375 In particular, the changes to the standard mode and the finite state
6376 machine are described.  The self-tests required in this mode are
6377 described in the appendix on self-tests.
6378
6379 @c -------------------------------
6380 @section Restrictions in FIPS Mode
6381
6382 @noindent
6383 If Libgcrypt is used in FIPS mode these restrictions are effective:
6384
6385 @itemize
6386 @item
6387 The cryptographic algorithms are restricted to this list:
6388
6389 @table @asis
6390 @item GCRY_CIPHER_3DES
6391 3 key EDE Triple-DES symmetric encryption.
6392 @item GCRY_CIPHER_AES128
6393 AES 128 bit symmetric encryption.
6394 @item GCRY_CIPHER_AES192
6395 AES 192 bit symmetric encryption.
6396 @item GCRY_CIPHER_AES256
6397 AES 256 bit symmetric encryption.
6398 @item GCRY_MD_SHA1
6399 SHA-1 message digest.
6400 @item GCRY_MD_SHA224
6401 SHA-224 message digest.
6402 @item GCRY_MD_SHA256
6403 SHA-256 message digest.
6404 @item GCRY_MD_SHA384
6405 SHA-384 message digest.
6406 @item GCRY_MD_SHA512
6407 SHA-512 message digest.
6408 @item GCRY_MD_SHA1,GCRY_MD_FLAG_HMAC
6409 HMAC using a SHA-1 message digest.
6410 @item GCRY_MD_SHA224,GCRY_MD_FLAG_HMAC
6411 HMAC using a SHA-224 message digest.
6412 @item GCRY_MD_SHA256,GCRY_MD_FLAG_HMAC
6413 HMAC using a SHA-256 message digest.
6414 @item GCRY_MD_SHA384,GCRY_MD_FLAG_HMAC
6415 HMAC using a SHA-384 message digest.
6416 @item GCRY_MD_SHA512,GCRY_MD_FLAG_HMAC
6417 HMAC using a SHA-512 message digest.
6418 @item GCRY_PK_RSA
6419 RSA encryption and signing.
6420 @item GCRY_PK_DSA
6421 DSA signing.
6422 @end table
6423
6424 Note that the CRC algorithms are not considered cryptographic algorithms
6425 and thus are in addition available.
6426
6427 @item
6428 RSA key generation refuses to create a key with a keysize of
6429 less than 1024 bits.
6430
6431 @item
6432 DSA key generation refuses to create a key with a keysize other
6433 than 1024 bits.
6434
6435 @item
6436 The @code{transient-key} flag for RSA and DSA key generation is ignored.
6437
6438 @item
6439 Support for the VIA Padlock engine is disabled.
6440
6441 @item
6442 FIPS mode may only be used on systems with a /dev/random device.
6443 Switching into FIPS mode on other systems will fail at runtime.
6444
6445 @item
6446 Saving and loading a random seed file is ignored.
6447
6448 @item
6449 An X9.31 style random number generator is used in place of the
6450 large-pool-CSPRNG generator.
6451
6452 @item
6453 The command @code{GCRYCTL_ENABLE_QUICK_RANDOM} is ignored.
6454
6455 @item
6456 Message digest debugging is disabled.
6457
6458 @item
6459 All debug output related to cryptographic data is suppressed.
6460
6461 @item
6462 On-the-fly self-tests are not performed, instead self-tests are run
6463 before entering operational state.
6464
6465 @item
6466 The function @code{gcry_set_allocation_handler} may not be used.  If
6467 it is used Libgcrypt disables FIPS mode unless Enforced FIPS mode is
6468 enabled, in which case Libgcrypt will enter the error state.
6469
6470 @item
6471 The digest algorithm MD5 may not be used.  If it is used Libgcrypt
6472 disables FIPS mode unless Enforced FIPS mode is enabled, in which case
6473 Libgcrypt will enter the error state.
6474
6475 @item
6476 In Enforced FIPS mode the command @code{GCRYCTL_DISABLE_SECMEM} is
6477 ignored.  In standard FIPS mode it disables FIPS mode.
6478
6479 @item
6480 A handler set by @code{gcry_set_outofcore_handler} is ignored.
6481 @item
6482 A handler set by @code{gcry_set_fatalerror_handler} is ignored.
6483
6484 @end itemize
6485
6486 Note that when we speak about disabling FIPS mode, it merely means
6487 that the function @code{gcry_fips_mode_active} returns false; it does
6488 not mean that any non FIPS algorithms are allowed.
6489
6490 @c ********************************************
6491 @section FIPS Finite State Machine
6492
6493 The FIPS mode of libgcrypt implements a finite state machine (FSM) using
6494 8 states (@pxref{tbl:fips-states}) and checks at runtime that only valid
6495 transitions (@pxref{tbl:fips-state-transitions}) may happen.
6496
6497 @float Figure,fig:fips-fsm
6498 @caption{FIPS mode state diagram}
6499 @center @image{fips-fsm,150mm,,FIPS FSM Diagram}
6500 @end float
6501
6502 @float Table,tbl:fips-states
6503 @caption{FIPS mode states}
6504 @noindent
6505 States used by the FIPS FSM:
6506 @table @asis
6507
6508 @item Power-Off
6509 Libgcrypt is not runtime linked to another application.  This usually
6510 means that the library is not loaded into main memory.  This state is
6511 documentation only.
6512
6513 @item Power-On
6514 Libgcrypt is loaded into memory and API calls may be made.  Compiler
6515 introduced constructor functions may be run.  Note that Libgcrypt does
6516 not implement any arbitrary constructor functions to be called by the
6517 operating system
6518
6519 @item Init
6520 The Libgcrypt initialization functions are performed and the library has
6521 not yet run any self-test.
6522
6523 @item Self-Test
6524 Libgcrypt is performing self-tests.
6525
6526 @item Operational
6527 Libgcrypt is in the operational state and all interfaces may be used.
6528
6529 @item Error
6530 Libgrypt is in the error state.  When calling any FIPS relevant
6531 interfaces they either return an error (@code{GPG_ERR_NOT_OPERATIONAL})
6532 or put Libgcrypt into the Fatal-Error state and won't return.
6533
6534 @item Fatal-Error
6535 Libgcrypt is in a non-recoverable error state and
6536 will automatically transit into the  Shutdown state.
6537
6538 @item Shutdown
6539 Libgcrypt is about to be terminated and removed from the memory. The
6540 application may at this point still running cleanup handlers.
6541
6542 @end table
6543 @end float
6544
6545
6546 @float Table,tbl:fips-state-transitions
6547 @caption{FIPS mode state transitions}
6548 @noindent
6549 The valid state transitions (@pxref{fig:fips-fsm}) are:
6550 @table @code
6551 @item 1
6552 Power-Off to Power-On is implicitly done by the OS loading Libgcrypt as
6553 a shared library and having it linked to an application.
6554
6555 @item 2
6556 Power-On to Init is triggered by the application calling the
6557 Libgcrypt initialization function @code{gcry_check_version}.
6558
6559 @item 3
6560 Init to Self-Test is either triggered by a dedicated API call or implicit
6561 by invoking a libgrypt service controlled by the FSM.
6562
6563 @item 4
6564 Self-Test to Operational is triggered after all self-tests passed
6565 successfully.
6566
6567 @item 5
6568 Operational to Shutdown is an artificial state without any direct action
6569 in Libgcrypt.  When reaching the Shutdown state the library is
6570 deinitialized and can't return to any other state again.
6571
6572 @item 6
6573 Shutdown to Power-off is the process of removing Libgcrypt from the
6574 computer's memory.  For obvious reasons the Power-Off state can't be
6575 represented within Libgcrypt and thus this transition is for
6576 documentation only.
6577
6578 @item 7
6579 Operational to Error is triggered if Libgcrypt detected an application
6580 error which can't be returned to the caller but still allows Libgcrypt
6581 to properly run.  In the Error state all FIPS relevant interfaces return
6582 an error code.
6583
6584 @item 8
6585 Error to Shutdown is similar to the Operational to Shutdown transition
6586 (5).
6587
6588 @item 9
6589 Error to Fatal-Error is triggered if Libgrypt detects an fatal error
6590 while already being in Error state.
6591
6592 @item 10
6593 Fatal-Error to Shutdown is automatically entered by Libgcrypt
6594 after having reported the error.
6595
6596 @item 11
6597 Power-On to Shutdown is an artificial state to document that Libgcrypt
6598 has not ye been initialized but the process is about to terminate.
6599
6600 @item 12
6601 Power-On to Fatal-Error will be triggered if certain Libgcrypt functions
6602 are used without having reached the Init state.
6603
6604 @item 13
6605 Self-Test to Fatal-Error is triggered by severe errors in Libgcrypt while
6606 running self-tests.
6607
6608 @item 14
6609 Self-Test to Error is triggered by a failed self-test.
6610
6611 @item 15
6612 Operational to Fatal-Error is triggered if Libcrypt encountered a
6613 non-recoverable error.
6614
6615 @item 16
6616 Operational to Self-Test is triggered if the application requested to run
6617 the self-tests again.
6618
6619 @item 17
6620 Error to Self-Test is triggered if the application has requested to run
6621 self-tests to get to get back into operational state after an error.
6622
6623 @item 18
6624 Init to Error is triggered by errors in the initialization code.
6625
6626 @item 19
6627 Init to Fatal-Error is triggered by non-recoverable errors in the
6628 initialization code.
6629
6630 @item 20
6631 Error to Error is triggered by errors while already in the Error
6632 state.
6633
6634
6635 @end table
6636 @end float
6637
6638 @c ********************************************
6639 @section FIPS Miscellaneous Information
6640
6641 Libgcrypt does not do any key management on itself; the application
6642 needs to care about it.  Keys which are passed to Libgcrypt should be
6643 allocated in secure memory as available with the functions
6644 @code{gcry_malloc_secure} and @code{gcry_calloc_secure}.  By calling
6645 @code{gcry_free} on this memory, the memory and thus the keys are
6646 overwritten with zero bytes before releasing the memory.
6647
6648 For use with the random number generator, Libgcrypt generates 3
6649 internal keys which are stored in the encryption contexts used by the
6650 RNG.  These keys are stored in secure memory for the lifetime of the
6651 process.  Application are required to use @code{GCRYCTL_TERM_SECMEM}
6652 before process termination.  This will zero out the entire secure
6653 memory and thus also the encryption contexts with these keys.
6654
6655
6656
6657 @c **********************************************************
6658 @c *************  Appendices (license etc.)  ****************
6659 @c **********************************************************
6660 @include lgpl.texi
6661
6662 @include gpl.texi
6663
6664 @node Figures and Tables
6665 @unnumbered List of Figures and Tables
6666
6667 @listoffloats Figure
6668
6669 @listoffloats Table
6670
6671 @node Concept Index
6672 @unnumbered Concept Index
6673
6674 @printindex cp
6675
6676 @node Function and Data Index
6677 @unnumbered Function and Data Index
6678
6679 @printindex fn
6680
6681
6682
6683 @bye
6684
6685 GCRYCTL_SET_RANDOM_DAEMON_SOCKET
6686 GCRYCTL_USE_RANDOM_DAEMON
6687 The random daemon is still a bit experimental, thus we do not document
6688 them.  Note that they should be used during initialization and that
6689 these functions are not really thread safe.
6690
6691
6692
6693
6694 @c  LocalWords:  int HD