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