PageRenderTime 68ms CodeModel.GetById 13ms RepoModel.GetById 1ms app.codeStats 0ms

/indra/libgcrypt/libgcrypt-1.2.2/doc/gcrypt.texi

https://bitbucket.org/lkalif/emerald-snowglobe
Unknown | 3756 lines | 2904 code | 852 blank | 0 comment | 0 complexity | 24b2b163fa8a26f44910b45e9aff279d MD5 | raw file
Possible License(s): LGPL-2.1, LGPL-2.0, BSD-3-Clause, GPL-2.0
  1. \input texinfo @c -*- Texinfo -*-
  2. @c %**start of header
  3. @setfilename gcrypt.info
  4. @include version.texi
  5. @settitle The Libgcrypt Reference Manual
  6. @c Unify some of the indices.
  7. @syncodeindex tp fn
  8. @syncodeindex pg fn
  9. @c %**end of header
  10. @copying
  11. This manual is for Libgcrypt
  12. (version @value{VERSION}, @value{UPDATED}),
  13. which is GNU's library of cryptographic building blocks.
  14. Copyright @copyright{} 2000, 2002, 2003, 2004 Free Software Foundation, Inc.
  15. @quotation
  16. Permission is granted to copy, distribute and/or modify this document
  17. under the terms of the GNU General Public License as published by the
  18. Free Software Foundation; either version 2 of the License, or (at your
  19. option) any later version. The text of the license can be found in the
  20. section entitled ``Copying''.
  21. @end quotation
  22. @end copying
  23. @dircategory GNU Libraries
  24. @direntry
  25. * libgcrypt: (gcrypt). Cryptographic function library.
  26. @end direntry
  27. @c
  28. @c Titlepage
  29. @c
  30. @setchapternewpage odd
  31. @titlepage
  32. @title The Libgcrypt Reference Manual
  33. @subtitle Version @value{VERSION}
  34. @subtitle @value{UPDATED}
  35. @author Werner Koch (@email{wk@@gnupg.org})
  36. @author Moritz Schulte (@email{mo@@g10code.com})
  37. @page
  38. @vskip 0pt plus 1filll
  39. @insertcopying
  40. @end titlepage
  41. @summarycontents
  42. @contents
  43. @page
  44. @ifnottex
  45. @node Top
  46. @top The Libgcrypt Library
  47. @insertcopying
  48. @end ifnottex
  49. @menu
  50. * Introduction:: What is @acronym{Libgcrypt}.
  51. * Preparation:: What you should do before using the library.
  52. * Generalities:: General library functions and data types.
  53. * Handler Functions:: Working with handler functions.
  54. * Symmetric cryptography:: How to use symmetric cryptography.
  55. * Hashing:: How to use hashing.
  56. * Public Key cryptography (I):: How to use public key cryptography.
  57. * Public Key cryptography (II):: How to use public key cryptography, alternatively.
  58. * Random Numbers:: How to work with random numbers.
  59. * S-expressions:: How to manage S-expressions.
  60. * MPI library:: How to work with multi-precision-integers.
  61. * Utilities:: Utility functions.
  62. Appendices
  63. * Library Copying:: The GNU Lesser General Public License
  64. says how you can copy and share `Libgcrypt'.
  65. * Copying:: The GNU General Public License says how you
  66. can copy and share some parts of `Libgcrypt'.
  67. Indices
  68. * Concept Index:: Index of concepts and programs.
  69. * Function and Data Index:: Index of functions, variables and data types.
  70. @detailmenu
  71. --- The Detailed Node Listing ---
  72. Introduction
  73. * Getting Started:: How to use this manual.
  74. * Features:: A glance at @acronym{Libgcrypt}'s features.
  75. * Overview:: Overview about the library.
  76. Preparation
  77. * Header:: What header file you need to include.
  78. * Building sources:: How to build sources using the library.
  79. * Building sources using Automake:: How to build sources with the help of Automake.
  80. * Initializing the library:: How to initialize the library.
  81. * Multi Threading:: How @acronym{Libgcrypt} can be used in a MT environment.
  82. Generalities
  83. * Controlling the library:: Controlling @acronym{Libgcrypt}'s behavior.
  84. * Modules:: Description of extension modules.
  85. * Error Handling:: Error codes and such.
  86. Handler Functions
  87. * Progress handler:: Using a progress handler function.
  88. * Allocation handler:: Using special memory allocation functions.
  89. * Error handler:: Using error handler functions.
  90. * Logging handler:: Using a special logging function.
  91. Symmetric cryptography
  92. * Available ciphers:: List of ciphers supported by the library.
  93. * Cipher modules:: How to work with cipher modules.
  94. * Available cipher modes:: List of cipher modes supported by the library.
  95. * Working with cipher handles:: How to perform operations related to cipher handles.
  96. * General cipher functions:: General cipher functions independent of cipher handles.
  97. Hashing
  98. * Available hash algorithms:: List of hash algorithms supported by the library.
  99. * Hash algorithm modules:: How to work with hash algorithm modules.
  100. * Working with hash algorithms:: List of functions related to hashing.
  101. Public Key cryptography (I)
  102. * Used S-expressions:: Introduction into the used S-expression.
  103. * Available algorithms:: Algorithms supported by the library.
  104. * Public key modules:: How to work with public key modules.
  105. * Cryptographic Functions:: Functions for performing the cryptographic actions.
  106. * General public-key related Functions:: General functions, not implementing any cryptography.
  107. Public Key cryptography (II)
  108. * Available asymmetric algorithms:: List of algorithms supported by the library.
  109. * Working with sets of data:: How to work with sets of data.
  110. * Working with handles:: How to use handles.
  111. * Working with keys:: How to work with keys.
  112. * Using cryptographic functions:: How to perform cryptographic operations.
  113. * Handle-independent functions:: General functions independent of handles.
  114. Random Numbers
  115. * Quality of random numbers:: @acronym{Libgcrypt} uses different quality levels.
  116. * Retrieving random numbers:: How to retrieve random numbers.
  117. S-expressions
  118. * Data types for S-expressions:: Data types related with S-expressions.
  119. * Working with S-expressions:: How to work with S-expressions.
  120. MPI library
  121. * Data types:: MPI related data types.
  122. * Basic functions:: First steps with MPI numbers.
  123. * MPI formats:: External representation of MPIs.
  124. * Calculations:: Performing MPI calculations.
  125. * Comparisons:: How to compare MPI values.
  126. * Bit manipulations:: How to access single bits of MPI values.
  127. * Miscellaneous:: Miscellaneous MPI functions.
  128. Utilities
  129. * Memory allocation:: Functions related with memory allocation.
  130. @end detailmenu
  131. @end menu
  132. @c **********************************************************
  133. @c ******************* Introduction ***********************
  134. @c **********************************************************
  135. @node Introduction
  136. @chapter Introduction
  137. `@acronym{Libgcrypt}' is a library providing cryptographic building blocks.
  138. @menu
  139. * Getting Started:: How to use this manual.
  140. * Features:: A glance at @acronym{Libgcrypt}'s features.
  141. * Overview:: Overview about the library.
  142. @end menu
  143. @node Getting Started
  144. @section Getting Started
  145. This manual documents the `@acronym{Libgcrypt}' library application programming
  146. interface (API). All functions and data types provided by the library
  147. are explained.
  148. @noindent
  149. The reader is assumed to possess basic knowledge about applied
  150. cryptography.
  151. This manual can be used in several ways. If read from the beginning
  152. to the end, it gives a good introduction into the library and how it
  153. can be used in an application. Forward references are included where
  154. necessary. Later on, the manual can be used as a reference manual to
  155. get just the information needed about any particular interface of the
  156. library. Experienced programmers might want to start looking at the
  157. examples at the end of the manual, and then only read up those parts
  158. of the interface which are unclear.
  159. @node Features
  160. @section Features
  161. `Libgcrypt' might have a couple of advantages over other libraries doing
  162. a similar job.
  163. @table @asis
  164. @item It's Free Software
  165. Anybody can use, modify, and redistribute it under the terms of the GNU
  166. Lesser General Public License (@pxref{Library Copying}). Note, that
  167. some parts (which are not needed on a GNU or GNU/Linux system) are
  168. subject to the terms of the GNU General Public License
  169. (@pxref{Copying}); please see the README file of the distribution for of
  170. list of these parts.
  171. @item It encapsulates the low level cryptography
  172. `@acronym{Libgcrypt}' provides a high level interface to cryptographic building
  173. blocks using an extendable and flexible API.
  174. @end table
  175. @node Overview
  176. @section Overview
  177. @noindent
  178. The `@acronym{Libgcrypt}' library is fully thread-safe, where it makes
  179. sense to be thread-safe. An exception for thread-safety are some
  180. cryptographic functions that modify a certain context stored in
  181. handles. If the user really intents to use such functions from
  182. different threads on the same handle, he has to take care of the
  183. serialization of such functions himself. If not described otherwise,
  184. every function is thread-safe.
  185. @acronym{Libgcrypt} depends on the library `libgpg-error', which
  186. contains common error handling related code for GnuPG components.
  187. @c **********************************************************
  188. @c ******************* Preparation ************************
  189. @c **********************************************************
  190. @node Preparation
  191. @chapter Preparation
  192. To use `@acronym{Libgcrypt}', you have to perform some changes to your
  193. sources and the build system. The necessary changes are small and
  194. explained in the following sections. At the end of this chapter, it
  195. is described how the library is initialized, and how the requirements
  196. of the library are verified.
  197. @menu
  198. * Header:: What header file you need to include.
  199. * Building sources:: How to build sources using the library.
  200. * Building sources using Automake:: How to build sources with the help of Automake.
  201. * Initializing the library:: How to initialize the library.
  202. * Multi Threading:: How @acronym{Libgcrypt} can be used in a MT environment.
  203. @end menu
  204. @node Header
  205. @section Header
  206. All interfaces (data types and functions) of the library are defined
  207. in the header file `gcrypt.h'. You must include this in all source
  208. files using the library, either directly or through some other header
  209. file, like this:
  210. @example
  211. #include <gcrypt.h>
  212. @end example
  213. The name space of `@acronym{Libgcrypt}' is @code{gcry_*} for function
  214. and type names and @code{GCRY*} for other symbols. In addition the
  215. same name prefixes with one prepended underscore are reserved for
  216. internal use and should never be used by an application. Furthermore
  217. `libgpg-error' defines functions prefixed with `gpg_' and preprocessor
  218. symbols prefixed with `GPG_'. Note that @acronym{Libgcrypt} uses
  219. libgpg-error, which uses @code{gpg_err_*} as name space for function
  220. and type names and @code{GPG_ERR_*} for other symbols, including all
  221. the error codes.
  222. @node Building sources
  223. @section Building sources
  224. If you want to compile a source file including the `gcrypt.h' header
  225. file, you must make sure that the compiler can find it in the
  226. directory hierarchy. This is accomplished by adding the path to the
  227. directory in which the header file is located to the compilers include
  228. file search path (via the @option{-I} option).
  229. However, the path to the include file is determined at the time the
  230. source is configured. To solve this problem, `@acronym{Libgcrypt}' ships with a small
  231. helper program @command{libgcrypt-config} that knows the path to the
  232. include file and other configuration options. The options that need
  233. to be added to the compiler invocation at compile time are output by
  234. the @option{--cflags} option to @command{libgcrypt-config}. The following
  235. example shows how it can be used at the command line:
  236. @example
  237. gcc -c foo.c `libgcrypt-config --cflags`
  238. @end example
  239. Adding the output of @samp{libgcrypt-config --cflags} to the compilers
  240. command line will ensure that the compiler can find the `@acronym{Libgcrypt}' header
  241. file.
  242. A similar problem occurs when linking the program with the library.
  243. Again, the compiler has to find the library files. For this to work,
  244. the path to the library files has to be added to the library search path
  245. (via the @option{-L} option). For this, the option @option{--libs} to
  246. @command{libgcrypt-config} can be used. For convenience, this option
  247. also outputs all other options that are required to link the program
  248. with the `@acronym{Libgcrypt}' libraries (in particular, the @samp{-lgcrypt}
  249. option). The example shows how to link @file{foo.o} with the `@acronym{Libgcrypt}'
  250. library to a program @command{foo}.
  251. @example
  252. gcc -o foo foo.o `libgcrypt-config --libs`
  253. @end example
  254. Of course you can also combine both examples to a single command by
  255. specifying both options to @command{libgcrypt-config}:
  256. @example
  257. gcc -o foo foo.c `libgcrypt-config --cflags --libs`
  258. @end example
  259. @node Building sources using Automake
  260. @section Building sources using Automake
  261. It is much easier if you use GNU Automake instead of writing your own
  262. Makefiles. If you do that you do not have to worry about finding and
  263. invoking the @command{libgcrypt-config} script at all.
  264. @acronym{Libgcrypt} provides an extension to Automake that does all
  265. the work for you.
  266. @c A simple macro for optional variables.
  267. @macro ovar{varname}
  268. @r{[}@var{\varname\}@r{]}
  269. @end macro
  270. @defmac AM_PATH_LIBGCRYPT (@ovar{minimum-version}, @ovar{action-if-found}, @ovar{action-if-not-found})
  271. Check whether @acronym{Libgcrypt} (at least version
  272. @var{minimum-version}, if given) exists on the host system. If it is
  273. found, execute @var{action-if-found}, otherwise do
  274. @var{action-if-not-found}, if given.
  275. Additionally, the function defines @code{LIBGCRYPT_CFLAGS} to the
  276. flags needed for compilation of the program to find the
  277. @file{gcrypt.h} header file, and @code{LIBGCRYPT_LIBS} to the linker
  278. flags needed to link the program to the @acronym{Libgcrypt} library.
  279. @end defmac
  280. You can use the defined Autoconf variables like this in your
  281. @file{Makefile.am}:
  282. @example
  283. AM_CPPFLAGS = $(LIBGCRYPT_CFLAGS)
  284. LDADD = $(LIBGCRYPT_LIBS)
  285. @end example
  286. @node Initializing the library
  287. @section Initializing the library
  288. It is often desirable to check that the version of `@acronym{Libgcrypt}' used is
  289. indeed one which fits all requirements. Even with binary compatibility
  290. new features may have been introduced but due to problem with the
  291. dynamic linker an old version is actually used. So you may want to
  292. check that the version is okay right after program startup.
  293. @deftypefun const char *gcry_check_version (const char *@var{req_version})
  294. The function @code{gcry_check_version} has three purposes. It can be
  295. used to retrieve the version number of the library. In addition it
  296. can verify that the version number is higher than a certain required
  297. version number.
  298. In either case, the function initializes some sub-systems, and for
  299. this reason alone it must be invoked early in your program, before you
  300. make use of the other functions of @acronym{Libgcrypt}.
  301. @end deftypefun
  302. @node Multi Threading
  303. @section Multi Threading
  304. As mentioned earlier, the `@acronym{Libgcrypt}' library is
  305. thread-safe if you adhere to the following requirements:
  306. @itemize @bullet
  307. @item
  308. If your application is multi-threaded, you must set the thread support
  309. callbacks with the @code{GCRYCTL_SET_THREAD_CBS} command
  310. @strong{before} any other function in the library.
  311. This is easy enough if you are indeed writing an application using
  312. Libgcrypt. It is rather problematic if you are writing a library
  313. instead. Here are some tips what to do if you are writing a library:
  314. If your library requires a certain thread package, just initialize
  315. Libgcrypt to use this thread package. If your library supports multiple
  316. thread packages, but needs to be configured, you will have to
  317. implement a way to determine which thread package the application
  318. wants to use with your library anyway. Then configure Libgcrypt to use
  319. this thread package.
  320. If your library is fully reentrant without any special support by a
  321. thread package, then you are lucky indeed. Unfortunately, this does
  322. not relieve you from doing either of the two above, or use a third
  323. option. The third option is to let the application initialize Libgcrypt
  324. for you. Then you are not using Libgcrypt transparently, though.
  325. As if this was not difficult enough, a conflict may arise if two
  326. libraries try to initialize Libgcrypt independently of each others, and
  327. both such libraries are then linked into the same application. To
  328. make it a bit simpler for you, this will probably work, but only if
  329. both libraries have the same requirement for the thread package. This
  330. is currently only supported for the non-threaded case, GNU Pth and
  331. pthread. Support for more thread packages is easy to add, so contact
  332. us if you require it.
  333. @item
  334. The function @code{gcry_check_version} must be called before any other
  335. function in the library, except the @code{GCRYCTL_SET_THREAD_CBS}
  336. command (called via the @code{gcry_control} function), because it
  337. initializes the thread support subsystem in @acronym{Libgcrypt}. To
  338. achieve this in multi-threaded programs, you must synchronize the
  339. memory with respect to other threads that also want to use
  340. @acronym{Libgcrypt}. For this, it is sufficient to call
  341. @code{gcry_check_version} before creating the other threads using
  342. @acronym{Libgcrypt}@footnote{At least this is true for POSIX threads,
  343. as @code{pthread_create} is a function that synchronizes memory with
  344. respects to other threads. There are many functions which have this
  345. property, a complete list can be found in POSIX, IEEE Std 1003.1-2003,
  346. Base Definitions, Issue 6, in the definition of the term ``Memory
  347. Synchronization''. For other thread packages, more relaxed or more
  348. strict rules may apply.}.
  349. @item
  350. As with the function @code{gpg_strerror}, @code{gcry_strerror} is not
  351. thread safe. You have to use @code{gpg_strerror_r} instead.
  352. @end itemize
  353. @acronym{Libgcrypt} contains convenient macros, which define the
  354. necessary thread callbacks for PThread and for GNU Pth:
  355. @table @code
  356. @item GCRY_THREAD_OPTION_PTH_IMPL
  357. This macro defines the following (static) symbols: gcry_pth_init,
  358. gcry_pth_mutex_init, gcry_pth_mutex_destroy, gcry_pth_mutex_lock,
  359. gcry_pth_mutex_unlock, gcry_pth_read, gcry_pth_write, gcry_pth_select,
  360. gcry_pth_waitpid, gcry_pth_accept, gcry_pth_connect, gcry_threads_pth.
  361. After including this macro, gcry_control() shall be used with a
  362. command of GCRYCTL_SET_THREAD_CBS in order to register the thread
  363. callback structure named ``gcry_threads_pth''.
  364. @item GCRY_THREAD_OPTION_PTHREAD_IMPL
  365. This macro defines the following (static) symbols:
  366. gcry_pthread_mutex_init, gcry_pthread_mutex_destroy, gcry_mutex_lock,
  367. gcry_mutex_unlock, gcry_threads_pthread.
  368. After including this macro, gcry_control() shall be used with a
  369. command of GCRYCTL_SET_THREAD_CBS in order to register the thread
  370. callback structure named ``gcry_threads_pthread''.
  371. @end table
  372. Note that these macros need to be terminated with a semicolon. Keep
  373. in mind that these are convenient macros for C programmers; C++
  374. programmers might have to wrap these macros in an ``extern C'' body.
  375. @c **********************************************************
  376. @c ******************* General ****************************
  377. @c **********************************************************
  378. @node Generalities
  379. @chapter Generalities
  380. @menu
  381. * Controlling the library:: Controlling @acronym{Libgcrypt}'s behavior.
  382. * Modules:: Description of extension modules.
  383. * Error Handling:: Error codes and such.
  384. @end menu
  385. @node Controlling the library
  386. @section Controlling the library
  387. @deftypefun gcry_error_t gcry_control (enum gcry_ctl_cmds @var{cmd}, ...)
  388. This function can be used to influence the general behavior of
  389. @acronym{Libgcrypt} in several ways. Depending on @var{cmd}, more
  390. arguments can or have to be provided.
  391. @end deftypefun
  392. @node Modules
  393. @section Modules
  394. @acronym{Libgcrypt} supports the use of `extension modules', which
  395. implement algorithms in addition to those already built into the
  396. library directly.
  397. @deftp {Data type} gcry_module_t
  398. This data type represents a `module'.
  399. @end deftp
  400. Functions registering modules provided by the user take a `module
  401. specification structure' as input and return a value of
  402. @code{gcry_module_t} and an ID that is unique in the modules'
  403. category. This ID can be used to reference the newly registered
  404. module. After registering a module successfully, the new functionality
  405. should be able to be used through the normal functions provided by
  406. @acronym{Libgcrypt} until it is unregistered again.
  407. @c **********************************************************
  408. @c ******************* Errors ****************************
  409. @c **********************************************************
  410. @node Error Handling
  411. @section Error Handling
  412. Many functions in @acronym{Libgcrypt} can return an error if they
  413. fail. For this reason, the application should always catch the error
  414. condition and take appropriate measures, for example by releasing the
  415. resources and passing the error up to the caller, or by displaying a
  416. descriptive message to the user and cancelling the operation.
  417. Some error values do not indicate a system error or an error in the
  418. operation, but the result of an operation that failed properly. For
  419. example, if you try to decrypt a tempered message, the decryption will
  420. fail. Another error value actually means that the end of a data
  421. buffer or list has been reached. The following descriptions explain
  422. for many error codes what they mean usually. Some error values have
  423. specific meanings if returned by a certain functions. Such cases are
  424. described in the documentation of those functions.
  425. @acronym{Libgcrypt} uses the @code{libgpg-error} library. This allows
  426. to share the error codes with other components of the GnuPG system,
  427. and thus pass error values transparently from the crypto engine, or
  428. some helper application of the crypto engine, to the user. This way
  429. no information is lost. As a consequence, @acronym{Libgcrypt} does
  430. not use its own identifiers for error codes, but uses those provided
  431. by @code{libgpg-error}. They usually start with @code{GPG_ERR_}.
  432. However, @acronym{Libgcrypt} does provide aliases for the functions
  433. defined in libgpg-error, which might be preferred for name space
  434. consistency.
  435. Most functions in @acronym{Libgcrypt} return an error code in the case
  436. of failure. For this reason, the application should always catch the
  437. error condition and take appropriate measures, for example by
  438. releasing the resources and passing the error up to the caller, or by
  439. displaying a descriptive message to the user and canceling the
  440. operation.
  441. Some error values do not indicate a system error or an error in the
  442. operation, but the result of an operation that failed properly.
  443. GnuPG components, including Libgcrypt, use an extra library named
  444. libgpg-error to provide a common error handling scheme. For more
  445. information on libgpg-error, see the according manual.
  446. @menu
  447. * Error Values:: The error value and what it means.
  448. * Error Sources:: A list of important error sources.
  449. * Error Codes:: A list of important error codes.
  450. * Error Strings:: How to get a descriptive string from a value.
  451. @end menu
  452. @node Error Values
  453. @subsection Error Values
  454. @cindex error values
  455. @cindex error codes
  456. @cindex error sources
  457. @deftp {Data type} {gcry_err_code_t}
  458. The @code{gcry_err_code_t} type is an alias for the
  459. @code{libgpg-error} type @code{gpg_err_code_t}. The error code
  460. indicates the type of an error, or the reason why an operation failed.
  461. A list of important error codes can be found in the next section.
  462. @end deftp
  463. @deftp {Data type} {gcry_err_source_t}
  464. The @code{gcry_err_source_t} type is an alias for the
  465. @code{libgpg-error} type @code{gpg_err_source_t}. The error source
  466. has not a precisely defined meaning. Sometimes it is the place where
  467. the error happened, sometimes it is the place where an error was
  468. encoded into an error value. Usually the error source will give an
  469. indication to where to look for the problem. This is not always true,
  470. but it is attempted to achieve this goal.
  471. A list of important error sources can be found in the next section.
  472. @end deftp
  473. @deftp {Data type} {gcry_error_t}
  474. The @code{gcry_error_t} type is an alias for the @code{libgpg-error}
  475. type @code{gpg_error_t}. An error value like this has always two
  476. components, an error code and an error source. Both together form the
  477. error value.
  478. Thus, the error value can not be directly compared against an error
  479. code, but the accessor functions described below must be used.
  480. However, it is guaranteed that only 0 is used to indicate success
  481. (@code{GPG_ERR_NO_ERROR}), and that in this case all other parts of
  482. the error value are set to 0, too.
  483. Note that in @acronym{Libgcrypt}, the error source is used purely for
  484. diagnostic purposes. Only the error code should be checked to test
  485. for a certain outcome of a function. The manual only documents the
  486. error code part of an error value. The error source is left
  487. unspecified and might be anything.
  488. @end deftp
  489. @deftypefun {gcry_err_code_t} gcry_err_code (@w{gcry_error_t @var{err}})
  490. The static inline function @code{gcry_err_code} returns the
  491. @code{gcry_err_code_t} component of the error value @var{err}. This
  492. function must be used to extract the error code from an error value in
  493. order to compare it with the @code{GPG_ERR_*} error code macros.
  494. @end deftypefun
  495. @deftypefun {gcry_err_source_t} gcry_err_source (@w{gcry_error_t @var{err}})
  496. The static inline function @code{gcry_err_source} returns the
  497. @code{gcry_err_source_t} component of the error value @var{err}. This
  498. function must be used to extract the error source from an error value in
  499. order to compare it with the @code{GPG_ERR_SOURCE_*} error source macros.
  500. @end deftypefun
  501. @deftypefun {gcry_error_t} gcry_err_make (@w{gcry_err_source_t @var{source}}, @w{gcry_err_code_t @var{code}})
  502. The static inline function @code{gcry_err_make} returns the error
  503. value consisting of the error source @var{source} and the error code
  504. @var{code}.
  505. This function can be used in callback functions to construct an error
  506. value to return it to the library.
  507. @end deftypefun
  508. @deftypefun {gcry_error_t} gcry_error (@w{gcry_err_code_t @var{code}})
  509. The static inline function @code{gcry_error} returns the error value
  510. consisting of the default error source and the error code @var{code}.
  511. For @acronym{GCRY} applications, the default error source is
  512. @code{GPG_ERR_SOURCE_USER_1}. You can define
  513. @code{GCRY_ERR_SOURCE_DEFAULT} before including @file{gcrypt.h} to
  514. change this default.
  515. This function can be used in callback functions to construct an error
  516. value to return it to the library.
  517. @end deftypefun
  518. The @code{libgpg-error} library provides error codes for all system
  519. error numbers it knows about. If @var{err} is an unknown error
  520. number, the error code @code{GPG_ERR_UNKNOWN_ERRNO} is used. The
  521. following functions can be used to construct error values from system
  522. errno numbers.
  523. @deftypefun {gcry_error_t} gcry_err_make_from_errno (@w{gcry_err_source_t @var{source}}, @w{int @var{err}})
  524. The function @code{gcry_err_make_from_errno} is like
  525. @code{gcry_err_make}, but it takes a system error like @code{errno}
  526. instead of a @code{gcry_err_code_t} error code.
  527. @end deftypefun
  528. @deftypefun {gcry_error_t} gcry_error_from_errno (@w{int @var{err}})
  529. The function @code{gcry_error_from_errno} is like @code{gcry_error},
  530. but it takes a system error like @code{errno} instead of a
  531. @code{gcry_err_code_t} error code.
  532. @end deftypefun
  533. Sometimes you might want to map system error numbers to error codes
  534. directly, or map an error code representing a system error back to the
  535. system error number. The following functions can be used to do that.
  536. @deftypefun {gcry_err_code_t} gcry_err_code_from_errno (@w{int @var{err}})
  537. The function @code{gcry_err_code_from_errno} returns the error code
  538. for the system error @var{err}. If @var{err} is not a known system
  539. error, the function returns @code{GPG_ERR_UNKNOWN_ERRNO}.
  540. @end deftypefun
  541. @deftypefun {int} gcry_err_code_to_errno (@w{gcry_err_code_t @var{err}})
  542. The function @code{gcry_err_code_to_errno} returns the system error
  543. for the error code @var{err}. If @var{err} is not an error code
  544. representing a system error, or if this system error is not defined on
  545. this system, the function returns @code{0}.
  546. @end deftypefun
  547. @node Error Sources
  548. @subsection Error Sources
  549. @cindex error codes, list of
  550. The library @code{libgpg-error} defines an error source for every
  551. component of the GnuPG system. The error source part of an error
  552. value is not well defined. As such it is mainly useful to improve the
  553. diagnostic error message for the user.
  554. If the error code part of an error value is @code{0}, the whole error
  555. value will be @code{0}. In this case the error source part is of
  556. course @code{GPG_ERR_SOURCE_UNKNOWN}.
  557. The list of error sources that might occur in applications using
  558. @acronym{Libgctypt} is:
  559. @table @code
  560. @item GPG_ERR_SOURCE_UNKNOWN
  561. The error source is not known. The value of this error source is
  562. @code{0}.
  563. @item GPG_ERR_SOURCE_GPGME
  564. The error source is @acronym{GPGME} itself.
  565. @item GPG_ERR_SOURCE_GPG
  566. The error source is GnuPG, which is the crypto engine used for the
  567. OpenPGP protocol.
  568. @item GPG_ERR_SOURCE_GPGSM
  569. The error source is GPGSM, which is the crypto engine used for the
  570. OpenPGP protocol.
  571. @item GPG_ERR_SOURCE_GCRYPT
  572. The error source is @code{libgcrypt}, which is used by crypto engines
  573. to perform cryptographic operations.
  574. @item GPG_ERR_SOURCE_GPGAGENT
  575. The error source is @command{gpg-agent}, which is used by crypto
  576. engines to perform operations with the secret key.
  577. @item GPG_ERR_SOURCE_PINENTRY
  578. The error source is @command{pinentry}, which is used by
  579. @command{gpg-agent} to query the passphrase to unlock a secret key.
  580. @item GPG_ERR_SOURCE_SCD
  581. The error source is the SmartCard Daemon, which is used by
  582. @command{gpg-agent} to delegate operations with the secret key to a
  583. SmartCard.
  584. @item GPG_ERR_SOURCE_KEYBOX
  585. The error source is @code{libkbx}, a library used by the crypto
  586. engines to manage local keyrings.
  587. @item GPG_ERR_SOURCE_USER_1
  588. @item GPG_ERR_SOURCE_USER_2
  589. @item GPG_ERR_SOURCE_USER_3
  590. @item GPG_ERR_SOURCE_USER_4
  591. These error sources are not used by any GnuPG component and can be
  592. used by other software. For example, applications using
  593. @acronym{Libgcrypt} can use them to mark error values coming from callback
  594. handlers. Thus @code{GPG_ERR_SOURCE_USER_1} is the default for errors
  595. created with @code{gcry_error} and @code{gcry_error_from_errno},
  596. unless you define @code{GCRY_ERR_SOURCE_DEFAULT} before including
  597. @file{gcrypt.h}.
  598. @end table
  599. @node Error Codes
  600. @subsection Error Codes
  601. @cindex error codes, list of
  602. The library @code{libgpg-error} defines many error values. The
  603. following list includes the most important error codes.
  604. @table @code
  605. @item GPG_ERR_EOF
  606. This value indicates the end of a list, buffer or file.
  607. @item GPG_ERR_NO_ERROR
  608. This value indicates success. The value of this error code is
  609. @code{0}. Also, it is guaranteed that an error value made from the
  610. error code @code{0} will be @code{0} itself (as a whole). This means
  611. that the error source information is lost for this error code,
  612. however, as this error code indicates that no error occured, this is
  613. generally not a problem.
  614. @item GPG_ERR_GENERAL
  615. This value means that something went wrong, but either there is not
  616. enough information about the problem to return a more useful error
  617. value, or there is no separate error value for this type of problem.
  618. @item GPG_ERR_ENOMEM
  619. This value means that an out-of-memory condition occurred.
  620. @item GPG_ERR_E...
  621. System errors are mapped to GPG_ERR_EFOO where FOO is the symbol for
  622. the system error.
  623. @item GPG_ERR_INV_VALUE
  624. This value means that some user provided data was out of range.
  625. @item GPG_ERR_UNUSABLE_PUBKEY
  626. This value means that some recipients for a message were invalid.
  627. @item GPG_ERR_UNUSABLE_SECKEY
  628. This value means that some signers were invalid.
  629. @item GPG_ERR_NO_DATA
  630. This value means that data was expected where no data was found.
  631. @item GPG_ERR_CONFLICT
  632. This value means that a conflict of some sort occurred.
  633. @item GPG_ERR_NOT_IMPLEMENTED
  634. This value indicates that the specific function (or operation) is not
  635. implemented. This error should never happen. It can only occur if
  636. you use certain values or configuration options which do not work,
  637. but for which we think that they should work at some later time.
  638. @item GPG_ERR_DECRYPT_FAILED
  639. This value indicates that a decryption operation was unsuccessful.
  640. @item GPG_ERR_WRONG_KEY_USAGE
  641. This value indicates that a key is not used appropriately.
  642. @item GPG_ERR_NO_SECKEY
  643. This value indicates that no secret key for the user ID is available.
  644. @item GPG_ERR_UNSUPPORTED_ALGORITHM
  645. This value means a verification failed because the cryptographic
  646. algorithm is not supported by the crypto backend.
  647. @item GPG_ERR_BAD_SIGNATURE
  648. This value means a verification failed because the signature is bad.
  649. @item GPG_ERR_NO_PUBKEY
  650. This value means a verification failed because the public key is not
  651. available.
  652. @item GPG_ERR_USER_1
  653. @item GPG_ERR_USER_2
  654. @item ...
  655. @item GPG_ERR_USER_16
  656. These error codes are not used by any GnuPG component and can be
  657. freely used by other software. Applications using @acronym{Libgcrypt}
  658. might use them to mark specific errors returned by callback handlers
  659. if no suitable error codes (including the system errors) for these
  660. errors exist already.
  661. @end table
  662. @node Error Strings
  663. @subsection Error Strings
  664. @cindex error values, printing of
  665. @cindex error codes, printing of
  666. @cindex error sources, printing of
  667. @cindex error strings
  668. @deftypefun {const char *} gcry_strerror (@w{gcry_error_t @var{err}})
  669. The function @code{gcry_strerror} returns a pointer to a statically
  670. allocated string containing a description of the error code contained
  671. in the error value @var{err}. This string can be used to output a
  672. diagnostic message to the user.
  673. @end deftypefun
  674. @deftypefun {const char *} gcry_strsource (@w{gcry_error_t @var{err}})
  675. The function @code{gcry_strerror} returns a pointer to a statically
  676. allocated string containing a description of the error source
  677. contained in the error value @var{err}. This string can be used to
  678. output a diagnostic message to the user.
  679. @end deftypefun
  680. The following example illustrates the use of the functions described
  681. above:
  682. @example
  683. @{
  684. gcry_cipher_hd_t handle;
  685. gcry_error_t err = 0;
  686. err = gcry_cipher_open (&handle, GCRY_CIPHER_AES, GCRY_CIPHER_MODE_CBC, 0);
  687. if (err)
  688. @{
  689. fprintf (stderr, "Failure: %s/%s\n",
  690. gcry_strsource (err),
  691. gcry_strerror (err));
  692. @}
  693. @}
  694. @end example
  695. @c **********************************************************
  696. @c ******************* General ****************************
  697. @c **********************************************************
  698. @node Handler Functions
  699. @chapter Handler Functions
  700. @acronym{Libgcrypt} makes it possible to install so called `handler functions',
  701. which get called by @acronym{Libgcrypt} in case of certain events.
  702. @menu
  703. * Progress handler:: Using a progress handler function.
  704. * Allocation handler:: Using special memory allocation functions.
  705. * Error handler:: Using error handler functions.
  706. * Logging handler:: Using a special logging function.
  707. @end menu
  708. @node Progress handler
  709. @section Progress handler
  710. It is often useful to retrieve some feedback while long running
  711. operations are performed.
  712. @deftp {Data type} gcry_handler_progress_t
  713. Progress handler functions have to be of the type
  714. @code{gcry_handler_progress_t}, which is defined as:
  715. @code{void (*gcry_handler_progress_t) (void *, const char *, int, int, int)}
  716. @end deftp
  717. The following function may be used to register a handler function for
  718. this purpose.
  719. @deftypefun void gcry_set_progress_handler (gcry_handler_progress_t @var{cb}, void *@var{cb_data})
  720. This function installs @var{cb} as the `Progress handler' function.
  721. @var{cb} must be defined as follows:
  722. @example
  723. void
  724. my_progress_handler (void *@var{cb_data}, const char *@var{what},
  725. int @var{printchar}, int @var{current}, int @var{total})
  726. @{
  727. /* Do something. */
  728. @}
  729. @end example
  730. A description of the arguments of the progress handler function follows.
  731. @table @var
  732. @item cb_data
  733. The argument provided in the call to @code{gcry_set_progress_handler}.
  734. @item what
  735. A string identifying the type of the progress output. The following
  736. values for @var{what} are defined:
  737. @table @code
  738. @item need_entropy
  739. Not enough entropy is available. @var{total} holds the number of
  740. required bytes.
  741. @item primegen
  742. Values for @var{printchar}:
  743. @table @code
  744. @item \n
  745. Prime generated.
  746. @item !
  747. Need to refresh the pool of prime numbers.
  748. @item <, >
  749. Number of bits adjusted.
  750. @item ^
  751. Searching for a generator.
  752. @item .
  753. Fermat test on 10 candidates failed.
  754. @item :
  755. Restart with a new random value.
  756. @item +
  757. Rabin Miller test passed.
  758. @end table
  759. @end table
  760. @end table
  761. @end deftypefun
  762. @node Allocation handler
  763. @section Allocation handler
  764. It is possible to make @acronym{Libgcrypt} use special memory
  765. allocation functions instead of the built-in ones.
  766. Memory allocation functions are of the following types:
  767. @deftp {Data type} gcry_handler_alloc_t
  768. This type is defined as: @code{void *(*gcry_handler_alloc_t) (size_t n)}.
  769. @end deftp
  770. @deftp {Data type} gcry_handler_secure_check_t
  771. This type is defined as: @code{int *(*gcry_handler_secure_check_t) (const void *)}.
  772. @end deftp
  773. @deftp {Data type} gcry_handler_realloc_t
  774. This type is defined as: @code{void *(*gcry_handler_realloc_t) (void *p, size_t n)}.
  775. @end deftp
  776. @deftp {Data type} gcry_handler_free_t
  777. This type is defined as: @code{void *(*gcry_handler_free_t) (void *)}.
  778. @end deftp
  779. Special memory allocation functions can be installed with the
  780. following function:
  781. @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})
  782. Install the provided functions and use them instead of the built-in
  783. functions for doing memory allocation.
  784. @end deftypefun
  785. @node Error handler
  786. @section Error handler
  787. The following functions may be used to register handler functions that
  788. are called by @acronym{Libgcrypt} in case certain error conditions
  789. occur.
  790. @deftp {Data type} gcry_handler_no_mem_t
  791. This type is defined as: @code{void (*gcry_handler_no_mem_t) (void *, size_t, unsigned int)}
  792. @end deftp
  793. @deftypefun void gcry_set_outofcore_handler (gcry_handler_no_mem_t @var{func_no_mem}, void *@var{cb_data})
  794. This function registers @var{func_no_mem} as `out-of-core handler',
  795. which means that it will be called in the case of not having enough
  796. memory available.
  797. @end deftypefun
  798. @deftp {Data type} gcry_handler_error_t
  799. This type is defined as: @code{void (*gcry_handler_error_t) (void *, int, const char *)}
  800. @end deftp
  801. @deftypefun void gcry_set_fatalerror_handler (gcry_handler_error_t @var{func_error}, void *@var{cb_data})
  802. This function registers @var{func_error} as `error handler',
  803. which means that it will be called in error conditions.
  804. @end deftypefun
  805. @node Logging handler
  806. @section Logging handler
  807. @deftp {Data type} gcry_handler_log_t
  808. This type is defined as: @code{void (*gcry_handler_log_t) (void *, int, const char *, va_list)}
  809. @end deftp
  810. @deftypefun void gcry_set_log_handler (gcry_handler_log_t @var{func_log}, void *@var{cb_data})
  811. This function registers @var{func_log} as `logging handler', which
  812. means that it will be called in case @acronym{Libgcrypt} wants to log
  813. a message.
  814. @end deftypefun
  815. @c **********************************************************
  816. @c ******************* Ciphers ****************************
  817. @c **********************************************************
  818. @c @include cipher-ref.texi
  819. @node Symmetric cryptography
  820. @chapter Symmetric cryptography
  821. The cipher functions are used for symmetrical cryptography,
  822. i.e. cryptography using a shared key. The programming model follows
  823. an open/process/close paradigm and is in that similar to other
  824. building blocks provided by @acronym{Libgcrypt}.
  825. @menu
  826. * Available ciphers:: List of ciphers supported by the library.
  827. * Cipher modules:: How to work with cipher modules.
  828. * Available cipher modes:: List of cipher modes supported by the library.
  829. * Working with cipher handles:: How to perform operations related to cipher handles.
  830. * General cipher functions:: General cipher functions independent of cipher handles.
  831. @end menu
  832. @node Available ciphers
  833. @section Available ciphers
  834. @table @code
  835. @item GCRY_CIPHER_NONE
  836. This is not a real algorithm but used by some functions as error return.
  837. The value always evaluates to false.
  838. @item GCRY_CIPHER_IDEA
  839. This is the IDEA algorithm. The constant is provided but there is
  840. currently no implementation for it because the algorithm is patented.
  841. @item GCRY_CIPHER_3DES
  842. Triple-DES with 3 Keys as EDE. The key size of this algorithm is 168 but
  843. you have to pass 192 bits because the most significant bits of each byte
  844. are ignored.
  845. @item GCRY_CIPHER_CAST5
  846. CAST128-5 block cipher algorithm. The key size is 128 bits.
  847. @item GCRY_CIPHER_BLOWFISH
  848. The blowfish algorithm. The current implementation allows only for a key
  849. size of 128 bits.
  850. @item GCRY_CIPHER_SAFER_SK128
  851. Reserved and not currently implemented.
  852. @item GCRY_CIPHER_DES_SK
  853. Reserved and not currently implemented.
  854. @item GCRY_CIPHER_AES
  855. @itemx GCRY_CIPHER_AES128
  856. @itemx GCRY_CIPHER_RIJNDAEL
  857. @itemx GCRY_CIPHER_RIJNDAEL128
  858. AES (Rijndael) with a 128 bit key.
  859. @item GCRY_CIPHER_AES192
  860. @itemx GCRY_CIPHER_RIJNDAEL128
  861. AES (Rijndael) with a 192 bit key.
  862. @item GCRY_CIPHER_AES256
  863. @itemx GCRY_CIPHER_RIJNDAEL256
  864. AES (Rijndael) with a 256 bit key.
  865. @item GCRY_CIPHER_TWOFISH
  866. The Twofish algorithm with a 256 bit key.
  867. @item GCRY_CIPHER_TWOFISH128
  868. The Twofish algorithm with a 128 bit key.
  869. @item GCRY_CIPHER_ARCFOUR
  870. An algorithm which is 100% compatible with RSA Inc.'s RC4 algorithm.
  871. Note that this is a stream cipher and must be used very carefully to
  872. avoid a couple of weaknesses.
  873. @item GCRY_CIPHER_DES
  874. Standard DES with a 56 bit key. You need to pass 64 bit but the high
  875. bits of each byte are ignored. Note, that this is a weak algorithm
  876. which can be broken in reasonable time using a brute force approach.
  877. @end table
  878. @node Cipher modules
  879. @section Cipher modules
  880. @acronym{Libgcrypt} makes it possible to load additional `cipher
  881. modules'; these cipher can be used just like the cipher algorithms
  882. that are built into the library directly. For an introduction into
  883. extension modules, see @xref{Modules}.
  884. @deftp {Data type} gcry_cipher_spec_t
  885. This is the `module specification structure' needed for registering
  886. cipher modules, which has to be filled in by the user before it can be
  887. used to register a module. It contains the following members:
  888. @table @code
  889. @item const char *name
  890. The primary name of the algorithm.
  891. @item const char **aliases
  892. A list of strings that are `aliases' for the algorithm. The list must
  893. be terminated with a NULL element.
  894. @item gcry_cipher_oid_spec_t *oids
  895. A list of OIDs that are to be associated with the algorithm. The
  896. list's last element must have it's `oid' member set to NULL. See
  897. below for an explanation of this type.
  898. @item size_t blocksize
  899. The block size of the algorithm, in bytes.
  900. @item size_t keylen
  901. The length of the key, in bits.
  902. @item size_t contextsize
  903. The size of the algorithm-specific `context', that should be allocated
  904. for each handle.
  905. @item gcry_cipher_setkey_t setkey
  906. The function responsible for initializing a handle with a provided
  907. key. See below for a description of this type.
  908. @item gcry_cipher_encrypt_t encrypt
  909. The function responsible for encrypting a single block. See below for
  910. a description of this type.
  911. @item gcry_cipher_decrypt_t decrypt
  912. The function responsible for decrypting a single block. See below for
  913. a description of this type.
  914. @item gcry_cipher_stencrypt_t stencrypt
  915. Like `encrypt', for stream ciphers. See below for a description of
  916. this type.
  917. @item gcry_cipher_stdecrypt_t stdecrypt
  918. Like `decrypt', for stream ciphers. See below for a description of
  919. this type.
  920. @end table
  921. @end deftp
  922. @deftp {Data type} gcry_cipher_oid_spec_t
  923. This type is used for associating a user-provided algorithm
  924. implementation with certain OIDs. It contains the following members:
  925. @table @code
  926. @item const char *oid
  927. Textual representation of the OID.
  928. @item int mode
  929. Cipher mode for which this OID is valid.
  930. @end table
  931. @end deftp
  932. @deftp {Data type} gcry_cipher_setkey_t
  933. Type for the `setkey' function, defined as: gcry_err_code_t
  934. (*gcry_cipher_setkey_t) (void *c, const unsigned char *key, unsigned
  935. keylen)
  936. @end deftp
  937. @deftp {Data type} gcry_cipher_encrypt_t
  938. Type for the `encrypt' function, defined as: gcry_err_code_t
  939. (*gcry_cipher_encrypt_t) (void *c, const unsigned char *outbuf, const
  940. unsigned char *inbuf)
  941. @end deftp
  942. @deftp {Data type} gcry_cipher_decrypt_t
  943. Type for the `decrypt' function, defined as: gcry_err_code_t
  944. (*gcry_cipher_decrypt_t) (void *c, const unsigned char *outbuf, const
  945. unsigned char *inbuf)
  946. @end deftp
  947. @deftp {Data type} gcry_cipher_stencrypt_t
  948. Type for the `stencrypt' function, defined as: gcry_err_code_t
  949. (*gcry_cipher_stencrypt_t) (void *c, const unsigned char *outbuf, const
  950. unsigned char *, unsigned int n)
  951. @end deftp
  952. @deftp {Data type} gcry_cipher_stdecrypt_t
  953. Type for the `stdecrypt' function, defined as: gcry_err_code_t
  954. (*gcry_cipher_stdecrypt_t) (void *c, const unsigned char *outbuf, const
  955. unsigned char *, unsigned int n)
  956. @end deftp
  957. @deftypefun gcry_error_t gcry_cipher_register (gcry_cipher_spec_t *@var{cipher}, unsigned int *algorithm_id, gcry_module_t *@var{module})
  958. Register a new cipher module whose specification can be found in
  959. @var{cipher}. On success, a new algorithm ID is stored in
  960. @var{algorithm_id} and a pointer representing this module is stored
  961. in @var{module}.
  962. @end deftypefun
  963. @deftypefun void gcry_cipher_unregister (gcry_module_t @var{module})
  964. Unregister the cipher identified by @var{module}, which must have been
  965. registered with gcry_cipher_register.
  966. @end deftypefun
  967. @deftypefun gcry_error_t gcry_cipher_list (int *@var{list}, int *@var{list_length})
  968. Get a list consisting of the IDs of the loaded cipher modules. If
  969. @var{list} is zero, write the number of loaded cipher modules to
  970. @var{list_length} and return. If @var{list} is non-zero, the first
  971. *@var{list_length} algorithm IDs are stored in @var{list}, which must
  972. be of according size. In case there are less cipher modules than
  973. *@var{list_length}, *@var{list_length} is updated to the correct
  974. number.
  975. @end deftypefun
  976. @node Available cipher modes
  977. @section Available cipher modes
  978. @table @code
  979. @item GCRY_CIPHER_MODE_NONE
  980. No mode specified, may be set later using other functions. The value
  981. of this constant is always 0.
  982. @item GCRY_CIPHER_MODE_ECB
  983. Electronic Codebook mode.
  984. @item GCRY_CIPHER_MODE_CFB
  985. Cipher Feedback mode.
  986. @item GCRY_CIPHER_MODE_CBC
  987. Cipher Block Chaining mode.
  988. @item GCRY_CIPHER_MODE_STREAM
  989. Stream mode, only to be used with stream cipher algorithms.
  990. @item GCRY_CIPHER_MODE_OFB
  991. Outer Feedback mode.
  992. @item GCRY_CIPHER_MODE_CTR
  993. Counter mode.
  994. @end table
  995. @node Working with cipher handles
  996. @section Working with cipher handles
  997. To use a cipher algorithm, you must first allocate an according
  998. handle. This is to be done using the open function:
  999. @deftypefun gcry_error_t gcry_cipher_open (gcry_cipher_hd_t *@var{hd}, int @var{algo}, int @var{mode}, unsigned int @var{flags})
  1000. This function creates the context handle required for most of the
  1001. other cipher functions and returns a handle to it in `hd'. In case of
  1002. an error, an according error code is returned.
  1003. The ID of algorithm to use must be specified via @var{algo}. See
  1004. @xref{Available ciphers}, for a list of supported ciphers and the
  1005. according constants.
  1006. Besides using the constants directly, the function
  1007. @code{gcry_cipher_map_name} may be used to convert the textual name of
  1008. an algorithm into the according numeric ID.
  1009. The cipher mode to use must be specified via @var{mode}. See
  1010. @xref{Available cipher modes}, for a list of supported cipher modes
  1011. and the according constants. Note, that some modes do not work
  1012. together with all algorithms.
  1013. The third argument @var{flags} can either be passed as @code{0} or as
  1014. the bit-wise OR of the following constants.
  1015. @table @code
  1016. @item GCRY_CIPHER_SECURE
  1017. Make sure that all operations are allocated in secure memory. This is
  1018. useful, when the key material is highly confidential.
  1019. @item GCRY_CIPHER_ENABLE_SYNC
  1020. This flag enables the CFB sync mode, which is a special feature of
  1021. @acronym{Libgcrypt}'s CFB mode implementation to allow for OpenPGP's CFB variant.
  1022. See @code{gcry_cipher_sync}.
  1023. @item GCRY_CIPHER_CBC_CTS
  1024. Enable cipher text stealing (CTS) for the CBC mode. Cannot be used
  1025. simultaneous as GCRY_CIPHER_CBC_MAC
  1026. @item GCRY_CIPHER_CBC_MAC
  1027. Compute CBC-MAC keyed checksums. This is the same as CBC mode, but
  1028. only output the last block. Cannot be used simultaneous as
  1029. GCRY_CIPHER_CBC_CTS.
  1030. @end table
  1031. @end deftypefun
  1032. Use the following function to release an existing handle:
  1033. @deftypefun void gcry_cipher_close (gcry_cipher_hd_t @var{h})
  1034. This function releases the context created by @code{gcry_cipher_open}.
  1035. @end deftypefun
  1036. In order to use a handle for performing cryptographic operations, a
  1037. `key' has to be set first:
  1038. @deftypefun gcry_error_t gcry_cipher_setkey (gcry_cipher_hd_t @var{h}, void *@var{k}, size_t @var{l})
  1039. Set the key @var{k} used for encryption or decryption in the context
  1040. denoted by the handle @var{h}. The length @var{l} of the key @var{k}
  1041. must match the required length of the algorithm set for this context or
  1042. be in the allowed range for algorithms with variable key size. The
  1043. function checks this and returns an error if there is a problem. A
  1044. caller should always check for an error.
  1045. Note, this is currently implemented as a macro but may be changed to a
  1046. function in the future.
  1047. @end deftypefun
  1048. Most crypto modes requires an initialization vector (IV), which
  1049. usually is a non-secret random string acting as a kind of salt value.
  1050. The CTR mode requires a counter, which is also similar to a salt
  1051. value. To set the IV or CTR, use these functions:
  1052. @deftypefun gcry_error_t gcry_cipher_setiv (gcry_cipher_hd_t @var{h}, void *@var{k}, size_t @var{l})
  1053. Set the initialization vector used for encryption or decryption. The
  1054. vector is passed as the buffer @var{K} of length @var{l} and copied to
  1055. internal data structures. The function checks that the IV matches the
  1056. requirement of the selected algorithm and mode. Note, that this is
  1057. implemented as a macro.
  1058. @end deftypefun
  1059. @deftypefun gcry_error_t gcry_cipher_setctr (gcry_cipher_hd_t @var{h}, void *@var{c}, size_t @var{l})
  1060. Set the counter vector used for encryption or decryption. The counter
  1061. is passed as the buffer @var{c} of length @var{l} and copied to
  1062. internal data structures. The function checks that the counter
  1063. matches the requirement of the selected algorithm (i.e., it must be
  1064. the same size as the block size). Note, that this is implemented as a
  1065. macro.
  1066. @end deftypefun
  1067. @deftypefun gcry_error_t gcry_cipher_reset (gcry_cipher_hd_t @var{h})
  1068. Set the given handle's context back to the state it had after the last
  1069. call to gcry_cipher_setkey and clear the initialization vector.
  1070. Note, that gcry_cipher_reset is implemented as a macro.
  1071. @end deftypefun
  1072. The actual encryption and decryption is done by using one of the
  1073. following functions. They may be used as often as required to process
  1074. all the data.
  1075. @deftypefun gcry_error_t gcry_cipher_encrypt (gcry_cipher_hd_t @var{h}, void *{out}, size_t @var{outsize}, const void *@var{in}, size_t @var{inlen})
  1076. @code{gcry_cipher_encrypt} is used to encrypt the data. This function
  1077. can either work in place or with two buffers. It uses the cipher
  1078. context already setup and described by the handle @var{h}. There are 2
  1079. ways to use the function: If @var{in} is passed as @code{NULL} and
  1080. @var{inlen} is @code{0}, in-place encryption of the data in @var{out} or
  1081. length @var{outsize} takes place. With @var{in} being not @code{NULL},
  1082. @var{inlen} bytes are encrypted to the buffer @var{out} which must have
  1083. at least a size of @var{inlen}. @var{outlen} must be set to the
  1084. allocated size of @var{out}, so that the function can check that there
  1085. is sufficient space. Note, that overlapping buffers are not allowed.
  1086. Depending on the selected algorithms and encryption mode, the length of
  1087. the buffers must be a multiple of the block size.
  1088. The function returns @code{0} on success or an error code.
  1089. @end deftypefun
  1090. @deftypefun gcry_error_t gcry_cipher_decrypt (gcry_cipher_hd_t @var{h}, void *{out}, size_t @var{outsize}, const void *@var{in}, size_t @var{inlen})
  1091. @code{gcry_cipher_decrypt} is used to decrypt the data. This function
  1092. can either work in place or with two buffers. It uses the cipher
  1093. context already setup and described by the handle @var{h}. There are 2
  1094. ways to use the function: If @var{in} is passed as @code{NULL} and
  1095. @var{inlen} is @code{0}, in-place decryption of the data in @var{out} or
  1096. length @var{outsize} takes place. With @var{in} being not @code{NULL},
  1097. @var{inlen} bytes are decrypted to the buffer @var{out} which must have
  1098. at least a size of @var{inlen}. @var{outlen} must be set to the
  1099. allocated size of @var{out}, so that the function can check that there
  1100. is sufficient space. Note, that overlapping buffers are not allowed.
  1101. Depending on the selected algorithms and encryption mode, the length of
  1102. the buffers must be a multiple of the block size.
  1103. The function returns @code{0} on success or an error code.
  1104. @end deftypefun
  1105. OpenPGP (as defined in RFC-2440) requires a special sync operation in
  1106. some places, the following function is used for this:
  1107. @deftypefun gcry_error_t gcry_cipher_sync (gcry_cipher_hd_t @var{h})
  1108. Perform the OpenPGP sync operation on context @var{h}. Note, that this
  1109. is a no-op unless the context was created with the flag
  1110. @code{GCRY_CIPHER_ENABLE_SYNC}
  1111. @end deftypefun
  1112. Some of the described functions are implemented as macros utilizing a
  1113. catch-all control function. This control function is rarely used
  1114. directly but there is nothing which would inhibit it:
  1115. @deftypefun gcry_error_t gcry_cipher_ctl (gcry_cipher_hd_t @var{h}, int @var{cmd}, void *@var{buffer}, size_t @var{buflen})
  1116. @code{gcry_cipher_ctl} controls various aspects of the cipher module and
  1117. specific cipher contexts. Usually some more specialized functions or
  1118. macros are used for this purpose. The semantics of the function and its
  1119. parameters depends on the the command @var{cmd} and the passed context
  1120. handle @var{h}. Please see the comments in the source code
  1121. (@code{src/global.c}) for details.
  1122. @end deftypefun
  1123. @deftypefun gcry_error_t gcry_cipher_info (gcry_cipher_hd_t @var{h}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes})
  1124. @code{gcry_cipher_info} is used to retrieve various
  1125. information about a cipher context or the cipher module in general.
  1126. Currently no information is available.
  1127. @end deftypefun
  1128. @node General cipher functions
  1129. @section General cipher functions
  1130. To work with the algorithms, several functions are available to map
  1131. algorithm names to the internal identifiers, as well as ways to
  1132. retrieve information about an algorithm or the current cipher context.
  1133. @deftypefun gcry_error_t gcry_cipher_algo_info (int @var{algo}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes})
  1134. This function is used to retrieve information on a specific algorithm.
  1135. You pass the cipher algorithm ID as @var{algo} and the type of
  1136. information requested as @var{what}. The result is either returned as
  1137. the return code of the function or copied to the provided @var{buffer}
  1138. whose allocated length must be available in an integer variable with the
  1139. address passed in @var{nbytes}. This variable will also receive the
  1140. actual used length of the buffer.
  1141. Here is a list of supported codes for @var{what}:
  1142. @c begin constants for gcry_cipher_algo_info
  1143. @table @code
  1144. @item GCRYCTL_GET_KEYLEN:
  1145. Return the length of the key. If the algorithm supports multiple key
  1146. lengths, the maximum supported value is returned. The length is
  1147. returned as number of octets (bytes) and not as number of bits in
  1148. @var{nbytes}; @var{buffer} must be zero.
  1149. @item GCRYCTL_GET_BLKLEN:
  1150. Return the block length of the algorithm. The length is returned as a
  1151. number of octets in @var{nbytes}; @var{buffer} must be zero.
  1152. @item GCRYCTL_TEST_ALGO:
  1153. Returns @code{0} when the specified algorithm is available for use.
  1154. @var{buffer} and @var{nbytes} must be zero.
  1155. @end table
  1156. @c end constants for gcry_cipher_algo_info
  1157. @end deftypefun
  1158. @c end gcry_cipher_algo_info
  1159. @deftypefun const char *gcry_cipher_algo_name (int @var{algo})
  1160. @code{gcry_cipher_algo_name} returns a string with the name of the
  1161. cipher algorithm @var{algo}. If the algorithm is not known or another
  1162. error occurred, an empty string is returned. This function will never
  1163. return @code{NULL}.
  1164. @end deftypefun
  1165. @deftypefun int gcry_cipher_map_name (const char *@var{name})
  1166. @code{gcry_cipher_map_name} returns the algorithm identifier for the
  1167. cipher algorithm described by the string @var{name}. If this algorithm
  1168. is not available @code{0} is returned.
  1169. @end deftypefun
  1170. @deftypefun int gcry_cipher_mode_from_oid (const char *@var{string})
  1171. Return the cipher mode associated with an @acronym{ASN.1} object
  1172. identifier. The object identifier is expected to be in the
  1173. @acronym{IETF}-style dotted decimal notation. The function returns
  1174. @code{0} for an unknown object identifier or when no mode is associated
  1175. with it.
  1176. @end deftypefun
  1177. @c **********************************************************
  1178. @c ******************* Hash Functions *********************
  1179. @c **********************************************************
  1180. @node Hashing
  1181. @chapter Hashing
  1182. @acronym{Libgcrypt} provides an easy and consistent to use interface
  1183. for hashing. Hashing is buffered and several hash algorithms can be
  1184. updated at once. It is possible to calculate a MAC using the same
  1185. routines. The programming model follows an open/process/close
  1186. paradigm and is in that similar to other building blocks provided by
  1187. @acronym{Libgcrypt}.
  1188. For convenience reasons, a few cyclic redundancy check value operations
  1189. are also supported.
  1190. @menu
  1191. * Available hash algorithms:: List of hash algorithms supported by the library.
  1192. * Hash algorithm modules:: How to work with hash algorithm modules.
  1193. * Working with hash algorithms:: List of functions related to hashing.
  1194. @end menu
  1195. @node Available hash algorithms
  1196. @section Available hash algorithms
  1197. @c begin table of hash algorithms
  1198. @table @code
  1199. @item GCRY_MD_NONE
  1200. This is not a real algorithm but used by some functions as an error
  1201. return value. This constant is guaranteed to have the value @code{0}.
  1202. @item GCRY_MD_SHA1
  1203. This is the SHA-1 algorithm which yields a message digest of 20 bytes.
  1204. @item GCRY_MD_RMD160
  1205. This is the 160 bit version of the RIPE message digest (RIPE-MD-160).
  1206. Like SHA-1 it also yields a digest of 20 bytes.
  1207. @item GCRY_MD_MD5
  1208. This is the well known MD5 algorithm, which yields a message digest of
  1209. 16 bytes.
  1210. @item GCRY_MD_MD4
  1211. This is the MD4 algorithm, which yields a message digest of 16 bytes.
  1212. @item GCRY_MD_MD2
  1213. This is an reserved identifier for MD-2; there is no implementation yet.
  1214. @item GCRY_MD_TIGER
  1215. This is the TIGER/192 algorithm which yields a message digest of 24 bytes.
  1216. @item GCRY_MD_HAVAL
  1217. This is an reserved for the HAVAL algorithm with 5 passes and 160
  1218. bit. It yields a message digest of 20 bytes. Note that there is no
  1219. implementation yet available.
  1220. @item GCRY_MD_SHA256
  1221. This is the SHA-256 algorithm which yields a message digest of 32 bytes.
  1222. See FIPS 180-2 for the specification.
  1223. @item GCRY_MD_SHA384
  1224. This is reserved for SHA-2 with 384 bits. It yields a message digest of
  1225. 48 bytes. Note that there is no implementation yet available.
  1226. @item GCRY_MD_SHA512
  1227. This is reserved for SHA-2 with 512 bits. It yields a message digest of
  1228. 64 bytes. Note that there is no implementation yet available.
  1229. @item GCRY_MD_CRC32
  1230. This is the ISO 3309 and ITU-T V.42 cyclic redundancy check. It
  1231. yields an output of 4 bytes.
  1232. @item GCRY_MD_CRC32_RFC1510
  1233. This is the above cyclic redundancy check function, as modified by RFC
  1234. 1510. It yields an output of 4 bytes.
  1235. @item GCRY_MD_CRC24_RFC2440
  1236. This is the OpenPGP cyclic redundancy check function. It yields an
  1237. output of 3 bytes.
  1238. @end table
  1239. @c end table of hash algorithms
  1240. @node Hash algorithm modules
  1241. @section Hash algorithm modules
  1242. @acronym{Libgcrypt} makes it possible to load additional `message
  1243. digest modules'; these cipher can be used just like the message digest
  1244. algorithms that are built into the library directly. For an
  1245. introduction into extension modules, see @xref{Modules}.
  1246. @deftp {Data type} gcry_md_spec_t
  1247. This is the `module specification structure' needed for registering
  1248. message digest modules, which has to be filled in by the user before
  1249. it can be used to register a module. It contains the following
  1250. members:
  1251. @table @code
  1252. @item const char *name
  1253. The primary name of this algorithm.
  1254. @item unsigned char *asnoid
  1255. Array of bytes that form the ASN OID.
  1256. @item int asnlen
  1257. Length of bytes in `asnoid'.
  1258. @item gcry_md_oid_spec_t *oids
  1259. A list of OIDs that are to be associated with the algorithm. The
  1260. list's last element must have it's `oid' member set to NULL. See
  1261. below for an explanation of this type. See below for an explanation
  1262. of this type.
  1263. @item int mdlen
  1264. Length of the message digest algorithm. See below for an explanation
  1265. of this type.
  1266. @item gcry_md_init_t init
  1267. The function responsible for initializing a handle. See below for an
  1268. explanation of this type.
  1269. @item gcry_md_write_t write
  1270. The function responsible for writing data into a message digest
  1271. context. See below for an explanation of this type.
  1272. @item gcry_md_final_t final
  1273. The function responsible for `finalizing' a message digest context.
  1274. See below for an explanation of this type.
  1275. @item gcry_md_read_t read
  1276. The function responsible for reading out a message digest result. See
  1277. below for an explanation of this type.
  1278. @item size_t contextsize
  1279. The size of the algorithm-specific `context', that should be
  1280. allocated for each handle.
  1281. @end table
  1282. @end deftp
  1283. @deftp {Data type} gcry_md_oid_spec_t
  1284. This type is used for associating a user-provided algorithm
  1285. implementation with certain OIDs. It contains the following members:
  1286. @table @code
  1287. @item const char *oidstring
  1288. Textual representation of the OID.
  1289. @end table
  1290. @end deftp
  1291. @deftp {Data type} gcry_md_init_t
  1292. Type for the `init' function, defined as: void (*gcry_md_init_t) (void
  1293. *c)
  1294. @end deftp
  1295. @deftp {Data type} gcry_md_write_t
  1296. Type for the `write' function, defined as: void (*gcry_md_write_t)
  1297. (void *c, unsigned char *buf, size_t nbytes)
  1298. @end deftp
  1299. @deftp {Data type} gcry_md_final_t
  1300. Type for the `final' function, defined as: void (*gcry_md_final_t)
  1301. (void *c)
  1302. @end deftp
  1303. @deftp {Data type} gcry_md_read_t
  1304. Type for the `read' function, defined as: unsigned char
  1305. *(*gcry_md_read_t) (void *c)
  1306. @end deftp
  1307. @deftypefun gcry_error_t gcry_md_register (gcry_md_spec_t *@var{digest}, unsigned int *algorithm_id, gcry_module_t *@var{module})
  1308. Register a new digest module whose specification can be found in
  1309. @var{digest}. On success, a new algorithm ID is stored in
  1310. @var{algorithm_id} and a pointer representing this module is stored
  1311. in @var{module}.
  1312. @end deftypefun
  1313. @deftypefun void gcry_md_unregister (gcry_module_t @var{module})
  1314. Unregister the digest identified by @var{module}, which must have been
  1315. registered with gcry_md_register.
  1316. @end deftypefun
  1317. @deftypefun gcry_error_t gcry_md_list (int *@var{list}, int *@var{list_length})
  1318. Get a list consisting of the IDs of the loaded message digest modules.
  1319. If @var{list} is zero, write the number of loaded message digest
  1320. modules to @var{list_length} and return. If @var{list} is non-zero,
  1321. the first *@var{list_length} algorithm IDs are stored in @var{list},
  1322. which must be of according size. In case there are less message
  1323. digests modules than *@var{list_length}, *@var{list_length} is updated
  1324. to the correct number.
  1325. @end deftypefun
  1326. @node Working with hash algorithms
  1327. @section Working with hash algorithms
  1328. To use most of these function it is necessary to create a context;
  1329. this is done using:
  1330. @deftypefun gcry_error_t gcry_md_open (gcry_md_hd_t *@var{hd}, int @var{algo}, unsigned int @var{flags})
  1331. Create a message digest object for algorithm @var{algo}. @var{flags}
  1332. may be given as an bitwise OR of constants described below. @var{algo}
  1333. may be given as @code{0} if the algorithms to use are later set using
  1334. @code{gcry_md_enable}. @var{hd} is guaranteed to either receive a valid
  1335. handle or NULL.
  1336. For a list of supported algorithms, see @xref{Available hash
  1337. algorithms}.
  1338. The flags allowed for @var{mode} are:
  1339. @c begin table of hash flags
  1340. @table @code
  1341. @item GCRY_MD_FLAG_SECURE
  1342. Allocate all buffers and the resulting digest in "secure memory". Use
  1343. this is the hashed data is highly confidential.
  1344. @item GCRY_MD_FLAG_HMAC
  1345. Turn the algorithm into a HMAC message authentication algorithm. This
  1346. does only work if just one algorithm is enabled for the handle and
  1347. SHA-384 and SHA512 is not used. Note that the function
  1348. @code{gcry_md_setkey} must be used set the MAC key. If you want CBC
  1349. message authentication codes based on a cipher, see @xref{Working with
  1350. cipher handles}.
  1351. @end table
  1352. @c begin table of hash flags
  1353. You may use the function @code{gcry_md_is_enabled} to later check
  1354. whether an algorithm has been enabled.
  1355. @end deftypefun
  1356. @c end function gcry_md_open
  1357. If you want to calculate several hash algorithms at the same time, you
  1358. have to use the following function right after the @code{gcry_md_open}:
  1359. @deftypefun gcry_error_t gcry_md_enable (gcry_md_hd_t @var{h}, int @var{algo})
  1360. Add the message digest algorithm @var{algo} to the digest object
  1361. described by handle @var{h}. Duplicated enabling of algorithms is
  1362. detected and ignored.
  1363. @end deftypefun
  1364. If the flag @code{GCRY_MD_FLAG_HMAC} was used, the key for the MAC must
  1365. be set using the function:
  1366. @deftypefun gcry_error_t gcry_md_setkey (gcry_md_hd_t @var{h}, const void *@var{key}, size_t @var{keylen})
  1367. For use with the HMAC feature, set the MAC key to the value of @var{key}
  1368. of length @var{keylen}.
  1369. @end deftypefun
  1370. After you are done with the hash calculation, you should release the
  1371. resources by using:
  1372. @deftypefun void gcry_md_close (gcry_md_hd_t @var{h})
  1373. Release all resources of hash context @var{h}. @var{h} should not be
  1374. used after a call to this function. A @code{NULL} passed as @var{h} is
  1375. ignored.
  1376. @end deftypefun
  1377. Often you have to do several hash operations using the same algorithm.
  1378. To avoid the overhead of creating and releasing context, a reset function
  1379. is provided:
  1380. @deftypefun void gcry_md_reset (gcry_md_hd_t @var{h})
  1381. Reset the current context to its initial state. This is effectively
  1382. identical to a close followed by an open and enabling all currently
  1383. active algorithms.
  1384. @end deftypefun
  1385. Often it is necessary to start hashing some data and than continue to
  1386. hash different data. To avoid hashing the same data several times (which
  1387. might not even be possible if the data is received from a pipe), a
  1388. snapshot of the current hash context can be taken and turned into a new
  1389. context:
  1390. @deftypefun gcry_error_t gcry_md_copy (gcry_md_hd_t *@var{handle_dst}, gcry_md_hd_t @var{handle_src})
  1391. Create a new digest object as an exact copy of the object described by
  1392. handle @var{handle_src} and store it in @var{handle_dst}. The context
  1393. is not reset and you can continue to hash data using this context and
  1394. independently using the original context.
  1395. @end deftypefun
  1396. Now that we have prepared everything to calculate hashes, its time to
  1397. see how it is actually done. There are 2 ways for this, one to
  1398. update the hash with a block of memory and one macro to update the hash
  1399. by just one character. Both may be used intermixed.
  1400. @deftypefun void gcry_md_write (gcry_md_hd_t @var{h}, const void *@var{buffer}, size_t @var{length})
  1401. Pass @var{length} bytes of the data in @var{buffer} to the digest object
  1402. with handle @var{h} to update the digest values. This
  1403. function should be used for large blocks of data.
  1404. @end deftypefun
  1405. @deftypefun void gcry_md_putc (gcry_md_hd_t @var{h}, int @var{c})
  1406. Pass the byte in @var{c} to the digest object with handle @var{h} to
  1407. update the digest value. This is an efficient function, implemented as
  1408. a macro to buffer the data before an actual update.
  1409. @end deftypefun
  1410. The semantics of the hash functions don't allow to read out intermediate
  1411. message digests because the calculation must be finalized fist. This
  1412. finalization may for example include the number of bytes hashed in the
  1413. message digest.
  1414. @deftypefun void gcry_md_final (gcry_md_hd_t @var{h})
  1415. Finalize the message digest calculation. This is not really needed
  1416. because @code{gcry_md_read} does this implicitly. After this has been
  1417. done no further updates (by means of @code{gcry_md_write} or
  1418. @code{gcry_md_putc} are allowed. Only the first call to this function
  1419. has an effect. It is implemented as a macro.
  1420. @end deftypefun
  1421. The way to read out the calculated message digest is by using the
  1422. function:
  1423. @deftypefun unsigned char *gcry_md_read (gcry_md_hd_t @var{h}, int @var{algo})
  1424. @code{gcry_md_read} returns the message digest after finalizing the
  1425. calculation. This function may be used as often as required but it will
  1426. always return the same value for one handle. The returned message digest
  1427. is allocated within the message context and therefore valid until the
  1428. handle is released or reseted (using @code{gcry_md_close} or
  1429. @code{gcry_md_reset}. @var{algo} may be given as 0 to return the only
  1430. enabled message digest or it may specify one of the enabled algorithms.
  1431. The function does return @code{NULL} if the requested algorithm has not
  1432. been enabled.
  1433. @end deftypefun
  1434. Because it is often necessary to get the message digest of one block of
  1435. memory, a fast convenience function is available for this task:
  1436. @deftypefun void gcry_md_hash_buffer (int @var{algo}, void *@var{digest}, const cvoid *@var{buffer}, size_t @var{length});
  1437. @code{gcry_md_hash_buffer} is a shortcut function to calculate a message
  1438. digest of a buffer. This function does not require a context and
  1439. immediately returns the message digest of the @var{length} bytes at
  1440. @var{buffer}. @var{digest} must be allocated by the caller, large
  1441. enough to hold the message digest yielded by the the specified algorithm
  1442. @var{algo}. This required size may be obtained by using the function
  1443. @code{gcry_md_get_algo_dlen}.
  1444. Note, that this function will abort the process if an unavailable
  1445. algorithm is used.
  1446. @end deftypefun
  1447. @c ***********************************
  1448. @c ***** MD info functions ***********
  1449. @c ***********************************
  1450. Hash algorithms are identified by internal algorithm numbers (see
  1451. @code{gcry_md_open} for a list. However, in most applications they are
  1452. used by names, so 2 functions are available to map between string
  1453. representations and hash algorithm identifiers.
  1454. @deftypefun const char *gcry_md_algo_name (int @var{algo})
  1455. Map the digest algorithm id @var{algo} to a string representation of the
  1456. algorithm name. For unknown algorithms this functions returns an
  1457. empty string. This function should not be used to test for the
  1458. availability of an algorithm.
  1459. @end deftypefun
  1460. @deftypefun int gcry_md_map_name (const char *@var{name})
  1461. Map the algorithm with @var{name} to a digest algorithm identifier.
  1462. Returns 0 if the algorithm name is not known. Names representing
  1463. @acronym{ASN.1} object identifiers are recognized if the @acronym{IETF}
  1464. dotted format is used and the OID is prefixed with either "@code{oid.}"
  1465. or "@code{OID.}". For a list of supported OIDs, see the source code at
  1466. @file{cipher/md.c}. This function should not be used to test for the
  1467. availability of an algorithm.
  1468. @end deftypefun
  1469. @deftypefun gcry_error_t gcry_md_get_asnoid (int @var{algo}, void *@var{buffer}, size_t *@var{length})
  1470. Return an DER encoded ASN.1 OID for the algorithm @var{algo} in the
  1471. user allocated @var{buffer}. @var{length} must point to variable with
  1472. the available size of @var{buffer} and receives after return the
  1473. actual size of the returned OID. The returned error code may be
  1474. @code{GPG_ERR_TOO_SHORT} if the provided buffer is to short to receive
  1475. the OID; it is possible to call the function with @code{NULL} for
  1476. @var{buffer} to have it only return the required size. The function
  1477. returns 0 on success.
  1478. @end deftypefun
  1479. To test whether an algorithm is actually available for use, the
  1480. following macro should be used:
  1481. @deftypefun gcry_error_t gcry_md_test_algo (int @var{algo})
  1482. The macro returns 0 if the algorithm @var{algo} is available for use.
  1483. @end deftypefun
  1484. If the length of a message digest is not known, it can be retrieved
  1485. using the following function:
  1486. @deftypefun unsigned int gcry_md_get_algo_dlen (int @var{algo})
  1487. Retrieve the length in bytes of the digest yielded by algorithm
  1488. @var{algo}. This is often used prior to @code{gcry_md_read} to allocate
  1489. sufficient memory for the digest.
  1490. @end deftypefun
  1491. In some situations it might be hard to remember the algorithm used for
  1492. the ongoing hashing. The following function might be used to get that
  1493. information:
  1494. @deftypefun int gcry_md_get_algo (gcry_md_hd_t @var{h})
  1495. Retrieve the algorithm used with the handle @var{h}. Note, that this
  1496. does not work reliable if more than one algorithm is enabled in @var{h}.
  1497. @end deftypefun
  1498. The following macro might also be useful:
  1499. @deftypefun int gcry_md_is_secure (gcry_md_hd_t @var{h})
  1500. This function returns true when the digest object @var{h} is allocated
  1501. in "secure memory"; i.e. @var{h} was created with the
  1502. @code{GCRY_MD_FLAG_SECURE}.
  1503. @end deftypefun
  1504. @deftypefun int gcry_md_is_enabled (gcry_md_hd_t @var{h}, int @var{algo})
  1505. This function returns true when the algorithm @var{algo} has been
  1506. enabled for the digest object @var{h}.
  1507. @end deftypefun
  1508. Tracking bugs related to hashing is often a cumbersome task which
  1509. requires to add a lot of printf statements into the code. @acronym{Libgcrypt}
  1510. provides an easy way to avoid this. The actual data hashed can be
  1511. written to files on request. The following 2 macros should be used to
  1512. implement such a debugging facility:
  1513. @deftypefun void gcry_md_start_debug (gcry_md_hd_t @var{h}, const char *@var{suffix})
  1514. Enable debugging for the digest object with handle @var{h}. This
  1515. creates create files named @file{dbgmd-<n>.<string>} while doing the
  1516. actual hashing. @var{suffix} is the string part in the filename. The
  1517. number is a counter incremented for each new hashing. The data in the
  1518. file is the raw data as passed to @code{gcry_md_write} or
  1519. @code{gcry_md_putc}.
  1520. @end deftypefun
  1521. @deftypefun void gcry_md_stop_debug (gcry_md_hd_t @var{h}, int @var{reserved})
  1522. Stop debugging on handle @var{h}. @var{reserved} should be specified as
  1523. 0. This function is usually not required because @code{gcry_md_close}
  1524. does implicitly stop debugging.
  1525. @end deftypefun
  1526. @c **********************************************************
  1527. @c ******************* Public Key *************************
  1528. @c **********************************************************
  1529. @node Public Key cryptography (I)
  1530. @chapter Public Key cryptography (I)
  1531. Public key cryptography, also known as asymmetric cryptography, is an
  1532. easy way for key management and to provide digital signatures.
  1533. @acronym{Libgcrypt} provides two completely different interfaces to
  1534. public key cryptography, this chapter explains the one based on
  1535. S-expressions.
  1536. @menu
  1537. * Available algorithms:: Algorithms supported by the library.
  1538. * Used S-expressions:: Introduction into the used S-expression.
  1539. * Public key modules:: How to work with public key modules.
  1540. * Cryptographic Functions:: Functions for performing the cryptographic actions.
  1541. * General public-key related Functions:: General functions, not implementing any cryptography.
  1542. @end menu
  1543. @node Available algorithms
  1544. @section Available algorithms
  1545. @acronym{Libgcrypt} supports the RSA (Rivest-Shamir-Adleman) algorithms as well
  1546. as DSA (Digital Signature Algorithm) and ElGamal. The versatile
  1547. interface allows to add more algorithms in the future.
  1548. @node Used S-expressions
  1549. @section Used S-expressions
  1550. @acronym{Libgcrypt}'s API for asymmetric cryptography is based on data
  1551. structures called S-expressions (see XXXX) and does not work with
  1552. contexts as most of the other building blocks of @acronym{Libgcrypt}
  1553. do.
  1554. The following information are stored in S-expressions:
  1555. @table @asis
  1556. @item keys
  1557. @item plain text data
  1558. @item encrypted data
  1559. @item signatures
  1560. @end table
  1561. @noindent
  1562. To describe how @acronym{Libgcrypt} expect keys, we use some examples. Note that
  1563. words in
  1564. @ifnottex
  1565. uppercase
  1566. @end ifnottex
  1567. @iftex
  1568. italics
  1569. @end iftex
  1570. indicate parameters whereas lowercase words are literals.
  1571. @example
  1572. (private-key
  1573. (dsa
  1574. (p @var{p-mpi})
  1575. (q @var{q-mpi})
  1576. (g @var{g-mpi})
  1577. (y @var{y-mpi})
  1578. (x @var{x-mpi})))
  1579. @end example
  1580. @noindent
  1581. This specifies a DSA private key with the following parameters:
  1582. @table @var
  1583. @item p-mpi
  1584. DSA prime @math{p}.
  1585. @item q-mpi
  1586. DSA group order @math{q} (which is a prime divisor of @math{p-1}).
  1587. @item g-mpi
  1588. DSA group generator @math{g}.
  1589. @item y-mpi
  1590. DSA public key value @math{y = g^x \bmod p}.
  1591. @item x-mpi
  1592. DSA secret exponent x.
  1593. @end table
  1594. All the MPI values are expected to be in @code{GCRYMPI_FMT_USG} format.
  1595. The public key is similar with "private-key" replaced by "public-key"
  1596. and no @var{x-mpi}.
  1597. An easy way to create such an S-expressions is by using
  1598. @code{gcry_sexp_build} which allows to pass a string with printf-like
  1599. escapes to insert MPI values.
  1600. @noindent
  1601. Here is an example for an RSA key:
  1602. @example
  1603. (private-key
  1604. (rsa
  1605. (n @var{n-mpi})
  1606. (e @var{e-mpi})
  1607. (d @var{d-mpi})
  1608. (p @var{p-mpi})
  1609. (q @var{q-mpi})
  1610. (u @var{u-mpi})
  1611. @end example
  1612. @noindent
  1613. with
  1614. @table @var
  1615. @item n-mpi
  1616. RSA public modulus @math{n}.
  1617. @item e-mpi
  1618. RSA public exponent @math{e}.
  1619. @item d-mpi
  1620. RSA secret exponent @math{d = e^{-1} \bmod (p-1)(q-1)}.
  1621. @item p-mpi
  1622. RSA secret prime @math{p}.
  1623. @item q-mpi
  1624. RSA secret prime @math{q} with @math{q > p}.
  1625. @item u-mpi
  1626. multiplicative inverse @math{u = p^{-1} \bmod q}.
  1627. @end table
  1628. @node Public key modules
  1629. @section Public key modules
  1630. @acronym{Libgcrypt} makes it possible to load additional `public key
  1631. modules'; these public key algorithms can be used just like the
  1632. algorithms that are built into the library directly. For an
  1633. introduction into extension modules, see @xref{Modules}.
  1634. @deftp {Data type} gcry_pk_spec_t
  1635. This is the `module specification structure' needed for registering
  1636. public key modules, which has to be filled in by the user before it
  1637. can be used to register a module. It contains the following members:
  1638. @table @code
  1639. @item const char *name
  1640. The primary name of this algorithm.
  1641. @item char **aliases
  1642. A list of strings that are `aliases' for the algorithm. The list
  1643. must be terminated with a NULL element.
  1644. @item const char *elements_pkey
  1645. String containing the one-letter names of the MPI values contained in
  1646. a public key.
  1647. @item const char *element_skey
  1648. String containing the one-letter names of the MPI values contained in
  1649. a secret key.
  1650. @item const char *elements_enc
  1651. String containing the one-letter names of the MPI values that are the
  1652. result of an encryption operation using this algorithm.
  1653. @item const char *elements_sig
  1654. String containing the one-letter names of the MPI values that are the
  1655. result of a sign operation using this algorithm.
  1656. @item const char *elements_grip
  1657. String containing the one-letter names of the MPI values that are to
  1658. be included in the `key grip'.
  1659. @item int use
  1660. The bitwise-OR of the following flags, depending on the abilities of
  1661. the algorithm:
  1662. @table @code
  1663. @item GCRY_PK_USAGE_SIGN
  1664. The algorithm supports signing and verifying of data.
  1665. @item GCRY_PK_USAGE_ENCR
  1666. The algorithm supports the encryption and decryption of data.
  1667. @end table
  1668. @item gcry_pk_generate_t generate
  1669. The function responsible for generating a new key pair. See below for
  1670. a description of this type.
  1671. @item gcry_pk_check_secret_key_t check_secret_key
  1672. The function responsible for checking the sanity of a provided secret
  1673. key. See below for a description of this type.
  1674. @item gcry_pk_encrypt_t encrypt
  1675. The function responsible for encrypting data. See below for a
  1676. description of this type.
  1677. @item gcry_pk_decrypt_t decrypt
  1678. The function responsible for decrypting data. See below for a
  1679. description of this type.
  1680. @item gcry_pk_sign_t sign
  1681. The function responsible for signing data. See below for a description
  1682. of this type.
  1683. @item gcry_pk_verify_t verify
  1684. The function responsible for verifying that the provided signature
  1685. matches the provided data. See below for a description of this type.
  1686. @item gcry_pk_get_nbits_t get_nbits
  1687. The function responsible for returning the number of bits of a provided
  1688. key. See below for a description of this type.
  1689. @end table
  1690. @end deftp
  1691. @deftp {Data type} gcry_pk_generate_t
  1692. Type for the `generate' function, defined as: gcry_err_code_t
  1693. (*gcry_pk_generate_t) (int algo, unsigned int nbits, unsigned long
  1694. use_e, gcry_mpi_t *skey, gcry_mpi_t **retfactors)
  1695. @end deftp
  1696. @deftp {Data type} gcry_pk_check_secret_key_t
  1697. Type for the `check_secret_key' function, defined as: gcry_err_code_t
  1698. (*gcry_pk_check_secret_key_t) (int algo, gcry_mpi_t *skey)
  1699. @end deftp
  1700. @deftp {Data type} gcry_pk_encrypt_t
  1701. Type for the `encrypt' function, defined as: gcry_err_code_t
  1702. (*gcry_pk_encrypt_t) (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
  1703. gcry_mpi_t *pkey, int flags)
  1704. @end deftp
  1705. @deftp {Data type} gcry_pk_decrypt_t
  1706. Type for the `decrypt' function, defined as: gcry_err_code_t
  1707. (*gcry_pk_decrypt_t) (int algo, gcry_mpi_t *result, gcry_mpi_t *data,
  1708. gcry_mpi_t *skey, int flags)
  1709. @end deftp
  1710. @deftp {Data type} gcry_pk_sign_t
  1711. Type for the `sign' function, defined as: gcry_err_code_t
  1712. (*gcry_pk_sign_t) (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
  1713. gcry_mpi_t *skey)
  1714. @end deftp
  1715. @deftp {Data type} gcry_pk_verify_t
  1716. Type for the `verify' function, defined as: gcry_err_code_t
  1717. (*gcry_pk_verify_t) (int algo, gcry_mpi_t hash, gcry_mpi_t *data,
  1718. gcry_mpi_t *pkey, int (*cmp) (void *, gcry_mpi_t), void *opaquev)
  1719. @end deftp
  1720. @deftp {Data type} gcry_pk_get_nbits_t
  1721. Type for the `get_nbits' function, defined as: unsigned
  1722. (*gcry_pk_get_nbits_t) (int algo, gcry_mpi_t *pkey)
  1723. @end deftp
  1724. @deftypefun gcry_error_t gcry_pk_register (gcry_pk_spec_t *@var{pubkey}, unsigned int *algorithm_id, gcry_module_t *@var{module})
  1725. Register a new public key module whose specification can be found in
  1726. @var{pubkey}. On success, a new algorithm ID is stored in
  1727. @var{algorithm_id} and a pointer representing this module is stored
  1728. in @var{module}.
  1729. @end deftypefun
  1730. @deftypefun void gcry_pk_unregister (gcry_module_t @var{module})
  1731. Unregister the public key module identified by @var{module}, which
  1732. must have been registered with gcry_pk_register.
  1733. @end deftypefun
  1734. @deftypefun gcry_error_t gcry_pk_list (int *@var{list}, int *@var{list_length})
  1735. Get a list consisting of the IDs of the loaded pubkey modules. If
  1736. @var{list} is zero, write the number of loaded pubkey modules to
  1737. @var{list_length} and return. If @var{list} is non-zero, the first
  1738. *@var{list_length} algorithm IDs are stored in @var{list}, which must
  1739. be of according size. In case there are less pubkey modules than
  1740. *@var{list_length}, *@var{list_length} is updated to the correct
  1741. number.
  1742. @end deftypefun
  1743. @node Cryptographic Functions
  1744. @section Cryptographic Functions
  1745. @noindent
  1746. Note, that we will in future allow to use keys without p,q and u
  1747. specified and may also support other parameters for performance
  1748. reasons.
  1749. @noindent
  1750. Some functions operating on S-expressions support `flags', that
  1751. influence the operation. These flags have to be listed in a
  1752. sub-S-expression named `flags'; the following flags are known:
  1753. @table @var
  1754. @item pkcs1
  1755. Use PKCS#1 block type 2 padding.
  1756. @item no-blinding
  1757. Do not use a technique called `blinding', which is used by default in
  1758. order to prevent leaking of secret information. Blinding is only
  1759. implemented by RSA, but it might be implemented by other algorithms in
  1760. the future as well, when necessary.
  1761. @end table
  1762. @noindent
  1763. Now that we know the key basics, we can carry on and explain how to
  1764. encrypt and decrypt data. In almost all cases the data is a random
  1765. session key which is in turn used for the actual encryption of the real
  1766. data. There are 2 functions to do this:
  1767. @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}})
  1768. Obviously a public key must be provided for encryption. It is
  1769. expected as an appropriate S-expression (see above) in @var{pkey}.
  1770. The data to be encrypted can either be in the simple old format, which
  1771. is a very simple S-expression consisting only of one MPI, or it may be
  1772. a more complex S-expression which also allows to specify flags for
  1773. operation, like e.g. padding rules.
  1774. @noindent
  1775. If you don't want to let @acronym{Libgcrypt} handle the padding, you must pass an
  1776. appropriate MPI using this expression for @var{data}:
  1777. @example
  1778. (data
  1779. (flags raw)
  1780. (value @var{mpi}))
  1781. @end example
  1782. @noindent
  1783. This has the same semantics as the old style MPI only way. @var{MPI} is
  1784. the actual data, already padded appropriate for your protocol. Most
  1785. systems however use PKCS#1 padding and so you can use this S-expression
  1786. for @var{data}:
  1787. @example
  1788. (data
  1789. (flags pkcs1)
  1790. (value @var{block}))
  1791. @end example
  1792. @noindent
  1793. Here, the "flags" list has the "pkcs1" flag which let the function know
  1794. that it should provide PKCS#1 block type 2 padding. The actual data to
  1795. be encrypted is passed as a string of octets in @var{block}. The
  1796. function checks that this data actually can be used with the given key,
  1797. does the padding and encrypts it.
  1798. If the function could successfully perform the encryption, the return
  1799. value will be 0 and a a new S-expression with the encrypted result is
  1800. allocated and assign to the variable at the address of @var{r_ciph}.
  1801. The caller is responsible to release this value using
  1802. @code{gcry_sexp_release}. In case of an error, an error code is
  1803. returned and @var{r_ciph} will be set to @code{NULL}.
  1804. @noindent
  1805. The returned S-expression has this format when used with RSA:
  1806. @example
  1807. (enc-val
  1808. (rsa
  1809. (a @var{a-mpi})))
  1810. @end example
  1811. @noindent
  1812. Where @var{a-mpi} is an MPI with the result of the RSA operation. When
  1813. using the ElGamal algorithm, the return value will have this format:
  1814. @example
  1815. (enc-val
  1816. (elg
  1817. (a @var{a-mpi})
  1818. (b @var{b-mpi})))
  1819. @end example
  1820. @noindent
  1821. Where @var{a-mpi} and @var{b-mpi} are MPIs with the result of the
  1822. ElGamal encryption operation.
  1823. @end deftypefun
  1824. @c end gcry_pk_encrypt
  1825. @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}})
  1826. Obviously a private key must be provided for decryption. It is expected
  1827. as an appropriate S-expression (see above) in @var{skey}. The data to
  1828. be decrypted must match the format of the result as returned by
  1829. @code{gcry_pk_encrypt}, but should be enlarged with a @code{flags}
  1830. element:
  1831. @example
  1832. (enc-val
  1833. (flags)
  1834. (elg
  1835. (a @var{a-mpi})
  1836. (b @var{b-mpi})))
  1837. @end example
  1838. @noindent
  1839. Note, that this function currently does not know of any padding
  1840. methods and the caller must do any un-padding on his own.
  1841. @noindent
  1842. The function returns 0 on success or an error code. The variable at the
  1843. address of @var{r_plain} will be set to NULL on error or receive the
  1844. decrypted value on success. The format of @var{r_plain} is a
  1845. simple S-expression part (i.e. not a valid one) with just one MPI if
  1846. there was no @code{flags} element in @var{data}; if at least an empty
  1847. @code{flags} is passed in @var{data}, the format is:
  1848. @example
  1849. (value @var{plaintext})
  1850. @end example
  1851. @end deftypefun
  1852. @c end gcry_pk_decrypt
  1853. Another operation commonly performed using public key cryptography is
  1854. signing data. In some sense this is even more important than
  1855. encryption because digital signatures are an important instrument for
  1856. key management. @acronym{Libgcrypt} supports digital signatures using
  1857. 2 functions, similar to the encryption functions:
  1858. @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}})
  1859. This function creates a digital signature for @var{data} using the
  1860. private key @var{skey} and place it into the variable at the address of
  1861. @var{r_sig}. @var{data} may either be the simple old style S-expression
  1862. with just one MPI or a modern and more versatile S-expression which
  1863. allows to let @acronym{Libgcrypt} handle padding:
  1864. @example
  1865. (data
  1866. (flags pkcs1)
  1867. (hash @var{hash-algo} @var{block}))
  1868. @end example
  1869. @noindent
  1870. This example requests to sign the data in @var{block} after applying
  1871. PKCS#1 block type 1 style padding. @var{hash-algo} is a string with the
  1872. hash algorithm to be encoded into the signature, this may be any hash
  1873. algorithm name as supported by @acronym{Libgcrypt}. Most likely, this will be
  1874. "sha1", "rmd160" or "md5". It is obvious that the length of @var{block}
  1875. must match the size of that message digests; the function checks that
  1876. this and other constraints are valid.
  1877. @noindent
  1878. If PKCS#1 padding is not required (because the caller does already
  1879. provide a padded value), either the old format or better the following
  1880. format should be used:
  1881. @example
  1882. (data
  1883. (flags raw)
  1884. (value @var{mpi}))
  1885. @end example
  1886. @noindent
  1887. Here, the data to be signed is directly given as an @var{MPI}.
  1888. @noindent
  1889. The signature is returned as a newly allocated S-expression in
  1890. @var{r_sig} using this format for RSA:
  1891. @example
  1892. (sig-val
  1893. (rsa
  1894. (s @var{s-mpi})))
  1895. @end example
  1896. Where @var{s-mpi} is the result of the RSA sign operation. For DSA the
  1897. S-expression returned is:
  1898. @example
  1899. (sig-val
  1900. (dsa
  1901. (r @var{r-mpi})
  1902. (s @var{s-mpi})))
  1903. @end example
  1904. Where @var{r-mpi} and @var{s-mpi} are the result of the DSA sign
  1905. operation. For ElGamal signing (which is slow, yields large numbers
  1906. and probably is not as secure as the other algorithms), the same format is
  1907. used with "elg" replacing "dsa".
  1908. @end deftypefun
  1909. @c end gcry_pk_sign
  1910. @noindent
  1911. The operation most commonly used is definitely the verification of a
  1912. signature. @acronym{Libgcrypt} provides this function:
  1913. @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}})
  1914. This is used to check whether the signature @var{sig} matches the
  1915. @var{data}. The public key @var{pkey} must be provided to perform this
  1916. verification. This function is similar in its parameters to
  1917. @code{gcry_pk_sign} with the exceptions that the public key is used
  1918. instead of the private key and that no signature is created but a
  1919. signature, in a format as created by @code{gcry_pk_sign}, is passed to
  1920. the function in @var{sig}.
  1921. @noindent
  1922. The result is 0 for success (i.e. the data matches the signature), or an
  1923. error code where the most relevant code is @code{GCRYERR_BAD_SIGNATURE}
  1924. to indicate that the signature does not match the provided data.
  1925. @end deftypefun
  1926. @c end gcry_pk_verify
  1927. @node General public-key related Functions
  1928. @section General public-key related Functions
  1929. @noindent
  1930. A couple of utility functions are available to retrieve the length of
  1931. the key, map algorithm identifiers and perform sanity checks:
  1932. @deftypefun {const char *} gcry_pk_algo_name (int @var{algo})
  1933. Map the public key algorithm id @var{algo} to a string representation of
  1934. the algorithm name. For unknown algorithms this functions returns an
  1935. empty string.
  1936. @end deftypefun
  1937. @deftypefun int gcry_pk_map_name (const char *@var{name})
  1938. Map the algorithm @var{name} to a public key algorithm Id. Returns 0 if
  1939. the algorithm name is not known.
  1940. @end deftypefun
  1941. @deftypefun int gcry_pk_test_algo (int @var{algo})
  1942. Return 0 if the public key algorithm @var{algo} is available for use.
  1943. Note, that this is implemented as a macro.
  1944. @end deftypefun
  1945. @deftypefun {unsigned int} gcry_pk_get_nbits (gcry_sexp_t @var{key})
  1946. Return what is commonly referred as the key length for the given
  1947. public or private in @var{key}.
  1948. @end deftypefun
  1949. @deftypefun {unsigned char *} gcry_pk_get_keygrip (@w{gcry_sexp_t @var{key}}, @w{unsigned char *@var{array}})
  1950. Return the so called "keygrip" which is the SHA-1 hash of the public key
  1951. parameters expressed in a way depended on the algorithm. @var{array}
  1952. must either provide space for 20 bytes or @code{NULL;}. In the latter
  1953. case a newly allocated array of that size is returned. On success a
  1954. pointer to the newly allocated space or to @var{array} is returned.
  1955. @code{NULL} is returned to indicate an error which is most likely an unknown
  1956. algorithm or one where a "keygrip" has not yet been defined.
  1957. The function accepts public or secret keys in @var{key}.
  1958. @end deftypefun
  1959. @deftypefun gcry_error_t gcry_pk_testkey (gcry_sexp_t @var{key})
  1960. Return zero if the private key @var{key} is `sane', an error code otherwise.
  1961. Note, that it is not possible to chek the `saneness' of a public key.
  1962. @end deftypefun
  1963. @deftypefun int gcry_pk_algo_info (@w{int @var{algo}}, @w{int @var{what}}, @w{void *@var{buffer}}, @w{size_t *@var{nbytes}})
  1964. Depending on the value of @var{what} return various information about
  1965. the public key algorithm with the id @var{algo}. Note, that the
  1966. function returns @code{-1} on error and the actual error code must be
  1967. retrieved using the function @code{gcry_errno}. The currently defined
  1968. values for @var{what} are:
  1969. @table @code
  1970. @item GCRYCTL_TEST_ALGO:
  1971. Return 0 when the specified algorithm is available for use.
  1972. @var{buffer} must be @code{NULL}, @var{nbytes} may be passed as
  1973. @code{NULL} or point to a variable with the required usage of the
  1974. algorithm. This may be 0 for "don't care" or the bit-wise OR of these
  1975. flags:
  1976. @table @code
  1977. @item GCRY_PK_USAGE_SIGN
  1978. Algorithm is usable for signing.
  1979. @item GCRY_PK_USAGE_ENCR
  1980. Algorithm is usable for encryption.
  1981. @end table
  1982. @item GCRYCTL_GET_ALGO_USAGE:
  1983. Return the usage flags for the given algorithm. An invalid algorithm
  1984. return 0. Disabled algorithms are ignored here because we
  1985. want to know whether the algorithm is at all capable of a certain usage.
  1986. @item GCRYCTL_GET_ALGO_NPKEY
  1987. Return the number of elements the public key for algorithm @var{algo}
  1988. consist of. Return 0 for an unknown algorithm.
  1989. @item GCRYCTL_GET_ALGO_NSKEY
  1990. Return the number of elements the private key for algorithm @var{algo}
  1991. consist of. Note that this value is always larger than that of the
  1992. public key. Return 0 for an unknown algorithm.
  1993. @item GCRYCTL_GET_ALGO_NSIGN
  1994. Return the number of elements a signature created with the algorithm
  1995. @var{algo} consists of. Return 0 for an unknown algorithm or for an
  1996. algorithm not capable of creating signatures.
  1997. @item GCRYCTL_GET_ALGO_NENC
  1998. Return the number of elements a encrypted message created with the algorithm
  1999. @var{algo} consists of. Return 0 for an unknown algorithm or for an
  2000. algorithm not capable of encryption.
  2001. @end table
  2002. @noindent
  2003. Please note that parameters not required should be passed as @code{NULL}.
  2004. @end deftypefun
  2005. @c end gcry_pk_algo_info
  2006. @deftypefun gcry_error_t gcry_pk_ctl (@w{int @var{cmd}}, @w{void *@var{buffer}}, @w{size_t @var{buflen}})
  2007. This is a general purpose function to perform certain control
  2008. operations. @var{cmd} controls what is to be done. The return value is
  2009. 0 for success or an error code. Currently supported values for
  2010. @var{cmd} are:
  2011. @table @code
  2012. @item GCRYCTL_DISABLE_ALGO
  2013. Disable the algorithm given as an algorithm id in @var{buffer}.
  2014. @var{buffer} must point to an @code{int} variable with the algorithm id
  2015. and @var{buflen} must have the value @code{sizeof (int)}.
  2016. @end table
  2017. @end deftypefun
  2018. @c end gcry_pk_ctl
  2019. @noindent
  2020. @acronym{Libgcrypt} also provides a function for generating public key
  2021. pairs:
  2022. @deftypefun gcry_error_t gcry_pk_genkey (@w{gcry_sexp_t *@var{r_key}}, @w{gcry_sexp_t @var{parms}})
  2023. This function create a new public key pair using information given in
  2024. the S-expression @var{parms} and stores the private and the public key
  2025. in one new S-expression at the address given by @var{r_key}. In case of
  2026. an error, @var{r_key} is set to @code{NULL}. The return code is 0 for
  2027. success or an error code otherwise.
  2028. @noindent
  2029. Here is an example for @var{parms} for creating a 1024 bit RSA key:
  2030. @example
  2031. (genkey
  2032. (rsa
  2033. (nbits 4:1024)))
  2034. @end example
  2035. @noindent
  2036. To create an ElGamal key, substitute "elg" for "rsa" and to create a DSA
  2037. key use "dsa". Valid ranges for the key length depend on the
  2038. algorithms; all commonly used key lengths are supported. Currently
  2039. supported parameters are:
  2040. @table @code
  2041. @item nbits
  2042. This is always required to specify the length of the key. The argument
  2043. is a string with a number in C-notation.
  2044. @item rsa-use-e
  2045. This is only used with RSA to give a hint for the public exponent. The
  2046. value will be used as a base to test for a usable exponent. Some values
  2047. are special:
  2048. @table @samp
  2049. @item 0
  2050. Use a secure and fast value. This is currently the number 41.
  2051. @item 1
  2052. Use a secure value as required by some specification. This is currently
  2053. the number 65537.
  2054. @item 2
  2055. Reserved
  2056. @end table
  2057. @noindent
  2058. If this parameter is not used, @acronym{Libgcrypt} uses for historic reasons
  2059. 65537.
  2060. @end table
  2061. @c end table of parameters
  2062. @noindent
  2063. The key pair is returned in a format depending on the algorithm. Both
  2064. private and public keys are returned in one container and may be
  2065. accompanied by some miscellaneous information.
  2066. @noindent
  2067. As an example, here is what the ElGamal key generation returns:
  2068. @example
  2069. (key-data
  2070. (public-key
  2071. (elg
  2072. (p @var{p-mpi})
  2073. (g @var{g-mpi})
  2074. (y @var{y-mpi})))
  2075. (private-key
  2076. (elg
  2077. (p @var{p-mpi})
  2078. (g @var{g-mpi})
  2079. (y @var{y-mpi})
  2080. (x @var{x-mpi})))
  2081. (misc-key-info
  2082. (pm1-factors @var{n1 n2 ... nn})))
  2083. @end example
  2084. @noindent
  2085. As you can see, some of the information is duplicated, but this provides
  2086. an easy way to extract either the public or the private key. Note that
  2087. the order of the elements is not defined, e.g. the private key may be
  2088. stored before the public key. @var{n1 n2 ... nn} is a list of prime
  2089. numbers used to composite @var{p-mpi}; this is in general not a very
  2090. useful information.
  2091. @end deftypefun
  2092. @c end gcry_pk_genkey
  2093. @node Public Key cryptography (II)
  2094. @chapter Public Key cryptography (II)
  2095. This chapter documents the alternative interface to asymmetric
  2096. cryptography (ac) that is not based on S-expressions, but on native C
  2097. data structures. As opposed to the pk interface described in the
  2098. former chapter, this one follows an open/use/close paradigm like other
  2099. building blocks of the library.
  2100. @menu
  2101. * Available asymmetric algorithms:: List of algorithms supported by the library.
  2102. * Working with sets of data:: How to work with sets of data.
  2103. * Working with handles:: How to use handles.
  2104. * Working with keys:: How to work with keys.
  2105. * Using cryptographic functions:: How to perform cryptographic operations.
  2106. * Handle-independent functions:: General functions independent of handles.
  2107. @end menu
  2108. @node Available asymmetric algorithms
  2109. @section Available asymmetric algorithms
  2110. @acronym{Libgcrypt} supports the RSA (Rivest-Shamir-Adleman)
  2111. algorithms as well as DSA (Digital Signature Algorithm) and ElGamal.
  2112. The versatile interface allows to add more algorithms in the future.
  2113. @deftp {Data type} gcry_ac_id_t
  2114. The following constants are defined for this type:
  2115. @table @code
  2116. @item GCRY_AC_RSA
  2117. Riven-Shamir-Adleman
  2118. @item GCRY_AC_DSA
  2119. Digital Signature Algorithm
  2120. @item GCRY_AC_ELG
  2121. ElGamal
  2122. @item GCRY_AC_ELG_E
  2123. ElGamal, encryption only.
  2124. @end table
  2125. @end deftp
  2126. @node Working with sets of data
  2127. @section Working with sets of data
  2128. In the context of this interface the term `data set' refers to a list
  2129. of `named MPI values' that is used by functions performing
  2130. cryptographic operations.
  2131. Such data sets are used for representing keys, since keys simply
  2132. consist of a variable amount of numbers. Furthermore some functions
  2133. return data sets to the caller that are to be provided to other
  2134. functions.
  2135. This section documents the data types, symbols and functions that are
  2136. relevant for working with such data sets.
  2137. @deftp {Data type} gcry_ac_data_t
  2138. A data set, that is simply a list of named MPI values.
  2139. @end deftp
  2140. The following flags are supported:
  2141. @table @code
  2142. @item GCRY_AC_FLAG_DEALLOC
  2143. Used for storing data in a data set. If given, the data will be
  2144. released by the library.
  2145. @item GCRY_AC_FLAG_COPY
  2146. Used for storing/retrieving data in/from a data set. If given, the
  2147. library will create copies of the provided/contained data, which will
  2148. then be given to the user/associated with the data set.
  2149. @end table
  2150. @deftypefun gcry_error_t gcry_ac_data_new (gcry_ac_data_t *@var{data})
  2151. Creates a new, empty data set and stores it in @var{data}.
  2152. @end deftypefun
  2153. @deftypefun void gcry_ac_data_destroy (gcry_ac_data_t @var{data})
  2154. Destroys the data set @var{data}.
  2155. @end deftypefun
  2156. @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})
  2157. Add the value @var{mpi} to @var{data} with the label @var{name}. If
  2158. @var{flags} contains GCRY_AC_FLAG_DATA_COPY, the data set will contain
  2159. copies of @var{name} and @var{mpi}. If @var{flags} contains
  2160. GCRY_AC_FLAG_DATA_DEALLOC or GCRY_AC_FLAG_DATA_COPY, the values
  2161. contained in the data set will be deallocated when they are to be
  2162. removed from the data set.
  2163. @end deftypefun
  2164. @deftypefun gcry_error_t gcry_ac_data_copy (gcry_ac_data_t *@var{data_cp}, gcry_ac_data_t @var{data})
  2165. Create a copy of the data set @var{data} and store it in @var{data_cp}.
  2166. @end deftypefun
  2167. @deftypefun unsigned int gcry_ac_data_length (gcry_ac_data_t @var{data})
  2168. Returns the number of named MPI values inside of the data set
  2169. @var{data}.
  2170. @end deftypefun
  2171. @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})
  2172. Store the value labelled with @var{name} found in @var{data} in
  2173. @var{mpi}. If @var{flags} contains GCRY_AC_FLAG_COPY, store a copy of
  2174. the @var{mpi} value contained in the data set. @var{mpi} may be NULL.
  2175. @end deftypefun
  2176. @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})
  2177. Stores in @var{name} and @var{mpi} the named @var{mpi} value contained
  2178. in the data set @var{data} with the index @var{idx}. If @var{flags}
  2179. contains GCRY_AC_FLAG_COPY, store copies of the values contained in
  2180. the data set. @var{name} or @var{mpi} may be NULL.
  2181. @end deftypefun
  2182. @deftypefun void gcry_ac_data_clear (gcry_ac_data_t @var{data})
  2183. Destroys any values contained in the data set @var{data}.
  2184. @end deftypefun
  2185. @node Working with handles
  2186. @section Working with handles
  2187. In order to use an algorithm, an according handle must be created.
  2188. This is done using the following function:
  2189. @deftypefun gcry_error_t gcry_ac_open (gcry_ac_handle_t *@var{handle}, int @var{algorithm}, int @var{flags})
  2190. Creates a new handle for the algorithm @var{algorithm} and stores it
  2191. in @var{handle}. @var{flags} is not used yet.
  2192. @var{algorithm} must be a valid algorithm ID, see @xref{Available
  2193. algorithms}, for a list of supported algorithms and the according
  2194. constants. Besides using the listed constants directly, the functions
  2195. @code{gcry_ac_name_to_id} may be used to convert the textual name of
  2196. an algorithm into the according numeric ID.
  2197. @end deftypefun
  2198. @deftypefun void gcry_ac_close (gcry_ac_handle_t @var{handle})
  2199. Destroys the handle @var{handle}.
  2200. @end deftypefun
  2201. @node Working with keys
  2202. @section Working with keys
  2203. @deftp {Data type} gcry_ac_key_type_t
  2204. Defined constants:
  2205. @table @code
  2206. @item GCRY_AC_KEY_TYPE_SECRET
  2207. Specifies a secret key.
  2208. @item GCRY_AC_KEY_TYPE_PUBLIC
  2209. Specifies a public key.
  2210. @end table
  2211. @end deftp
  2212. @deftp {Data type} gcry_ac_key_t
  2213. This type represents a single `key', either a secret one or a public
  2214. one.
  2215. @end deftp
  2216. @deftp {Data type} gcry_ac_key_pair_t
  2217. This type represents a `key pair' containing a secret and a public key.
  2218. @end deftp
  2219. Key data structures can be created in two different ways; a new key
  2220. pair can be generated, resulting in ready-to-use key. Alternatively a
  2221. key can be initialized from a given data set.
  2222. @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})
  2223. Creates a new key of type @var{type}, consisting of the MPI values
  2224. contained in the data set @var{data} and stores it in @var{key}.
  2225. @end deftypefun
  2226. @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})
  2227. Generates a new key pair via the handle @var{handle} of @var{NBITS}
  2228. bits and stores it in @var{key_pair}.
  2229. In case non-standard settings are wanted, a pointer to a structure of
  2230. type @code{gcry_ac_key_spec_<algorithm>_t}, matching the selected
  2231. algorithm, can be given as @var{key_spec}. @var{misc_data} is not
  2232. used yet. Such a structure does only exist for RSA. A descriptions
  2233. of the members of the supported structures follows.
  2234. @table @code
  2235. @item gcry_ac_key_spec_rsa_t
  2236. @table @code
  2237. @item gcry_mpi_t e
  2238. Generate the key pair using a special @code{e}. The value of @code{e}
  2239. has the following meanings:
  2240. @table @code
  2241. @item = 0
  2242. Let @acronym{Libgcrypt} device what exponent should be used.
  2243. @item = 1
  2244. Request the use of a ``secure'' exponent; this is required by some
  2245. specification to be 65537.
  2246. @item > 2
  2247. Try starting at this value until a working exponent is found. Note,
  2248. that the current implementation leaks some information about the
  2249. private key because the incrementation used is not randomized. Thus,
  2250. this function will be changed in the future to return a random
  2251. exponent of the given size.
  2252. @end table
  2253. @end table
  2254. @end table
  2255. Example code:
  2256. @example
  2257. @{
  2258. gcry_ac_key_pair_t key_pair;
  2259. gcry_ac_key_spec_rsa rsa_spec;
  2260. rsa_spec.e = gcry_mpi_new (0);
  2261. gcry_mpi_set_ui (rsa_spec.e, 1)
  2262. err = gcry_ac_open (&handle, GCRY_AC_RSA, 0);
  2263. assert (! err);
  2264. err = gcry_ac_key_pair_generate (handle, &key_pair, 1024, (void *) &rsa_spec);
  2265. assert (! err);
  2266. @}
  2267. @end example
  2268. @end deftypefun
  2269. @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})
  2270. Returns the key of type @var{which} out of the key pair
  2271. @var{key_pair}.
  2272. @end deftypefun
  2273. @deftypefun void gcry_ac_key_destroy (gcry_ac_key_t @var{key})
  2274. Destroys the key @var{key}.
  2275. @end deftypefun
  2276. @deftypefun void gcry_ac_key_pair_destroy (gcry_ac_key_pair_t @var{key_pair})
  2277. Destroys the key pair @var{key_pair}.
  2278. @end deftypefun
  2279. @deftypefun gcry_ac_data_t gcry_ac_key_data_get (gcry_ac_key_t @var{key})
  2280. Returns the data set contained in the key @var{key}.
  2281. @end deftypefun
  2282. @deftypefun gcry_error_t gcry_ac_key_test (gcry_ac_handle_t @var{handle}, gcry_ac_key_t @var{key})
  2283. Verifies that the private key @var{key} is sane via @var{handle}.
  2284. @end deftypefun
  2285. @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})
  2286. Stores the number of bits of the key @var{key} in @var{nbits} via @var{handle}.
  2287. @end deftypefun
  2288. @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})
  2289. Writes the 20 byte long key grip of the key @var{key} to
  2290. @var{key_grip} via @var{handle}.
  2291. @end deftypefun
  2292. @node Using cryptographic functions
  2293. @section Using cryptographic functions
  2294. The following flags might be relevant:
  2295. @table @code
  2296. @item GCRY_AC_FLAG_NO_BLINDING
  2297. Disable any blinding, which might be supported by the chosen
  2298. algorithm; blinding is the default.
  2299. @end table
  2300. @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})
  2301. Encrypts the plain text MPI value @var{data_plain} with the key public
  2302. @var{key} under the control of the flags @var{flags} and stores the
  2303. resulting data set into @var{data_encrypted}.
  2304. @end deftypefun
  2305. @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})
  2306. Decrypts the encrypted data contained in the data set
  2307. @var{data_encrypted} with the secret key KEY under the control of the
  2308. flags @var{flags} and stores the resulting plain text MPI value in
  2309. @var{DATA_PLAIN}.
  2310. @end deftypefun
  2311. @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})
  2312. Signs the data contained in @var{data} with the secret key @var{key}
  2313. and stores the resulting signature in the data set
  2314. @var{data_signature}.
  2315. @end deftypefun
  2316. @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})
  2317. Verifies that the signature contained in the data set
  2318. @var{data_signature} is indeed the result of signing the data
  2319. contained in @var{data} with the secret key belonging to the public
  2320. key @var{key}.
  2321. @end deftypefun
  2322. @node Handle-independent functions
  2323. @section Handle-independent functions
  2324. @deftypefun gcry_error_t gcry_ac_id_to_name (gcry_ac_id_t @var{algorithm}, const char **@var{name})
  2325. Stores the textual representation of the algorithm whose id is given
  2326. in @var{algorithm} in @var{name}.
  2327. @end deftypefun
  2328. @deftypefun gcry_error_t gcry_ac_name_to_id (const char *@var{name}, gcry_ac_id_t *@var{algorithm})
  2329. Stores the numeric ID of the algorithm whose textual representation is
  2330. contained in @var{name} in @var{algorithm}.
  2331. @end deftypefun
  2332. @c **********************************************************
  2333. @c ******************* Random *****************************
  2334. @c **********************************************************
  2335. @node Random Numbers
  2336. @chapter Random Numbers
  2337. @menu
  2338. * Quality of random numbers:: @acronym{Libgcrypt} uses different quality levels.
  2339. * Retrieving random numbers:: How to retrieve random numbers.
  2340. @end menu
  2341. @node Quality of random numbers
  2342. @section Quality of random numbers
  2343. @acronym{Libgcypt} offers random numbers of different quality levels:
  2344. @deftp {Data type} enum gcry_random_level
  2345. The constants for the random quality levels are of this type.
  2346. @end deftp
  2347. @table @code
  2348. @item GCRY_WEAK_RANDOM
  2349. This should not anymore be used. It has recently been changed to an
  2350. alias of GCRY_STRONG_RANDOM. Use @code{gcry_create_nonce} instead.
  2351. @item GCRY_STRONG_RANDOM
  2352. Use this level for e.g. session keys and similar purposes.
  2353. @item GCRY_VERY_STRONG_RANDOM
  2354. Use this level for e.g. key material.
  2355. @end table
  2356. @node Retrieving random numbers
  2357. @section Retrieving random numbers
  2358. @deftypefun void gcry_randomize (unsigned char *@var{buffer}, size_t @var{length}, enum gcry_random_level @var{level})
  2359. Fill @var{buffer} with @var{length} random bytes using a random quality
  2360. as defined by @var{level}.
  2361. @end deftypefun
  2362. @deftypefun void * gcry_random_bytes (size_t @var{nbytes}, enum gcry_random_level @var{level})
  2363. Allocate a memory block consisting of @var{nbytes} fresh random bytes
  2364. using a random quality as defined by @var{level}.
  2365. @end deftypefun
  2366. @deftypefun void * gcry_random_bytes_secure (size_t @var{nbytes}, enum gcry_random_level @var{level})
  2367. Allocate a memory block consisting of @var{nbytes} fresh random bytes
  2368. using a random quality as defined by @var{level}. This function
  2369. differs from @code{gcry_random_bytes} in that the returned buffer is
  2370. allocated in a ``secure'' area of the memory.
  2371. @end deftypefun
  2372. @deftypefun void gcry_create_nonce (void *@var{buffer}, size_t @var{length})
  2373. Fill @var{buffer} with @var{length} unpredictable bytes. This is
  2374. commonly called a nonce and may also be used for initialization
  2375. vectors and padding. This is an extra function nearly independent of
  2376. the other random function for 3 reasons: It better protects the
  2377. regular random generator's internal state, provides better performance
  2378. and does not drain the precious entropy pool.
  2379. @end deftypefun
  2380. @c **********************************************************
  2381. @c ******************* S-Expressions ***********************
  2382. @c **********************************************************
  2383. @node S-expressions
  2384. @chapter S-expressions
  2385. S-expressions are used by the public key functions to pass complex data
  2386. structures around. These LISP like objects are used by some
  2387. cryptographic protocols (cf. RFC-2692) and @acronym{Libgcrypt} provides functions
  2388. to parse and construct them. For detailed information, see
  2389. @cite{Ron Rivest, code and description of S-expressions,
  2390. @uref{http://theory.lcs.mit.edu/~rivest/sexp.html}}.
  2391. @menu
  2392. * Data types for S-expressions:: Data types related with S-expressions.
  2393. * Working with S-expressions:: How to work with S-expressions.
  2394. @end menu
  2395. @node Data types for S-expressions
  2396. @section Data types for S-expressions
  2397. @deftp {Data type} gcry_sexp_t
  2398. The @code{gcry_sexp_t} type describes an object with the @acronym{Libgcrypt} internal
  2399. representation of an S-expression.
  2400. @end deftp
  2401. @node Working with S-expressions
  2402. @section Working with S-expressions
  2403. @noindent
  2404. There are several functions to create an @acronym{Libgcrypt} S-expression object
  2405. from its external representation or from a string template. There is
  2406. also a function to convert the internal representation back into one of
  2407. the external formats:
  2408. @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}})
  2409. This is the generic function to create an new S-expression object from
  2410. its external representation in @var{buffer} of @var{length} bytes. On
  2411. success the result is stored at the address given by @var{r_sexp}.
  2412. With @var{autodetect} set to 0, the data in @var{buffer} is expected to
  2413. be in canonized format, with @var{autodetect} set to 1 the parses any of
  2414. the defined external formats. If @var{buffer} does not hold a valid
  2415. S-expression an error code is returned and @var{r_sexp} set to
  2416. @code{NULL}.
  2417. Note, that the caller is responsible for releasing the newly allocated
  2418. S-expression using @code{gcry_sexp_release}.
  2419. @end deftypefun
  2420. @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*)})
  2421. This function is identical to @code{gcry_sexp_new} but has an extra
  2422. argument @var{freefnc}, which, when not set to @code{NULL}, is expected
  2423. to be a function to release the @var{buffer}; most likely the standard
  2424. @code{free} function is used for this argument. This has the effect of
  2425. transferring the ownership of @var{buffer} to the created object in
  2426. @var{r_sexp}. The advantage of using this function is that @acronym{Libgcrypt}
  2427. might decide to directly use the provided buffer and thus avoid extra
  2428. copying.
  2429. @end deftypefun
  2430. @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}})
  2431. This is another variant of the above functions. It behaves nearly
  2432. identical but provides an @var{erroff} argument which will receive the
  2433. offset into the buffer where the parsing stopped on error.
  2434. @end deftypefun
  2435. @deftypefun gcry_error_t gcry_sexp_build (@w{gcry_sexp_t *@var{r_sexp}}, @w{size_t *@var{erroff}}, @w{const char *@var{format}, ...})
  2436. This function creates an internal S-expression from the string template
  2437. @var{format} and stores it at the address of @var{r_sexp}. If there is a
  2438. parsing error, the function returns an appropriate error code and stores
  2439. the offset into @var{format} where the parsing stopped in @var{erroff}.
  2440. The function supports a couple of printf-like formatting characters and
  2441. expects arguments for some of these escape sequences right after
  2442. @var{format}. The following format characters are defined:
  2443. @table @samp
  2444. @item %m
  2445. The next argument is expected to be of type @code{gcry_mpi_t} and a copy of
  2446. its value is inserted into the resulting S-expression.
  2447. @item %s
  2448. The next argument is expected to be of type @code{char *} and that
  2449. string is inserted into the resulting S-expression.
  2450. @item %d
  2451. The next argument is expected to be of type @code{int} and its
  2452. value ist inserted into the resulting S-expression.
  2453. @item %b
  2454. The next argument is expected to be of type @code{int} directly
  2455. followed by an argument of type @code{char *}. This represents a
  2456. buffer of given length to be inserted into the resulting regular
  2457. expression.
  2458. @end table
  2459. @noindent
  2460. No other format characters are defined and would return an error. Note,
  2461. that the format character @samp{%%} does not exists, because a percent
  2462. sign is not a valid character in an S-expression.
  2463. @end deftypefun
  2464. @deftypefun void gcry_sexp_release (@w{gcry_sexp_t @var{sexp}})
  2465. Release the S-expression object @var{sexp}.
  2466. @end deftypefun
  2467. @noindent
  2468. The next 2 functions are used to convert the internal representation
  2469. back into a regular external S-expression format and to show the
  2470. structure for debugging.
  2471. @deftypefun size_t gcry_sexp_sprint (@w{gcry_sexp_t @var{sexp}}, @w{int @var{mode}}, @w{void *@var{buffer}}, @w{size_t @var{maxlength}})
  2472. Copies the S-expression object @var{sexp} into @var{buffer} using the
  2473. format specified in @var{mode}. @var{maxlength} must be set to the
  2474. allocated length of @var{buffer}. The function returns the actual
  2475. length of valid bytes put into @var{buffer} or 0 if the provided buffer
  2476. is too short. Passing @code{NULL} for @var{buffer} returns the required
  2477. length for @var{buffer}. For convenience reasons an extra byte with
  2478. value 0 is appended to the buffer.
  2479. @noindent
  2480. The following formats are supported:
  2481. @table @code
  2482. @item GCRYSEXP_FMT_DEFAULT
  2483. Returns a convenient external S-expression representation.
  2484. @item GCRYSEXP_FMT_CANON
  2485. Return the S-expression in canonical format.
  2486. @item GCRYSEXP_FMT_BASE64
  2487. Not currently supported.
  2488. @item GCRYSEXP_FMT_ADVANCED
  2489. Returns the S-expression in advanced format.
  2490. @end table
  2491. @end deftypefun
  2492. @deftypefun void gcry_sexp_dump (@w{gcry_sexp_t @var{sexp}})
  2493. Dumps @var{sexp} in a format suitable for debugging to @acronym{Libgcrypt}'s
  2494. logging stream.
  2495. @end deftypefun
  2496. @noindent
  2497. Often canonical encoding is used in the external representation. The
  2498. following function can be used to check for valid encoding and to learn
  2499. the length of the S-expression"
  2500. @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}})
  2501. Scan the canonical encoded @var{buffer} with implicit length values and
  2502. return the actual length this S-expression uses. For a valid S-expression
  2503. it should never return 0. If @var{length} is not 0, the maximum
  2504. length to scan is given; this can be used for syntax checks of
  2505. data passed from outside. @var{errcode} and @var{erroff} may both be
  2506. passed as @code{NULL}.
  2507. @end deftypefun
  2508. @noindent
  2509. There are a couple of functions to parse S-expressions and retrieve
  2510. elements:
  2511. @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}})
  2512. Scan the S-expression for a sublist with a type (the car of the list)
  2513. matching the string @var{token}. If @var{toklen} is not 0, the token is
  2514. assumed to be raw memory of this length. The function returns a newly
  2515. allocated S-expression consisting of the found sublist or @code{NULL}
  2516. when not found.
  2517. @end deftypefun
  2518. @deftypefun int gcry_sexp_length (@w{const gcry_sexp_t @var{list}})
  2519. Return the length of the @var{list}. For a valid S-expression this
  2520. should be at least 1.
  2521. @end deftypefun
  2522. @deftypefun gcry_sexp_t gcry_sexp_nth (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}})
  2523. Create and return a new S-expression from the element with index @var{number} in
  2524. @var{list}. Note that the first element has the index 0. If there is
  2525. no such element, @code{NULL} is returned.
  2526. @end deftypefun
  2527. @deftypefun gcry_sexp_t gcry_sexp_car (@w{const gcry_sexp_t @var{list}})
  2528. Create and return a new S-expression from the first element in
  2529. @var{list}; this called the "type" and should always exist and be a
  2530. string. @code{NULL} is returned in case of a problem.
  2531. @end deftypefun
  2532. @deftypefun gcry_sexp_t gcry_sexp_cdr (@w{const gcry_sexp_t @var{list}})
  2533. Create and return a new list form all elements except for the first one.
  2534. Note, that this function may return an invalid S-expression because it
  2535. is not guaranteed, that the type exists and is a string. However, for
  2536. parsing a complex S-expression it might be useful for intermediate
  2537. lists. Returns @code{NULL} on error.
  2538. @end deftypefun
  2539. @deftypefun {const char *} gcry_sexp_nth_data (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{size_t *@var{datalen}})
  2540. This function is used to get data from a @var{list}. A pointer to the
  2541. actual data with index @var{number} is returned and the length of this
  2542. data will be stored to @var{datalen}. If there is no data at the given
  2543. index or the index represents another list, @code{NULL} is returned.
  2544. @strong{Take care:} The returned pointer is valid as long as @var{list} is
  2545. not modified or released.
  2546. @noindent
  2547. Here is an example on how to extract and print the surname (Meier) from
  2548. the S-expression @samp{(Name Otto Meier (address Burgplatz 3))}:
  2549. @example
  2550. size_t len;
  2551. const char *name;
  2552. name = gcry_sexp_nth_data (list, 2, &len);
  2553. printf ("my name is %.*s\n", (int)len, name);
  2554. @end example
  2555. @end deftypefun
  2556. @deftypefun gcry_mpi_t gcry_sexp_nth_mpi (@w{gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{int @var{mpifmt}})
  2557. This function is used to get and convert data from a @var{list}. This
  2558. data is assumed to be an MPI stored in the format described by
  2559. @var{mpifmt} and returned as a standard @acronym{Libgcrypt} MPI. The caller must
  2560. release this returned value using @code{gcry_mpi_release}. If there is
  2561. no data at the given index, the index represents a list or the value
  2562. can't be converted to an MPI, @code{NULL} is returned.
  2563. @end deftypefun
  2564. @c **********************************************************
  2565. @c ******************* MPIs ******** ***********************
  2566. @c **********************************************************
  2567. @node MPI library
  2568. @chapter MPI library
  2569. @menu
  2570. * Data types:: MPI related data types.
  2571. * Basic functions:: First steps with MPI numbers.
  2572. * MPI formats:: External representation of MPIs.
  2573. * Calculations:: Performing MPI calculations.
  2574. * Comparisons:: How to compare MPI values.
  2575. * Bit manipulations:: How to access single bits of MPI values.
  2576. * Miscellaneous:: Miscellaneous MPI functions.
  2577. @end menu
  2578. Public key cryptography is based on mathematics with large numbers. To
  2579. implement the public key functions, a library for handling these large
  2580. numbers is required. Because of the general usefulness of such a
  2581. library, its interface is exposed by @acronym{Libgcrypt}. The implementation is
  2582. based on an old release of GNU Multi-Precision Library (GMP) but in the
  2583. meantime heavily modified and stripped down to what is required for
  2584. cryptography. For a lot of CPUs, high performance assembler
  2585. implementations of some very low level functions are used to gain much
  2586. better performance than with the standard C implementation.
  2587. @noindent
  2588. In the context of @acronym{Libgcrypt} and in most other applications, these large
  2589. numbers are called MPIs (multi-precision-integers).
  2590. @node Data types
  2591. @section Data types
  2592. @deftp {Data type} gcry_mpi_t
  2593. The @code{gcry_mpi_t} type represents an object to hold an MPI.
  2594. @end deftp
  2595. @node Basic functions
  2596. @section Basic functions
  2597. @noindent
  2598. To work with MPIs, storage must be allocated and released for the
  2599. numbers. This can be done with one of these functions:
  2600. @deftypefun gcry_mpi_t gcry_mpi_new (@w{unsigned int @var{nbits}})
  2601. Allocate a new MPI object, initialize it to 0 and initially allocate
  2602. enough memory for a number of at least @var{nbits}. This pre-allocation is
  2603. only a small performance issue and not actually necessary because
  2604. @acronym{Libgcrypt} automatically re-allocates the required memory.
  2605. @end deftypefun
  2606. @deftypefun gcry_mpi_t gcry_mpi_snew (@w{unsigned int @var{nbits}})
  2607. This is identical to @code{gcry_mpi_new} but allocates the MPI in the so
  2608. called "secure memory" which in turn will take care that all derived
  2609. values will also be stored in this "secure memory". Use this for highly
  2610. confidential data like private key parameters.
  2611. @end deftypefun
  2612. @deftypefun gcry_mpi_t gcry_mpi_copy (@w{const gcry_mpi_t @var{a}})
  2613. Create a new MPI as the exact copy of @var{a}.
  2614. @end deftypefun
  2615. @deftypefun void gcry_mpi_release (@w{gcry_mpi_t @var{a}})
  2616. Release the MPI @var{a} and free all associated resources. Passing
  2617. @code{NULL} is allowed and ignored. When a MPI stored in the "secure
  2618. memory" is released, that memory gets wiped out immediately.
  2619. @end deftypefun
  2620. @noindent
  2621. The simplest operations are used to assign a new value to an MPI:
  2622. @deftypefun gcry_mpi_t gcry_mpi_set (@w{gcry_mpi_t @var{w}}, @w{const gcry_mpi_t @var{u}})
  2623. Assign the value of @var{u} to @var{w} and return @var{w}. If
  2624. @code{NULL} is passed for @var{w}, a new MPI is allocated, set to the
  2625. value of @var{u} and returned.
  2626. @end deftypefun
  2627. @deftypefun gcry_mpi_t gcry_mpi_set_ui (@w{gcry_mpi_t @var{w}}, @w{unsigned long @var{u}})
  2628. Assign the value of @var{u} to @var{w} and return @var{w}. If
  2629. @code{NULL} is passed for @var{w}, a new MPI is allocated, set to the
  2630. value of @var{u} and returned. This function takes an @code{unsigned
  2631. int} as type for @var{u} and thus it is only possible to set @var{w} to
  2632. small values (usually up to the word size of the CPU).
  2633. @end deftypefun
  2634. @deftypefun void gcry_mpi_swap (@w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}})
  2635. Swap the values of @var{a} and @var{b}.
  2636. @end deftypefun
  2637. @node MPI formats
  2638. @section MPI formats
  2639. @noindent
  2640. The following functions are used to convert between an external
  2641. representation of an MPI and the internal one of @acronym{Libgcrypt}.
  2642. @deftypefun int gcry_mpi_scan (@w{gcry_mpi_t *@var{r_mpi}}, @w{enum gcry_mpi_format @var{format}}, @w{const void *@var{buffer}}, @w{size_t @var{buflen}}, @w{size_t *@var{nscanned}})
  2643. Convert the external representation of an integer stored in @var{buffer}
  2644. with a length of @var{buflen} into a newly created MPI returned which
  2645. will be stored at the address of @var{r_mpi}. For certain formats the
  2646. length argument is not required and may be passed as @code{0}. After a
  2647. successful operation the variable @var{nscanned} receives the number of
  2648. bytes actually scanned unless @var{nscanned} was given as
  2649. @code{NULL}. @var{format} describes the format of the MPI as stored in
  2650. @var{buffer}:
  2651. @table @code
  2652. @item GCRYMPI_FMT_STD
  2653. 2-complement stored without a length header.
  2654. @item GCRYMPI_FMT_PGP
  2655. As used by OpenPGP (only defined as unsigned). This is basically
  2656. @code{GCRYMPI_FMT_STD} with a 2 byte big endian length header.
  2657. @item GCRYMPI_FMT_SSH
  2658. As used in the Secure Shell protocol. This is @code{GCRYMPI_FMT_STD}
  2659. with a 4 byte big endian header.
  2660. @item GCRYMPI_FMT_HEX
  2661. Stored as a C style string with each byte of the MPI encoded as 2 hex
  2662. digits.
  2663. @item GCRYMPI_FMT_USG
  2664. Simple unsigned integer.
  2665. @end table
  2666. @noindent
  2667. Note, that all of the above formats store the integer in big-endian
  2668. format (MSB first).
  2669. @end deftypefun
  2670. @deftypefun int 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}})
  2671. Convert the MPI @var{a} into an external representation described by
  2672. @var{format} (see above) and store it in the provided @var{buffer}
  2673. which has a usable length of at least the @var{buflen} bytes. If
  2674. @var{nwritten} is not NULL, it will receive the number of bytes
  2675. actually stored in @var{buffer} after a successful operation.
  2676. @end deftypefun
  2677. @deftypefun int 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}})
  2678. Convert the MPI @var{a} into an external representation described by
  2679. @var{format} (see above) and store it in a newly allocated buffer which
  2680. address will be stored in the variable @var{buffer} points to. The
  2681. number of bytes stored in this buffer will be stored in the variable
  2682. @var{nbytes} points to, unless @var{nbytes} is @code{NULL}.
  2683. @end deftypefun
  2684. @deftypefun void gcry_mpi_dump (@w{const gcry_mpi_t @var{a}})
  2685. Dump the value of @var{a} in a format suitable for debugging to
  2686. Libgcrypt's logging stream. Note that one leading space but no trailing
  2687. space or linefeed will be printed. It is okay to pass @code{NULL} for
  2688. @var{a}.
  2689. @end deftypefun
  2690. @node Calculations
  2691. @section Calculations
  2692. @noindent
  2693. Basic arithmetic operations:
  2694. @deftypefun void gcry_mpi_add (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
  2695. @math{@var{w} = @var{u} + @var{v}}.
  2696. @end deftypefun
  2697. @deftypefun void gcry_mpi_add_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
  2698. @math{@var{w} = @var{u} + @var{v}}. Note, that @var{v} is an unsigned integer.
  2699. @end deftypefun
  2700. @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}})
  2701. @math{@var{w} = @var{u} + @var{v} \bmod @var{m}}.
  2702. @end deftypefun
  2703. @deftypefun void gcry_mpi_sub (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
  2704. @math{@var{w} = @var{u} - @var{v}}.
  2705. @end deftypefun
  2706. @deftypefun void gcry_mpi_sub_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
  2707. @math{@var{w} = @var{u} - @var{v}}. @var{v} is an unsigned integer.
  2708. @end deftypefun
  2709. @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}})
  2710. @math{@var{w} = @var{u} - @var{v} \bmod @var{m}}.
  2711. @end deftypefun
  2712. @deftypefun void gcry_mpi_mul (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
  2713. @math{@var{w} = @var{u} * @var{v}}.
  2714. @end deftypefun
  2715. @deftypefun void gcry_mpi_mul_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
  2716. @math{@var{w} = @var{u} * @var{v}}. @var{v} is an unsigned integer.
  2717. @end deftypefun
  2718. @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}})
  2719. @math{@var{w} = @var{u} * @var{v} \bmod @var{m}}.
  2720. @end deftypefun
  2721. @deftypefun void gcry_mpi_mul_2exp (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{e}})
  2722. @c FIXME: I am in need for a real TeX{info} guru:
  2723. @c I don't know why TeX can grok @var{e} here.
  2724. @math{@var{w} = @var{u} * 2^e}.
  2725. @end deftypefun
  2726. @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}})
  2727. @math{@var{q} = @var{dividend} / @var{divisor}}, @math{@var{r} =
  2728. @var{dividend} \bmod @var{divisor}}. @var{q} and @var{r} may be passed
  2729. as @code{NULL}. @var{round} should be negative or 0.
  2730. @end deftypefun
  2731. @deftypefun void gcry_mpi_mod (@w{gcry_mpi_t @var{r}}, @w{gcry_mpi_t @var{dividend}}, @w{gcry_mpi_t @var{divisor}})
  2732. @math{@var{r} = @var{dividend} \bmod @var{divisor}}.
  2733. @end deftypefun
  2734. @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}})
  2735. @c I don't know why TeX can grok @var{e} here.
  2736. @math{@var{w} = @var{b}^e \bmod @var{m}}.
  2737. @end deftypefun
  2738. @deftypefun int gcry_mpi_gcd (@w{gcry_mpi_t @var{g}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}})
  2739. Set @var{g} to the greatest common divisor of @var{a} and @var{b}.
  2740. Return true if the @var{g} is 1.
  2741. @end deftypefun
  2742. @deftypefun int gcry_mpi_invm (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{m}})
  2743. Set @var{x} to the multiplicative inverse of @math{@var{a} \bmod @var{m}}.
  2744. Return true if the inverse exists.
  2745. @end deftypefun
  2746. @node Comparisons
  2747. @section Comparisons
  2748. @noindent
  2749. The next 2 functions are used to compare MPIs:
  2750. @deftypefun int gcry_mpi_cmp (@w{const gcry_mpi_t @var{u}}, @w{const gcry_mpi_t @var{v}})
  2751. Compare the big integer number @var{u} and @var{v} returning 0 for
  2752. equality, a positive value for @var{u} > @var{v} and a negative for
  2753. @var{u} < @var{v}.
  2754. @end deftypefun
  2755. @deftypefun int gcry_mpi_cmp_ui (@w{const gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
  2756. Compare the big integer number @var{u} with the unsigned integer @var{v}
  2757. returning 0 for equality, a positive value for @var{u} > @var{v} and a
  2758. negative for @var{u} < @var{v}.
  2759. @end deftypefun
  2760. @node Bit manipulations
  2761. @section Bit manipulations
  2762. @noindent
  2763. There are a couple of functions to get information on arbitrary bits
  2764. in an MPI and to set or clear them:
  2765. @deftypefun {unsigned int} gcry_mpi_get_nbits (@w{gcry_mpi_t @var{a}})
  2766. Return the number of bits required to represent @var{a}.
  2767. @end deftypefun
  2768. @deftypefun int gcry_mpi_test_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
  2769. Return true if bit number @var{n} (counting from 0) is set in @var{a}.
  2770. @end deftypefun
  2771. @deftypefun void gcry_mpi_set_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
  2772. Set bit number @var{n} in @var{a}.
  2773. @end deftypefun
  2774. @deftypefun void gcry_mpi_clear_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
  2775. Clear bit number @var{n} in @var{a}.
  2776. @end deftypefun
  2777. @deftypefun void gcry_mpi_set_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
  2778. Set bit number @var{n} in @var{a} and clear all bits greater than @var{n}.
  2779. @end deftypefun
  2780. @deftypefun void gcry_mpi_clear_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
  2781. Clear bit number @var{n} in @var{a} and all bits greater than @var{n}.
  2782. @end deftypefun
  2783. @deftypefun void gcry_mpi_rshift (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
  2784. Shift the value of @var{a} by @var{n} bits to the right and store the
  2785. result in @var{x}.
  2786. @end deftypefun
  2787. @node Miscellaneous
  2788. @section Miscellanous
  2789. @deftypefun gcry_mpi_t gcry_mpi_set_opaque (@w{gcry_mpi_t @var{a}}, @w{void *@var{p}}, @w{unsigned int @var{nbits}})
  2790. Store @var{nbits} of the value @var{p} points to in @var{a} and mark
  2791. @var{a} as an opaque value (i.e. an value that can't be used for any
  2792. math calculation and is only used to store an arbitrary bit pattern in
  2793. @var{a}).
  2794. WARNING: Never use an opaque MPI for actual math operations. The only
  2795. valid functions are gcry_mpi_get_opaque and gcry_mpi_release. Use
  2796. gcry_mpi_scan to convert a string of arbitrary bytes into an MPI.
  2797. @end deftypefun
  2798. @deftypefun {void *} gcry_mpi_get_opaque (@w{gcry_mpi_t @var{a}}, @w{unsigned int *@var{nbits}})
  2799. Return a pointer to an opaque value stored in @var{a} and return its
  2800. size in @var{nbits}. Note, that the returned pointer is still owned by
  2801. @var{a} and that the function should never be used for an non-opaque
  2802. MPI.
  2803. @end deftypefun
  2804. @deftypefun void gcry_mpi_set_flag (@w{gcry_mpi_t @var{a}}, @w{enum gcry_mpi_flag @var{flag}})
  2805. Set the @var{flag} for the MPI @var{a}. Currently only the flag
  2806. @code{GCRYMPI_FLAG_SECURE} is allowed to convert @var{a} into an MPI
  2807. stored in "secure memory".
  2808. @end deftypefun
  2809. @deftypefun void gcry_mpi_clear_flag (@w{gcry_mpi_t @var{a}}, @w{enum gcry_mpi_flag @var{flag}})
  2810. Clear @var{flag} for the big integer @var{a}. Note, that this function is
  2811. currently useless as no flags are allowed.
  2812. @end deftypefun
  2813. @deftypefun int gcry_mpi_get_flag (@w{gcry_mpi_t @var{a}}, @w{enum gcry_mpi_flag @var{flag}})
  2814. Return true when the @var{flag} is set for @var{a}.
  2815. @end deftypefun
  2816. @deftypefun void gcry_mpi_randomize (@w{gcry_mpi_t @var{w}}, @w{unsigned int @var{nbits}}, @w{enum gcry_random_level @var{level}})
  2817. Set the big integer @var{w} to a random value of @var{nbits}, using
  2818. random data quality of level @var{level}. In case @var{nbits} is not
  2819. a multiple of a byte, @var{nbits} is rounded up to the next byte
  2820. boundary.
  2821. @end deftypefun
  2822. @node Utilities
  2823. @chapter Utilities
  2824. @menu
  2825. * Memory allocation:: Functions related with memory allocation.
  2826. @end menu
  2827. @node Memory allocation
  2828. @section Memory allocation
  2829. @deftypefun void *gcry_malloc (size_t @var{n})
  2830. This function tries to allocate @var{n} bytes of memory. On success
  2831. it returns a pointer to the memory area, in an out-of-core condition,
  2832. it returns NULL.
  2833. @end deftypefun
  2834. @deftypefun void *gcry_malloc_secure (size_t @var{n})
  2835. Like @code{gcry_malloc}, but uses secure memory.
  2836. @end deftypefun
  2837. @deftypefun void *gcry_calloc (size_t @var{n})
  2838. This function tries to allocate @var{n} bytes of cleared memory
  2839. (i.e. memory that is initialized with zero bytes). On success it
  2840. returns a pointer to the memory area, in an out-of-core condition, it
  2841. returns NULL.
  2842. @end deftypefun
  2843. @deftypefun void *gcry_calloc_secure (size_t @var{n})
  2844. Like @code{gcry_calloc}, but uses secure memory.
  2845. @end deftypefun
  2846. @deftypefun void *gcry_realloc (void *@var{p}, size_t @var{n})
  2847. This function tries to resize the memory area pointed to by @var{p} to
  2848. @var{n} bytes. On success it returns a pointer to the new memory
  2849. area, in an out-of-core condition, it returns NULL. Depending on
  2850. whether the memory pointed to by @var{p} is secure memory or not,
  2851. gcry_realloc tries to use secure memory as well.
  2852. @end deftypefun
  2853. @deftypefun void gcry_free (void *@var{p})
  2854. Release the memory area pointed to by @var{p}.
  2855. @end deftypefun
  2856. @c **********************************************************
  2857. @c ******************* Appendices *************************
  2858. @c **********************************************************
  2859. @include lgpl.texi
  2860. @include gpl.texi
  2861. @node Concept Index
  2862. @unnumbered Concept Index
  2863. @printindex cp
  2864. @node Function and Data Index
  2865. @unnumbered Function and Data Index
  2866. @printindex fn
  2867. @bye
  2868. /* Version check should be the very first gcry call because it
  2869. makes sure that constructor functions are run. */
  2870. if (!gcry_check_version (GCRYPT_VERSION))
  2871. die ("version mismatch\n");
  2872. /* Many applications don't require secure memory, so they should
  2873. disable it right away. There won't be a problem unless one makes
  2874. use of a feature which requires secure memory - in that case the
  2875. process would abort because the secmem is not initialized. */
  2876. gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
  2877. /* .. add whatever initialization you want, but better don't make calls
  2878. to libgcrypt from more than one thread ... */
  2879. /* Tell Libgcrypt that initialization has completed. */
  2880. gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
  2881. If you require secure memory, this code should be used:
  2882. if (!gcry_check_version (GCRYPT_VERSION))
  2883. die ("version mismatch\n");
  2884. /* We don't want to see any warnings, e.g. because we have not yet
  2885. parsed options which might be used to suppress such warnings */
  2886. gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
  2887. /* ... */
  2888. /* Allocate a pool of 16k secure memory. This also drops priviliges
  2889. on some systems. */
  2890. gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
  2891. /* It is now okay to let Libgcrypt complain when there was/is a problem
  2892. with the secure memory. */
  2893. gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
  2894. /* Tell Libgcrypt that initialization has completed. */
  2895. gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
  2896. This sounds a bit complicated but has the advantage that the caller
  2897. must decide whether he wants secure memory or not - there is no
  2898. default.
  2899. It is important that this initialization is not done by a library but
  2900. in the application. The library might want to check for finished
  2901. initialization using:
  2902. if (!gcry_control (GCRYCTL_INITIALIZATION_FINISHED_P))
  2903. return MYLIB_ERROR_LIBGCRYPT_NOT_INITIALIZED;
  2904. @c LocalWords: int HD