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