Page MenuHome GnuPG

No OneTemporary

This file is larger than 256 KB, so syntax highlighting was skipped.
This document is not UTF8. It was detected as Shift JIS and converted to UTF8 for display.
diff --git a/AUTHORS b/AUTHORS
index 718a914f..699e7a82 100644
--- a/AUTHORS
+++ b/AUTHORS
@@ -1,125 +1,130 @@
Library: Libgcrypt
Maintainer: Werner Koch <wk@gnupg.org>
Bug reports: <bug-libgcrypt@gnupg.org> or http://bugs.gnupg.org
Security related bug reports: <security@gnupg.org>
License (library): LGPLv2.1+
License (manual and tools): GPLv2+
Libgcrypt used to be part of GnuPG but has been taken out into its own
package on 2000-12-21.
Authors of Libgcrypt
====================
GNUPG Werner Koch 1998-02-23
Assigns GNU Privacy Guard and future changes.
wk@gnupg.org
Designed and implemented GnuPG.
GNUPG Matthew Skala 1998-08-10
Disclaims changes.
mskala@ansuz.sooke.bc.ca
Wrote cipher/twofish.c.
GNUPG Natural Resources Canada 1998-08-11
Disclaims changes by Matthew Skala.
GNUPG Michael Roth Germany 1998-09-17
Assigns changes.
mroth@nessie.de
Wrote cipher/des.c.
Changes and bug fixes all over the place.
GNUPG Niklas Hernaeus 1998-09-18
Disclaims changes.
nh@df.lth.se
Weak key patches.
GNUPG R駑i Guyomarch 1999-05-25
Assigns past and future changes. (g10/compress.c, g10/encr-data.c,
g10/free-packet.c, g10/mdfilter.c, g10/plaintext.c, util/iobuf.c)
rguyom@mail.dotcom.fr
ANY g10 Code GmbH 2001-06-07
Code marked with ChangeLog entries of g10 Code employees.
LIBGCRYPT Timo Schulz 2001-08-31
Assigns past and future changes.
twoaday@freakmail.de
LIBGCRYPT Simon Josefsson 2002-10-25
Assigns past and future changes to FSF (cipher/{md4,crc}.c, CTR mode,
CTS/MAC flags, self test improvements)
simon@josefsson.org
LIBGCRYPT Moritz Schulte 2003-04-17
Assigns past and future changes.
moritz@g10code.com
GNUTLS Nikolaos Mavrogiannopoulos 2003-11-22
nmav@gnutls.org
Original code for cipher/rfc2268.c.
LIBGCRYPT The Written Word 2005-04-15
Assigns past and future changes. (new: src/libgcrypt.pc.in,
src/Makefile.am, src/secmem.c, mpi/hppa1.1/mpih-mul3.S,
mpi/hppa1.1/udiv-qrnnd.S, mpi/hppa1.1/mpih-mul2.S,
mpi/hppa1.1/mpih-mul1.S, mpi/Makefile.am, tests/prime.c,
tests/register.c, tests/ac.c, tests/basic.c, tests/tsexp.c,
tests/keygen.c, tests/pubkey.c, configure.ac, acinclude.m4)
LIBGCRYPT Brad Hards 2006-02-09
Assigns Past and Future Changes
bradh@frogmouth.net
(Added OFB mode. Changed cipher/cipher.c, test/basic.c doc/gcrypt.tex.
added SHA-224, changed cipher/sha256.c, added HMAC tests.)
LIBGCRYPT Hye-Shik Chang 2006-09-07
Assigns Past and Future Changes
perky@freebsd.org
(SEED cipher)
LIBGCRYPT Werner Dittmann ** pending **
werner.dittmann@t-online.de
(mpi/amd64, tests/mpitests.c)
GNUPG David Shaw
Assigns past and future changes.
dshaw@jabberwocky.com>
(cipher/camellia-glue.c and related stuff)
More credits
============
The ATH implementation (src/ath*) has been taken from GPGME and
relicensed to the LGPL by the copyright holder of GPGME (g10 Code
GmbH); it is now considered to be a part of Libgcrypt.
Most of the stuff in mpi has been taken from an old GMP library
version by Torbjorn Granlund <tege@noisy.tmg.se>.
The files cipher/rndunix.c and cipher/rndw32.c are based on those
files from Cryptlib. Copyright Peter Gutmann, Paul Kendall, and Chris
Wedgwood 1996-1999.
The ECC code cipher/ecc.c was based on code by Sergi Blanch i Torne,
sergi at calcurco dot org.
The implementation of the Camellia cipher has been been taken from the
original NTT provided GPL source.
+The CAVS testing program tests/cavs_driver.pl is not to be considered
+a part of libgcrypt proper. We distribute it merely for convenience.
+It has a permissive license and is copyright by atsec information
+security corporation. See the file for details.
+
Copyright 1998, 1999, 2000, 2001, 2002, 2003,
2006, 2007, 2008 Free Software Foundation, Inc.
This file is free software; as a special exception the author gives
unlimited permission to copy and/or distribute it, with or without
modifications, as long as this notice is preserved.
This file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
diff --git a/NEWS b/NEWS
index 362e81cf..0678dd28 100644
--- a/NEWS
+++ b/NEWS
@@ -1,579 +1,586 @@
+Noteworthy changes in version 1.4.4
+------------------------------------------------
+
+ * Publish GCRY_MODULE_ID_USER and GCRY_MODULE_ID_USER_LAST constants.
+ This functionality is in Libgcrypt since 1.3.0.
+
+
Noteworthy changes in version 1.4.3 (2008-09-18)
------------------------------------------------
* Try to auto-initialize Libgcrypt to minimize the effect of
applications not doing that correctly. This is not a perfect
solution but given that many applicationion would totally fail
without such a hack, we try to help at least with the most common
cases. Folks, please read the manual to learn how to properly
initialize Libgcrypt!
* Auto-initialize the secure memory to 32k instead of aborting the
process.
* Log fatal errors via syslog.
* Changed the name and the semantics of the fips mode config file.
* Add convenience macro gcry_fips_mode_active.
* More self-tests.
* Documentation cleanups.
Noteworthy changes in version 1.4.2 (2008-09-08)
------------------------------------------------
* The long missing gcry_mpi_lshift function has been added.
* RSA key generation now supports a "transient-key" flag.
* The keygrip computation for ECDSA has been implemented thus ECDSA
is now fully supported.
* A few macros have been replaced by functions for better type
checking.
* The thread initialization structure now carries version
information.
* The manual describes more clearly how to initialize Libgcrypt.
* The library may now be switched into a FIPS mode.
* Interface changes relative to the 1.3.0 release:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GCRYCTL_OPERATIONAL_P NEW.
GCRYCTL_FIPS_MODE_P NEW.
GCRYCTL_FORCE_FIPS_MODE NEW.
gcry_cipher_setkey NEW: Replaces macro.
gcry_cipher_setiv NEW: Replaces macro.
gcry_cipher_setctr NEW: Replaces macro.
gcry_mpi_lshift NEW.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Noteworthy changes in version 1.4.1 (2008-04-25)
------------------------------------------------
* Fixed a bug introduced by 1.3.1 which led to the comsumption of far
too much entropy for the intial seeding.
* Improved AES performance for CFB and CBC modes.
* Removed build problems for the Padlock support.
Noteworthy changes in version 1.4.0 (2007-12-10)
------------------------------------------------
* New configure option --disable-padlock-support which is mostly
useful in case of build problems.
Noteworthy changes in version 1.3.2 (2007-12-03)
------------------------------------------------
* The visibility attribute is now used if supported by the toolchain.
* The ACE engine of VIA processors is now used for AES-128.
* The ASN.1 DER template for SHA-224 has been fixed.
Noteworthy changes in version 1.3.1 (2007-10-26)
------------------------------------------------
* The entire library is now under the LGPL. The helper programs and
the manual are under the GPL. Kudos to Peter Gutmann for giving
permissions to relicense the rndw32 and rndunix modules.
* The Camellia cipher is now under the LGPL and included by default.
* Fixed a bug in the detection of symbol prefixes which inhibited the
build of optimzied assembler code on certain systems.
* Updated the entropy gatherer for W32.
Noteworthy changes in version 1.3.0 (2007-05-04)
------------------------------------------------
* Changed the way the RNG gets initialized. This allows to keep it
uninitialized as long as no random numbers are used. To override
this, the new macro gcry_fast_random_poll may be used. It is in
general a good idea to spread this macro into the application code
to make sure that these polls happen often enough.
* Made the RNG immune against fork without exec.
* Reading and writing the random seed file is now protected by a
fcntl style file lock on systems that provide this function.
* Support for SHA-224 and HMAC using SHA-384 and SHA-512.
* Support for the SEED cipher.
* Support for the Camellia cipher. Note that Camellia is disabled by
default, and that enabling it changes the license of libgcrypt from
LGPL to GPL.
* Support for OFB encryption mode.
* gcry_mpi_rshift does not anymore truncate the shift count.
* Reserved algorithm ranges for use by applications.
* Support for DSA2.
* The new function gcry_md_debug should be used instead of the
gcry_md_start_debug and gcry_md_stop_debug macros.
* New configure option --enable-random-daemon to support a system
wide random daemon. The daemon code is experimental and not yet
very well working. It will eventually allow to keep a global
random pool for the sake of short living processes.
* Non executable stack support is now used by default on systems
supporting it.
* Support for Microsoft Windows.
* Assembler support for the AMD64 architecture.
* New configure option --enable-mpi-path for optimized builds.
* Experimental support for ECDSA; should only be used for testing.
* New control code GCRYCTL_PRINT_CONFIG to print the build
configuration.
* Minor changes to some function declarations. Buffer arguments are
now typed as void pointer. This should not affect any compilation.
Fixed two bugs in return values and clarified documentation.
* Interface changes relative to the 1.2.0 release:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
gcry_fast_random_poll NEW
gcry_md_debug NEW
gcry_sexp_nth_string NEW
GCRY_MD_SHA224 NEW
GCRY_PK_USAGE_CERT NEW
GCRY_PK_USAGE_AUTH NEW
GCRY_PK_USAGE_UNKN NEW
GCRY_PK_ECDSA NEW
GCRY_CIPHER_SEED NEW
GCRY_CIPHER_CAMELLIA128 NEW
GCRY_CIPHER_CAMELLIA192 NEW
GCRY_CIPHER_CAMELLIA256 NEW
GCRYCTL_FAKED_RANDOM_P NEW
GCRYCTL_PRINT_CONFIG NEW
GCRYCTL_SET_RNDEGD_SOCKET NEW.
gcry_mpi_scan CHANGED: Argument BUFFER is now void*.
gcry_pk_algo_name CHANGED: Returns "?" instead of NULL.
gcry_cipher_algo_name CHANGED: Returns "?" instead of "".
gcry_pk_spec_t CHANGED: Element ALIASES is now const ptr.
gcry_md_write_t CHANGED: Argument BUF is now a const void*.
gcry_md_ctl CHANGED: Argument BUFFER is now void*.
gcry_cipher_encrypt CHANGED: Arguments IN and OUT are now void*.
gcry_cipher_decrypt CHANGED: Arguments IN and OUT are now void*.
gcry_sexp_sprint CHANGED: Argument BUFFER is now void*.
gcry_create_nonce CHANGED: Argument BUFFER is now void*.
gcry_randomize CHANGED: Argument BUFFER is now void*.
gcry_cipher_register CHANGED: Argument ALGORITHM_ID is now int*.
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Noteworthy changes in version 1.2.0 (2004-04-15)
------------------------------------------------
* First stable release.
Noteworthy changes in version 1.1.94 (2004-03-29)
-------------------------------------------------
* The support for multi-threaded users goes into its third
incarnation. We removed compile time support for thread libraries.
To support the thread library of your choice, you have to set up
callback handlers at initialization time. New data structures, a
new control command, and default initializers are provided for this
purpose.
* Interface changes relative to the 1.1.93 release:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
libgcrypt-config --thread OBSOLETE
libgcrypt-pth.la REMOVED
libgcrypt-pthread.la REMOVED
GCRYCTL_SET_THREAD_CBS NEW
struct gcrypt_thread_cbs NEW
enum gcry_thread_option NEW
GCRY_THREAD_OPTION_PTH_IMPL NEW
GCRY_THREAD_OPTION_PTHREAD_IMPL NEW
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Noteworthy changes in version 1.1.93 (2004-03-06)
-------------------------------------------------
* The automatic thread library detection has finally been removed.
From now on, only linking explicitely to libgcrypt, libgcrypt-pth
or libgcrypt-pthread is supported.
Noteworthy changes in version 1.1.92 (2004-02-20)
-------------------------------------------------
* Minor bug fixes.
* Included a limited implementation of RFC2268.
* Changed API of the gcry_ac_ functions. Only a very few programs
should be affected by this.
* Interface changes relative to the 1.1.91 release:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GCRY_CIPHER_RFC2268_40 NEW.
gcry_ac_data_set CHANGED: New argument FLAGS.
gcry_ac_data_get_name CHANGED: New argument FLAGS.
gcry_ac_data_get_index CHANGED: New argument FLAGS.
gcry_ac_key_pair_generate CHANGED: New and reordered arguments.
gcry_ac_key_test CHANGED: New argument HANDLE.
gcry_ac_key_get_nbits CHANGED: New argument HANDLE.
gcry_ac_key_get_grip CHANGED: New argument HANDLE.
gcry_ac_data_search REMOVED.
gcry_ac_data_add REMOVED.
GCRY_AC_DATA_FLAG_NO_BLINDING REMOVED.
GCRY_AC_FLAG_NO_BLINDING NEW: Replaces above.
Noteworthy changes in version 1.1.91 (2003-12-19)
-------------------------------------------------
* Code cleanups and minor bug fixes.
Noteworthy changes in version 1.1.90 (2003-11-14)
-------------------------------------------------
* The use of the GCRY_WEAK_RANDOM level is now deprecated in favor of
the new gcry_create_nonce function.
* gcry_sexp_build now supports a "%b" format to include a memory buffer.
* Minor configuration fixes.
* Interface changes relative to the 1.1.44 release:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
gcry_create_nonce NEW
gcry_sexp_build ENHANCED
Noteworthy changes in version 1.1.44 (2003-10-31)
-------------------------------------------------
* Bug fixes and more code cleanups.
* Enhanced the prime API.
* Interface changes relative to the 1.1.43 release:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
gcry_prime_group_generator NEW
gcry_prime_release_factors NEW
Noteworthy changes in version 1.1.43 (2003-09-04)
-------------------------------------------------
* Bug fixes and internal code cleanups.
* Support for the Serpent cipher algorithm.
* Interface changes relative to the 1.1.42 release:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
gcry_prime_generate NEW
gcry_prime_check NEW
Noteworthy changes in version 1.1.42 (2003-07-31)
-------------------------------------------------
* Major API cleanup. Applications need to be converted to the new
API. See README.apichanges for hints on how to do that. Backward
compatibility is provided where it was possible without too much
effort and did not collide with the overall sanitization effort.
However, this is only for ease of transition. NO DEPRECATED
FUNCTION OR DATA TYPE IS CONSIDERED A PART OF THE API OR ABI AND
WILL BE DROPPED IN THE FUTURE WITHOUT CHANGING THE SONAME OF THE
LIBRARY.
* If gcrypt.h is included in sources compiled by GCC 3.1 or later,
deprecated attributes will warn about use of obsolete functions and
type definitions. You can suppress these warnings by passing
-Wno-deprecated-declarations to the gcc command.
* gcry_check_version must be called from now on to initialize the
library, it is not longer optional.
* Removed `libgcrypt errno' concept.
* Libgcrypt depends on libgpg-error, a library that provides error
codes and according functions for all GnuPG components. Functions
that used to return error codes asa `int' have been changed to
return a code of type `gcry_error_t'. All GCRYERR_* error symbols
have been removed, since they are now contained in libgpg-error
(GPG_ERR_*). All functions and types in libgpg-error have also been
wrapped in Libgcrypt. The new types are gcry_err_code_t and
gcry_err_source_t. The new functions are gcry_err_code,
gcry_err_source, gcry_error, gcry_err_make, gcry_error_from_errno,
gcry_err_make_from_errno, gcry_err_code_from_errno,
gcry_err_code_to_errno, gcry_strsource.
* New function gcry_mpi_dump to help in debugging.
* Added alternative interface for asymmetric cryptography.
* CRC-32, CRC-32 a'la RFC 1510, CRC-24 a'la RFC 2440 are now
supported.
* SHA-256, SHA-384 and SHA-512 are now supported.
* 128 bit Twofish is now supported.
* The random module won't print the "not enough random bytes
available" anymore. A new progress status is issued instead.
* CBC-MAC for block ciphers is now supported, by using a
GCRY_CIPHER_CBC_MAC cipher flag.
* CTR mode for block ciphers is now supported.
* The public RSA exponent can now be specified in key generation.
* RSA blinding is now supported and is used automatically for RSA
decryption. It can be explicitely disabled by using the
`no-blinding' symbol in the `flags' S-Expression or by using the
GCRY_AC_FLAG_DATA_NO_BLINDING flag when using the ac interface.
* gcry_sexp_canon_len does not use a `historically encoded' error
code anymore.
* Interface changes relative to the 1.1.12 release:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GCRY_MPI DEPRECATED; Use: gcry_mpi_t
GcryMPI DEPRECATED; Use: gcry_mpi_t
GCRY_SEXP DEPRECATED; Use: gcry_sexp_t
GcrySexp DEPRECATED; Use: gcry_sexp_t
GCRY_CIPHER_HD DEPRECATED; Use: gcry_cipher_hd_t
GcryCipherHd DEPRECATED; Use: gcry_cipher_hd_t
GCRY_MD_HD DEPRECATED; Use: gcry_md_hd_t
GcryMDHd DEPRECATED; Use: gcry_md_hd_t
gcry_error_t NEW
gcry_err_code_t NEW
gcry_err_source_t NEW
gcry_err_make NEW
gcry_error NEW
gcry_err_code NEW
gcry_err_source NEW
gcry_err_code_from_errno NEW
gcry_err_code_to_errno NEW
gcry_err_make_from_errno NEW
gcry_error_from_errno NEW
gcry_strsource NEW
GCRYERR_{some error code} REMOVED; Use GPG_ERR_*
from libgpg-error instead.
gcry_errno REMOVED
gcry_sexp_canon_len CHANGED
gcry_sexp_build_array NEW
gcry_mpi_scan CHANGED: New argument to separate in/out args.
gcry_mpi_print CHANGED: Ditto.
gcry_mpi_dump NEW
gcry_cipher_open CHANGED
gcry_cipher_reset NEW
gcry_cipher_register NEW
gcry_cipher_unregister NEW
gcry_cipher_list NEW
gcry_cipher_algo_keylen REPLACED macro with function.
gcry_cipher_algo_blklen REPLACED macro with function.
gcry_pk_register NEW
gcry_pk_unregister NEW
gcry_pk_list NEW
gcry_pk_decrypt ENHANCED: Allows flag to return
complete S-expression.
gcry_md_open CHANGED
gcry_md_copy CHANGED
gcry_md_is_enabled NEW
gcry_md_is_secure NEW
gcry_md_register NEW
gcry_md_unregister NEW
gcry_md_list NEW
gcry_ac_data_t NEW
gcry_ac_key_t NEW
gcry_ac_key_pair_t NEW
gcry_ac_handle_t NEW
gcry_ac_key_spec_rsa_t NEW
gcry_ac_data_new NEW
gcry_ac_data_destroy NEW
gcry_ac_data_set NEW
gcry_ac_data_copy NEW
gcry_ac_data_length NEW
gcry_ac_data_get_name NEW
gcry_ac_data_get_index NEW
gcry_ac_data_clear NEW
gcry_ac_open NEW
gcry_ac_close NEW
gcry_ac_key_init NEW
gcry_ac_key_pair_generate NEW
gcry_ac_key_pair_extract NEW
gcry_ac_key_data_get NEW
gcry_ac_key_test NEW
gcry_ac_key_get_nbits NEW
gcry_ac_key_get_grip NEW
gcry_ac_key_destroy NEW
gcry_ac_key_pair_destroy NEW
gcry_ac_data_encrypt NEW
gcry_ac_data_decrypt NEW
gcry_ac_data_sign NEW
gcry_ac_data_verify NEW
gcry_ac_id_to_name NEW
gcry_ac_name_to_id NEW
gcry_handler_progress_t NEW
gcry_handler_alloc_t NEW
gcry_handler_secure_check_t NEW
gcry_handle_realloc_t NEW
gcry_handler_free_t NEW
gcry_handler_no_mem_t NEW
gcry_handler_error_t NEW
gcry_handler_log_t NEW
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Noteworthy changes in version 1.1.12 (2003-01-20)
-------------------------------------------------
* gcry_pk_sign, gcry_pk_verify and gcry_pk_encrypt can now handle an
optional pkcs1 flags parameter in the S-expression. A similar flag
may be passed to gcry_pk_decrypt but it is only syntactically
implemented.
* New convenience macro gcry_md_get_asnoid.
* There is now some real stuff in the manual.
Noteworthy changes in version 1.1.11 (2002-12-21)
-------------------------------------------------
* Don't export internal symbols anymore (currently only for GNU systems)
* New algorithm: MD4
* Implemented ciphertext stealing.
* Smaller bugs fixes and a few new OIDs.
* Interface changes relative to the 1.1.8 release:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
gcry_cipher_cts NEW
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Noteworthy changes in version 1.1.10 (2002-09-20)
-------------------------------------------------
* Fixed shared library builds for i386, PPC and Sparc.
* Added simple benchmark tool.
* Replaced the internal mutexes by code which automatically adapts to
the used threading library. Currently Pth and Pthread are
supported. For non-ELF systems the GNU toolchain is now required..
* Added untested support to build Windows DLLs.
Noteworthy changes in version 1.1.9 (2002-08-23)
------------------------------------------------
* Support for plain old DES.
Noteworthy changes in version 1.1.8 (2002-06-25)
------------------------------------------------
* Minor cleanups and exported a few new functions.
* Interface changes relative to the 1.1.7 release:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
gcry_mpi_div NEW
gcry_mpi_mod NEW
gcry_mpi_invm NEW
gcry_mpi_swap NEW
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Noteworthy changes in version 1.1.7 (2002-05-21)
------------------------------------------------
* Libgcrypt is now distributed under the terms of the GNU Lesser
General Public License; see the README file for details.
* It is possible to use libgcrypt w/o intialized secure memory.
* Libgcrypt should now be thread safe after the initialization.
gcry_control (GCRYCRL_INITIALIZATION_FINISHED,NULL,0) should have
been called before creating additional threads.
* Interface changes relative to the 1.1.6 release:
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
GCRYCTL_DISABLE_INTERNAL_LOCKING NEW
GCRYCTL_DISABLE_SECMEM NEW
GCRYCTL_INITIALIZATION_FINISHED NEW
GCRYCTL_INITIALIZATION_FINISHED_P NEW
GCRYCTL_ANY_INITIALIZATION_P NEW
gcry_strdup NEW
gcry_sexp_create NEW
gcry_sexp_new NEW
gcry_set_progress_handler NEW
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Noteworthy changes in version 1.1.6 (2002-02-07)
------------------------------------------------
* Enhanced the S-expression conversion functions.
Noteworthy changes in version 1.1.5 (2001-12-18)
------------------------------------------------
* gcry_{cipher,md}_map_name are now able to map stringified object IDs.
* New functions gcry_sexp_canon_len and gcry_cipher_mode_from_oid.
* Closed some memory leaks.
Noteworthy changes in version 1.1.4 (2001-08-03)
------------------------------------------------
* Arcfour does now work.
* Some minor fixes.
* Added a first test program
* Migrated to autoconf 2.52.
Noteworthy changes in version 1.1.3 (2001-05-31)
------------------------------------------------
* First release of Libgcrypt which is a result of splitting GnuPG
into into libgcrypt and GnuPG.
Copyright 2001, 2002, 2003, 2004, 2007, 2008 Free Software Foundation, Inc.
This file is free software; as a special exception the author gives
unlimited permission to copy and/or distribute it, with or without
modifications, as long as this notice is preserved.
This file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
diff --git a/cipher/rsa.c b/cipher/rsa.c
index 72ee8a8b..434fd8ba 100644
--- a/cipher/rsa.c
+++ b/cipher/rsa.c
@@ -1,1106 +1,1107 @@
/* rsa.c - RSA implementation
* Copyright (C) 1997, 1998, 1999 by Werner Koch (dd9jn)
* Copyright (C) 2000, 2001, 2002, 2003, 2008 Free Software Foundation, Inc.
*
* This file is part of Libgcrypt.
*
* Libgcrypt is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* Libgcrypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
/* This code uses an algorithm protected by U.S. Patent #4,405,829
which expired on September 20, 2000. The patent holder placed that
patent into the public domain on Sep 6th, 2000.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include "g10lib.h"
#include "mpi.h"
#include "cipher.h"
typedef struct
{
gcry_mpi_t n; /* modulus */
gcry_mpi_t e; /* exponent */
} RSA_public_key;
typedef struct
{
gcry_mpi_t n; /* public modulus */
gcry_mpi_t e; /* public exponent */
gcry_mpi_t d; /* exponent */
gcry_mpi_t p; /* prime p. */
gcry_mpi_t q; /* prime q. */
gcry_mpi_t u; /* inverse of p mod q. */
} RSA_secret_key;
/* A sample 1024 bit RSA key used for the selftests. */
static const char sample_secret_key[] =
"(private-key"
" (rsa"
" (n #00e0ce96f90b6c9e02f3922beada93fe50a875eac6bcc18bb9a9cf2e84965caa"
" 2d1ff95a7f542465c6c0c19d276e4526ce048868a7a914fd343cc3a87dd74291"
" ffc565506d5bbb25cbac6a0e2dd1f8bcaab0d4a29c2f37c950f363484bf269f7"
" 891440464baf79827e03a36e70b814938eebdc63e964247be75dc58b014b7ea251#)"
" (e #010001#)"
" (d #046129f2489d71579be0a75fe029bd6cdb574ebf57ea8a5b0fda942cab943b11"
" 7d7bb95e5d28875e0f9fc5fcc06a72f6d502464dabded78ef6b716177b83d5bd"
" c543dc5d3fed932e59f5897e92e6f58a0f33424106a3b6fa2cbf877510e4ac21"
" c3ee47851e97d12996222ac3566d4ccb0b83d164074abf7de655fc2446da1781#)"
" (p #00e861b700e17e8afe6837e7512e35b6ca11d0ae47d8b85161c67baf64377213"
" fe52d772f2035b3ca830af41d8a4120e1c1c70d12cc22f00d28d31dd48a8d424f1#)"
" (q #00f7a7ca5367c661f8e62df34f0d05c10c88e5492348dd7bddc942c9a8f369f9"
" 35a07785d2db805215ed786e4285df1658eed3ce84f469b81b50d358407b4ad361#)"
" (u #304559a9ead56d2309d203811a641bb1a09626bc8eb36fffa23c968ec5bd891e"
" ebbafc73ae666e01ba7c8990bae06cc2bbe10b75e69fcacb353a6473079d8e9b#)))";
/* A sample 1024 bit RSA key used for the selftests (public only). */
static const char sample_public_key[] =
"(public-key"
" (rsa"
" (n #00e0ce96f90b6c9e02f3922beada93fe50a875eac6bcc18bb9a9cf2e84965caa"
" 2d1ff95a7f542465c6c0c19d276e4526ce048868a7a914fd343cc3a87dd74291"
" ffc565506d5bbb25cbac6a0e2dd1f8bcaab0d4a29c2f37c950f363484bf269f7"
" 891440464baf79827e03a36e70b814938eebdc63e964247be75dc58b014b7ea251#)"
" (e #010001#)))";
static int test_keys (RSA_secret_key *sk, unsigned nbits);
static gpg_err_code_t generate (RSA_secret_key *sk,
unsigned int nbits, unsigned long use_e,
int transient_key);
static int check_secret_key (RSA_secret_key *sk);
static void public (gcry_mpi_t output, gcry_mpi_t input, RSA_public_key *skey);
static void secret (gcry_mpi_t output, gcry_mpi_t input, RSA_secret_key *skey);
/* Check that a freshly generated key actually works. Returns 0 on success. */
static int
test_keys (RSA_secret_key *sk, unsigned int nbits)
{
int result = -1; /* Default to failure. */
RSA_public_key pk;
gcry_mpi_t plaintext = gcry_mpi_new (nbits);
gcry_mpi_t ciphertext = gcry_mpi_new (nbits);
gcry_mpi_t decr_plaintext = gcry_mpi_new (nbits);
gcry_mpi_t signature = gcry_mpi_new (nbits);
/* Put the relevant parameters into a public key structure. */
pk.n = sk->n;
pk.e = sk->e;
/* Create a random plaintext. */
gcry_mpi_randomize (plaintext, nbits, GCRY_WEAK_RANDOM);
/* Encrypt using the public key. */
public (ciphertext, plaintext, &pk);
/* Check that the cipher text does not match the plaintext. */
if (!gcry_mpi_cmp (ciphertext, plaintext))
goto leave; /* Ciphertext is identical to the plaintext. */
/* Decrypt using the secret key. */
secret (decr_plaintext, ciphertext, sk);
/* Check that the decrypted plaintext matches the original plaintext. */
if (gcry_mpi_cmp (decr_plaintext, plaintext))
goto leave; /* Plaintext does not match. */
/* Create another random plaintext as data for signature checking. */
gcry_mpi_randomize (plaintext, nbits, GCRY_WEAK_RANDOM);
/* Use the RSA secret function to create a signature of the plaintext. */
secret (signature, plaintext, sk);
/* Use the RSA public function to verify this signature. */
public (decr_plaintext, signature, &pk);
if (gcry_mpi_cmp (decr_plaintext, plaintext))
goto leave; /* Signature does not match. */
/* Modify the signature and check that the signing fails. */
gcry_mpi_add_ui (signature, signature, 1);
public (decr_plaintext, signature, &pk);
if (!gcry_mpi_cmp (decr_plaintext, plaintext))
goto leave; /* Signature matches but should not. */
result = 0; /* All tests succeeded. */
leave:
gcry_mpi_release (signature);
gcry_mpi_release (decr_plaintext);
gcry_mpi_release (ciphertext);
gcry_mpi_release (plaintext);
return result;
}
/* Callback used by the prime generation to test whether the exponent
is suitable. Returns 0 if the test has been passed. */
static int
check_exponent (void *arg, gcry_mpi_t a)
{
gcry_mpi_t e = arg;
gcry_mpi_t tmp;
int result;
mpi_sub_ui (a, a, 1);
tmp = _gcry_mpi_alloc_like (a);
result = !gcry_mpi_gcd(tmp, e, a); /* GCD is not 1. */
gcry_mpi_release (tmp);
mpi_add_ui (a, a, 1);
return result;
}
/****************
* Generate a key pair with a key of size NBITS.
* USE_E = 0 let Libcgrypt decide what exponent to use.
* = 1 request the use of a "secure" exponent; this is required by some
* specification to be 65537.
- * > 2 Try starting at this value until a working exponent is found.
+ * > 2 Use this public exponent. If the given exponent
+ * is not odd one is internally added to it.
* TRANSIENT_KEY: If true, generate the primes using the standard RNG.
* Returns: 2 structures filled with all needed values
*/
static gpg_err_code_t
generate (RSA_secret_key *sk, unsigned int nbits, unsigned long use_e,
int transient_key)
{
gcry_mpi_t p, q; /* the two primes */
gcry_mpi_t d; /* the private key */
gcry_mpi_t u;
gcry_mpi_t t1, t2;
gcry_mpi_t n; /* the public key */
gcry_mpi_t e; /* the exponent */
gcry_mpi_t phi; /* helper: (p-1)(q-1) */
gcry_mpi_t g;
gcry_mpi_t f;
gcry_random_level_t random_level;
if (fips_mode ())
{
if (nbits < 1024)
return GPG_ERR_INV_VALUE;
if (transient_key)
return GPG_ERR_INV_VALUE;
}
/* The random quality depends on the transient_key flag. */
random_level = transient_key ? GCRY_STRONG_RANDOM : GCRY_VERY_STRONG_RANDOM;
/* Make sure that nbits is even so that we generate p, q of equal size. */
if ( (nbits&1) )
nbits++;
if (use_e == 1) /* Alias for a secure value. */
use_e = 65537; /* as demanded by Spinx. */
/* Public exponent:
In general we use 41 as this is quite fast and more secure than the
commonly used 17. Benchmarking the RSA verify function
with a 1024 bit key yields (2001-11-08):
e=17 0.54 ms
e=41 0.75 ms
e=257 0.95 ms
e=65537 1.80 ms
*/
e = mpi_alloc( (32+BITS_PER_MPI_LIMB-1)/BITS_PER_MPI_LIMB );
if (!use_e)
mpi_set_ui (e, 41); /* This is a reasonable secure and fast value */
else
{
use_e |= 1; /* make sure this is odd */
mpi_set_ui (e, use_e);
}
n = gcry_mpi_new (nbits);
p = q = NULL;
do
{
/* select two (very secret) primes */
if (p)
gcry_mpi_release (p);
if (q)
gcry_mpi_release (q);
if (use_e)
{ /* Do an extra test to ensure that the given exponent is
suitable. */
p = _gcry_generate_secret_prime (nbits/2, random_level,
check_exponent, e);
q = _gcry_generate_secret_prime (nbits/2, random_level,
check_exponent, e);
}
else
{ /* We check the exponent later. */
p = _gcry_generate_secret_prime (nbits/2, random_level, NULL, NULL);
q = _gcry_generate_secret_prime (nbits/2, random_level, NULL, NULL);
}
if (mpi_cmp (p, q) > 0 ) /* p shall be smaller than q (for calc of u)*/
mpi_swap(p,q);
/* calculate the modulus */
mpi_mul( n, p, q );
}
while ( mpi_get_nbits(n) != nbits );
/* calculate Euler totient: phi = (p-1)(q-1) */
t1 = mpi_alloc_secure( mpi_get_nlimbs(p) );
t2 = mpi_alloc_secure( mpi_get_nlimbs(p) );
phi = gcry_mpi_snew ( nbits );
g = gcry_mpi_snew ( nbits );
f = gcry_mpi_snew ( nbits );
mpi_sub_ui( t1, p, 1 );
mpi_sub_ui( t2, q, 1 );
mpi_mul( phi, t1, t2 );
gcry_mpi_gcd(g, t1, t2);
mpi_fdiv_q(f, phi, g);
while (!gcry_mpi_gcd(t1, e, phi)) /* (while gcd is not 1) */
{
if (use_e)
BUG (); /* The prime generator already made sure that we
never can get to here. */
mpi_add_ui (e, e, 2);
}
/* calculate the secret key d = e^1 mod phi */
d = gcry_mpi_snew ( nbits );
mpi_invm(d, e, f );
/* calculate the inverse of p and q (used for chinese remainder theorem)*/
u = gcry_mpi_snew ( nbits );
mpi_invm(u, p, q );
if( DBG_CIPHER )
{
log_mpidump(" p= ", p );
log_mpidump(" q= ", q );
log_mpidump("phi= ", phi );
log_mpidump(" g= ", g );
log_mpidump(" f= ", f );
log_mpidump(" n= ", n );
log_mpidump(" e= ", e );
log_mpidump(" d= ", d );
log_mpidump(" u= ", u );
}
gcry_mpi_release (t1);
gcry_mpi_release (t2);
gcry_mpi_release (phi);
gcry_mpi_release (f);
gcry_mpi_release (g);
sk->n = n;
sk->e = e;
sk->p = p;
sk->q = q;
sk->d = d;
sk->u = u;
/* Now we can test our keys. */
if (test_keys (sk, nbits - 64))
{
gcry_mpi_release (sk->n); sk->n = NULL;
gcry_mpi_release (sk->e); sk->e = NULL;
gcry_mpi_release (sk->p); sk->p = NULL;
gcry_mpi_release (sk->q); sk->q = NULL;
gcry_mpi_release (sk->d); sk->d = NULL;
gcry_mpi_release (sk->u); sk->u = NULL;
fips_signal_error ("self-test after key generation failed");
return GPG_ERR_SELFTEST_FAILED;
}
return 0;
}
/****************
* Test wether the secret key is valid.
* Returns: true if this is a valid key.
*/
static int
check_secret_key( RSA_secret_key *sk )
{
int rc;
gcry_mpi_t temp = mpi_alloc( mpi_get_nlimbs(sk->p)*2 );
mpi_mul(temp, sk->p, sk->q );
rc = mpi_cmp( temp, sk->n );
mpi_free(temp);
return !rc;
}
/****************
* Public key operation. Encrypt INPUT with PKEY and put result into OUTPUT.
*
* c = m^e mod n
*
* Where c is OUTPUT, m is INPUT and e,n are elements of PKEY.
*/
static void
public(gcry_mpi_t output, gcry_mpi_t input, RSA_public_key *pkey )
{
if( output == input ) /* powm doesn't like output and input the same */
{
gcry_mpi_t x = mpi_alloc( mpi_get_nlimbs(input)*2 );
mpi_powm( x, input, pkey->e, pkey->n );
mpi_set(output, x);
mpi_free(x);
}
else
mpi_powm( output, input, pkey->e, pkey->n );
}
#if 0
static void
stronger_key_check ( RSA_secret_key *skey )
{
gcry_mpi_t t = mpi_alloc_secure ( 0 );
gcry_mpi_t t1 = mpi_alloc_secure ( 0 );
gcry_mpi_t t2 = mpi_alloc_secure ( 0 );
gcry_mpi_t phi = mpi_alloc_secure ( 0 );
/* check that n == p * q */
mpi_mul( t, skey->p, skey->q);
if (mpi_cmp( t, skey->n) )
log_info ( "RSA Oops: n != p * q\n" );
/* check that p is less than q */
if( mpi_cmp( skey->p, skey->q ) > 0 )
{
log_info ("RSA Oops: p >= q - fixed\n");
_gcry_mpi_swap ( skey->p, skey->q);
}
/* check that e divides neither p-1 nor q-1 */
mpi_sub_ui(t, skey->p, 1 );
mpi_fdiv_r(t, t, skey->e );
if ( !mpi_cmp_ui( t, 0) )
log_info ( "RSA Oops: e divides p-1\n" );
mpi_sub_ui(t, skey->q, 1 );
mpi_fdiv_r(t, t, skey->e );
if ( !mpi_cmp_ui( t, 0) )
log_info ( "RSA Oops: e divides q-1\n" );
/* check that d is correct */
mpi_sub_ui( t1, skey->p, 1 );
mpi_sub_ui( t2, skey->q, 1 );
mpi_mul( phi, t1, t2 );
gcry_mpi_gcd(t, t1, t2);
mpi_fdiv_q(t, phi, t);
mpi_invm(t, skey->e, t );
if ( mpi_cmp(t, skey->d ) )
{
log_info ( "RSA Oops: d is wrong - fixed\n");
mpi_set (skey->d, t);
_gcry_log_mpidump (" fixed d", skey->d);
}
/* check for correctness of u */
mpi_invm(t, skey->p, skey->q );
if ( mpi_cmp(t, skey->u ) )
{
log_info ( "RSA Oops: u is wrong - fixed\n");
mpi_set (skey->u, t);
_gcry_log_mpidump (" fixed u", skey->u);
}
log_info ( "RSA secret key check finished\n");
mpi_free (t);
mpi_free (t1);
mpi_free (t2);
mpi_free (phi);
}
#endif
/****************
* Secret key operation. Encrypt INPUT with SKEY and put result into OUTPUT.
*
* m = c^d mod n
*
* Or faster:
*
* m1 = c ^ (d mod (p-1)) mod p
* m2 = c ^ (d mod (q-1)) mod q
* h = u * (m2 - m1) mod q
* m = m1 + h * p
*
* Where m is OUTPUT, c is INPUT and d,n,p,q,u are elements of SKEY.
*/
static void
secret(gcry_mpi_t output, gcry_mpi_t input, RSA_secret_key *skey )
{
if (!skey->p || !skey->q || !skey->u)
{
mpi_powm (output, input, skey->d, skey->n);
}
else
{
gcry_mpi_t m1 = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 );
gcry_mpi_t m2 = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 );
gcry_mpi_t h = mpi_alloc_secure( mpi_get_nlimbs(skey->n)+1 );
/* m1 = c ^ (d mod (p-1)) mod p */
mpi_sub_ui( h, skey->p, 1 );
mpi_fdiv_r( h, skey->d, h );
mpi_powm( m1, input, h, skey->p );
/* m2 = c ^ (d mod (q-1)) mod q */
mpi_sub_ui( h, skey->q, 1 );
mpi_fdiv_r( h, skey->d, h );
mpi_powm( m2, input, h, skey->q );
/* h = u * ( m2 - m1 ) mod q */
mpi_sub( h, m2, m1 );
if ( mpi_is_neg( h ) )
mpi_add ( h, h, skey->q );
mpi_mulm( h, skey->u, h, skey->q );
/* m = m2 + h * p */
mpi_mul ( h, h, skey->p );
mpi_add ( output, m1, h );
mpi_free ( h );
mpi_free ( m1 );
mpi_free ( m2 );
}
}
/* Perform RSA blinding. */
static gcry_mpi_t
rsa_blind (gcry_mpi_t x, gcry_mpi_t r, gcry_mpi_t e, gcry_mpi_t n)
{
/* A helper. */
gcry_mpi_t a;
/* Result. */
gcry_mpi_t y;
a = gcry_mpi_snew (gcry_mpi_get_nbits (n));
y = gcry_mpi_snew (gcry_mpi_get_nbits (n));
/* Now we calculate: y = (x * r^e) mod n, where r is the random
number, e is the public exponent, x is the non-blinded data and n
is the RSA modulus. */
gcry_mpi_powm (a, r, e, n);
gcry_mpi_mulm (y, a, x, n);
gcry_mpi_release (a);
return y;
}
/* Undo RSA blinding. */
static gcry_mpi_t
rsa_unblind (gcry_mpi_t x, gcry_mpi_t ri, gcry_mpi_t n)
{
gcry_mpi_t y;
y = gcry_mpi_snew (gcry_mpi_get_nbits (n));
/* Here we calculate: y = (x * r^-1) mod n, where x is the blinded
decrypted data, ri is the modular multiplicative inverse of r and
n is the RSA modulus. */
gcry_mpi_mulm (y, ri, x, n);
return y;
}
/*********************************************
************** interface ******************
*********************************************/
static gcry_err_code_t
rsa_generate_ext (int algo, unsigned int nbits, unsigned int qbits,
unsigned long use_e,
const char *name, const gcry_sexp_t domain,
unsigned int keygen_flags,
gcry_mpi_t *skey, gcry_mpi_t **retfactors)
{
RSA_secret_key sk;
gpg_err_code_t ec;
int i;
(void)algo;
(void)qbits;
(void)name;
(void)domain;
ec = generate (&sk, nbits, use_e,
!!(keygen_flags & PUBKEY_FLAG_TRANSIENT_KEY) );
if (!ec)
{
skey[0] = sk.n;
skey[1] = sk.e;
skey[2] = sk.d;
skey[3] = sk.p;
skey[4] = sk.q;
skey[5] = sk.u;
/* Make an empty list of factors. */
*retfactors = gcry_calloc ( 1, sizeof **retfactors );
if (!*retfactors)
{
ec = gpg_err_code_from_syserror ();
for (i=0; i <= 5; i++)
{
gcry_mpi_release (skey[i]);
skey[i] = NULL;
}
}
else
ec = 0;
}
return ec;
}
static gcry_err_code_t
rsa_generate (int algo, unsigned int nbits, unsigned long use_e,
gcry_mpi_t *skey, gcry_mpi_t **retfactors)
{
return rsa_generate_ext (algo, nbits, 0, use_e, NULL, NULL, 0,
skey, retfactors);
}
static gcry_err_code_t
rsa_check_secret_key (int algo, gcry_mpi_t *skey)
{
gcry_err_code_t err = GPG_ERR_NO_ERROR;
RSA_secret_key sk;
(void)algo;
sk.n = skey[0];
sk.e = skey[1];
sk.d = skey[2];
sk.p = skey[3];
sk.q = skey[4];
sk.u = skey[5];
if (!sk.p || !sk.q || !sk.u)
err = GPG_ERR_NO_OBJ; /* To check the key we need the optional
parameters. */
else if (!check_secret_key (&sk))
err = GPG_ERR_PUBKEY_ALGO;
return err;
}
static gcry_err_code_t
rsa_encrypt (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
gcry_mpi_t *pkey, int flags)
{
RSA_public_key pk;
(void)algo;
(void)flags;
pk.n = pkey[0];
pk.e = pkey[1];
resarr[0] = mpi_alloc (mpi_get_nlimbs (pk.n));
public (resarr[0], data, &pk);
return GPG_ERR_NO_ERROR;
}
static gcry_err_code_t
rsa_decrypt (int algo, gcry_mpi_t *result, gcry_mpi_t *data,
gcry_mpi_t *skey, int flags)
{
RSA_secret_key sk;
gcry_mpi_t r = MPI_NULL; /* Random number needed for blinding. */
gcry_mpi_t ri = MPI_NULL; /* Modular multiplicative inverse of
r. */
gcry_mpi_t x = MPI_NULL; /* Data to decrypt. */
gcry_mpi_t y; /* Result. */
(void)algo;
/* Extract private key. */
sk.n = skey[0];
sk.e = skey[1];
sk.d = skey[2];
sk.p = skey[3]; /* Optional. */
sk.q = skey[4]; /* Optional. */
sk.u = skey[5]; /* Optional. */
y = gcry_mpi_snew (gcry_mpi_get_nbits (sk.n));
/* We use blinding by default to mitigate timing attacks which can
be practically mounted over the network as shown by Brumley and
Boney in 2003. */
if (! (flags & PUBKEY_FLAG_NO_BLINDING))
{
/* Initialize blinding. */
/* First, we need a random number r between 0 and n - 1, which
is relatively prime to n (i.e. it is neither p nor q). */
r = gcry_mpi_snew (gcry_mpi_get_nbits (sk.n));
ri = gcry_mpi_snew (gcry_mpi_get_nbits (sk.n));
gcry_mpi_randomize (r, gcry_mpi_get_nbits (sk.n),
GCRY_STRONG_RANDOM);
gcry_mpi_mod (r, r, sk.n);
/* Calculate inverse of r. It practically impossible that the
follwing test fails, thus we do not add code to release
allocated resources. */
if (!gcry_mpi_invm (ri, r, sk.n))
return GPG_ERR_INTERNAL;
}
if (! (flags & PUBKEY_FLAG_NO_BLINDING))
x = rsa_blind (data[0], r, sk.e, sk.n);
else
x = data[0];
/* Do the encryption. */
secret (y, x, &sk);
if (! (flags & PUBKEY_FLAG_NO_BLINDING))
{
/* Undo blinding. */
gcry_mpi_t a = gcry_mpi_copy (y);
gcry_mpi_release (y);
y = rsa_unblind (a, ri, sk.n);
gcry_mpi_release (a);
}
if (! (flags & PUBKEY_FLAG_NO_BLINDING))
{
/* Deallocate resources needed for blinding. */
gcry_mpi_release (x);
gcry_mpi_release (r);
gcry_mpi_release (ri);
}
/* Copy out result. */
*result = y;
return GPG_ERR_NO_ERROR;
}
static gcry_err_code_t
rsa_sign (int algo, gcry_mpi_t *resarr, gcry_mpi_t data, gcry_mpi_t *skey)
{
RSA_secret_key sk;
(void)algo;
sk.n = skey[0];
sk.e = skey[1];
sk.d = skey[2];
sk.p = skey[3];
sk.q = skey[4];
sk.u = skey[5];
resarr[0] = mpi_alloc( mpi_get_nlimbs (sk.n));
secret (resarr[0], data, &sk);
return GPG_ERR_NO_ERROR;
}
static gcry_err_code_t
rsa_verify (int algo, gcry_mpi_t hash, gcry_mpi_t *data, gcry_mpi_t *pkey,
int (*cmp) (void *opaque, gcry_mpi_t tmp),
void *opaquev)
{
RSA_public_key pk;
gcry_mpi_t result;
gcry_err_code_t rc;
(void)algo;
(void)cmp;
(void)opaquev;
pk.n = pkey[0];
pk.e = pkey[1];
result = gcry_mpi_new ( 160 );
public( result, data[0], &pk );
#ifdef IS_DEVELOPMENT_VERSION
if (DBG_CIPHER)
{
log_mpidump ("rsa verify result:", result );
log_mpidump (" hash:", hash );
}
#endif /*IS_DEVELOPMENT_VERSION*/
/*rc = (*cmp)( opaquev, result );*/
rc = mpi_cmp (result, hash) ? GPG_ERR_BAD_SIGNATURE : GPG_ERR_NO_ERROR;
gcry_mpi_release (result);
return rc;
}
static unsigned int
rsa_get_nbits (int algo, gcry_mpi_t *pkey)
{
(void)algo;
return mpi_get_nbits (pkey[0]);
}
/* Compute a keygrip. MD is the hash context which we are going to
update. KEYPARAM is an S-expression with the key parameters, this
is usually a public key but may also be a secret key. An example
of such an S-expression is:
(rsa
(n #00B...#)
(e #010001#))
PKCS-15 says that for RSA only the modulus should be hashed -
however, it is not clear wether this is meant to use the raw bytes
(assuming this is an unsigned integer) or whether the DER required
0 should be prefixed. We hash the raw bytes. */
static gpg_err_code_t
compute_keygrip (gcry_md_hd_t md, gcry_sexp_t keyparam)
{
gcry_sexp_t l1;
const char *data;
size_t datalen;
l1 = gcry_sexp_find_token (keyparam, "n", 1);
if (!l1)
return GPG_ERR_NO_OBJ;
data = gcry_sexp_nth_data (l1, 1, &datalen);
if (!data)
{
gcry_sexp_release (l1);
return GPG_ERR_NO_OBJ;
}
gcry_md_write (md, data, datalen);
gcry_sexp_release (l1);
return 0;
}
/*
Self-test section.
*/
static const char *
selftest_sign_1024 (gcry_sexp_t pkey, gcry_sexp_t skey)
{
static const char sample_data[] =
"(data (flags pkcs1)"
" (hash sha1 #11223344556677889900aabbccddeeff10203040#))";
static const char sample_data_bad[] =
"(data (flags pkcs1)"
" (hash sha1 #11223344556677889900aabbccddeeff80203040#))";
const char *errtxt = NULL;
gcry_error_t err;
gcry_sexp_t data = NULL;
gcry_sexp_t data_bad = NULL;
gcry_sexp_t sig = NULL;
err = gcry_sexp_sscan (&data, NULL,
sample_data, strlen (sample_data));
if (!err)
err = gcry_sexp_sscan (&data_bad, NULL,
sample_data_bad, strlen (sample_data_bad));
if (err)
{
errtxt = "converting data failed";
goto leave;
}
err = gcry_pk_sign (&sig, data, skey);
if (err)
{
errtxt = "signing failed";
goto leave;
}
err = gcry_pk_verify (sig, data, pkey);
if (err)
{
errtxt = "verify failed";
goto leave;
}
err = gcry_pk_verify (sig, data_bad, pkey);
if (gcry_err_code (err) != GPG_ERR_BAD_SIGNATURE)
{
errtxt = "bad signature not detected";
goto leave;
}
leave:
gcry_sexp_release (sig);
gcry_sexp_release (data_bad);
gcry_sexp_release (data);
return errtxt;
}
/* Given an S-expression ENCR_DATA of the form:
(enc-val
(rsa
(a a-value)))
as returned by gcry_pk_decrypt, return the the A-VALUE. On error,
return NULL. */
static gcry_mpi_t
extract_a_from_sexp (gcry_sexp_t encr_data)
{
gcry_sexp_t l1, l2, l3;
gcry_mpi_t a_value;
l1 = gcry_sexp_find_token (encr_data, "enc-val", 0);
if (!l1)
return NULL;
l2 = gcry_sexp_find_token (l1, "rsa", 0);
gcry_sexp_release (l1);
if (!l2)
return NULL;
l3 = gcry_sexp_find_token (l2, "a", 0);
gcry_sexp_release (l2);
if (!l3)
return NULL;
a_value = gcry_sexp_nth_mpi (l3, 1, 0);
gcry_sexp_release (l3);
return a_value;
}
static const char *
selftest_encr_1024 (gcry_sexp_t pkey, gcry_sexp_t skey)
{
const char *errtxt = NULL;
gcry_error_t err;
const unsigned int nbits = 1000; /* Encrypt 1000 random bits. */
gcry_mpi_t plaintext = NULL;
gcry_sexp_t plain = NULL;
gcry_sexp_t encr = NULL;
gcry_mpi_t ciphertext = NULL;
gcry_sexp_t decr = NULL;
gcry_mpi_t decr_plaintext = NULL;
gcry_sexp_t tmplist = NULL;
/* Create plaintext. The plaintext is actually a big integer number. */
plaintext = gcry_mpi_new (nbits);
gcry_mpi_randomize (plaintext, nbits, GCRY_WEAK_RANDOM);
/* Put the plaintext into an S-expression. */
err = gcry_sexp_build (&plain, NULL,
"(data (flags raw) (value %m))", plaintext);
if (err)
{
errtxt = "converting data failed";
goto leave;
}
/* Encrypt. */
err = gcry_pk_encrypt (&encr, plain, pkey);
if (err)
{
errtxt = "encrypt failed";
goto leave;
}
/* Extraxt the ciphertext from the returned S-expression. */
/*gcry_sexp_dump (encr);*/
ciphertext = extract_a_from_sexp (encr);
if (!ciphertext)
{
errtxt = "gcry_pk_decrypt returned garbage";
goto leave;
}
/* Check that the ciphertext does no match the plaintext. */
/* _gcry_log_mpidump ("plaintext", plaintext); */
/* _gcry_log_mpidump ("ciphertxt", ciphertext); */
if (!gcry_mpi_cmp (plaintext, ciphertext))
{
errtxt = "ciphertext matches plaintext";
goto leave;
}
/* Decrypt. */
err = gcry_pk_decrypt (&decr, encr, skey);
if (err)
{
errtxt = "decrypt failed";
goto leave;
}
/* Extract the decrypted data from the S-expression. Note that the
output of gcry_pk_decrypt depends on whether a flags lists occurs
in its input data. Because we passed the output of
gcry_pk_encrypt directly to gcry_pk_decrypt, such a flag value
won't be there as of today. To be prepared for future changes we
take care of it anyway. */
tmplist = gcry_sexp_find_token (decr, "value", 0);
if (tmplist)
decr_plaintext = gcry_sexp_nth_mpi (tmplist, 1, GCRYMPI_FMT_USG);
else
decr_plaintext = gcry_sexp_nth_mpi (decr, 0, GCRYMPI_FMT_USG);
if (!decr_plaintext)
{
errtxt = "decrypt returned no plaintext";
goto leave;
}
/* Check that the decrypted plaintext matches the original plaintext. */
if (gcry_mpi_cmp (plaintext, decr_plaintext))
{
errtxt = "mismatch";
goto leave;
}
leave:
gcry_sexp_release (tmplist);
gcry_mpi_release (decr_plaintext);
gcry_sexp_release (decr);
gcry_mpi_release (ciphertext);
gcry_sexp_release (encr);
gcry_sexp_release (plain);
gcry_mpi_release (plaintext);
return errtxt;
}
static gpg_err_code_t
selftests_rsa (selftest_report_func_t report)
{
const char *what;
const char *errtxt;
gcry_error_t err;
gcry_sexp_t skey = NULL;
gcry_sexp_t pkey = NULL;
/* Convert the S-expressions into the internal representation. */
what = "convert";
err = gcry_sexp_sscan (&skey, NULL,
sample_secret_key, strlen (sample_secret_key));
if (!err)
err = gcry_sexp_sscan (&pkey, NULL,
sample_public_key, strlen (sample_public_key));
if (err)
{
errtxt = gcry_strerror (err);
goto failed;
}
what = "key consistency";
err = gcry_pk_testkey (skey);
if (err)
{
errtxt = gcry_strerror (err);
goto failed;
}
what = "sign";
errtxt = selftest_sign_1024 (pkey, skey);
if (errtxt)
goto failed;
what = "encrypt";
errtxt = selftest_encr_1024 (pkey, skey);
if (errtxt)
goto failed;
gcry_sexp_release (pkey);
gcry_sexp_release (skey);
return 0; /* Succeeded. */
failed:
gcry_sexp_release (pkey);
gcry_sexp_release (skey);
if (report)
report ("pubkey", GCRY_PK_RSA, what, errtxt);
return GPG_ERR_SELFTEST_FAILED;
}
/* Run a full self-test for ALGO and return 0 on success. */
static gpg_err_code_t
run_selftests (int algo, int extended, selftest_report_func_t report)
{
gpg_err_code_t ec;
(void)extended;
switch (algo)
{
case GCRY_PK_RSA:
ec = selftests_rsa (report);
break;
default:
ec = GPG_ERR_PUBKEY_ALGO;
break;
}
return ec;
}
static const char *rsa_names[] =
{
"rsa",
"openpgp-rsa",
"oid.1.2.840.113549.1.1.1",
NULL,
};
gcry_pk_spec_t _gcry_pubkey_spec_rsa =
{
"RSA", rsa_names,
"ne", "nedpqu", "a", "s", "n",
GCRY_PK_USAGE_SIGN | GCRY_PK_USAGE_ENCR,
rsa_generate,
rsa_check_secret_key,
rsa_encrypt,
rsa_decrypt,
rsa_sign,
rsa_verify,
rsa_get_nbits,
};
pk_extra_spec_t _gcry_pubkey_extraspec_rsa =
{
run_selftests,
rsa_generate_ext,
compute_keygrip
};
diff --git a/configure.ac b/configure.ac
index 4b735991..de41ea5a 100644
--- a/configure.ac
+++ b/configure.ac
@@ -1,1163 +1,1163 @@
# Configure.ac script for Libgcrypt
# Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2006,
# 2007, 2008 Free Software Foundation, Inc.
#
# This file is part of Libgcrypt.
#
# Libgcrypt is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# Libgcrypt is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, see <http://www.gnu.org/licenses/>.
# (Process this file with autoconf to produce a configure script.)
AC_REVISION($Revision$)
AC_PREREQ(2.60)
min_automake_version="1.10"
# Remember to change the version number immediately *after* a release.
# Set my_issvn to "yes" for non-released code. Remember to run an
# "svn up" and "autogen.sh" right before creating a distribution.
-m4_define([my_version], [1.4.3])
-m4_define([my_issvn], [no])
+m4_define([my_version], [1.4.4])
+m4_define([my_issvn], [yes])
m4_define([svn_revision], m4_esyscmd([printf "%d" $(svn info 2>/dev/null \
| sed -n '/^Revision:/ s/[^0-9]//gp'|head -1)]))
AC_INIT([libgcrypt],
[my_version[]m4_if(my_issvn,[yes],[-svn[]svn_revision])],
[bug-libgcrypt@gnupg.org])
# LT Version numbers, remember to change them just *before* a release.
# (Interfaces removed: CURRENT++, AGE=0, REVISION=0)
# (Interfaces added: CURRENT++, AGE++, REVISION=0)
# (No interfaces changed: REVISION++)
LIBGCRYPT_LT_CURRENT=16
LIBGCRYPT_LT_AGE=5
LIBGCRYPT_LT_REVISION=1
# If the API is changed in an incompatible way: increment the next counter.
LIBGCRYPT_CONFIG_API_VERSION=1
NEED_GPG_ERROR_VERSION=1.4
is_development_version=my_issvn
BUILD_REVISION=svn_revision
PACKAGE=$PACKAGE_NAME
VERSION=$PACKAGE_VERSION
AC_CONFIG_SRCDIR([src/libgcrypt.vers])
AM_INIT_AUTOMAKE($PACKAGE, $VERSION)
AM_CONFIG_HEADER(config.h)
AC_CANONICAL_HOST
AM_MAINTAINER_MODE
AH_TOP([
#ifndef _GCRYPT_CONFIG_H_INCLUDED
#define _GCRYPT_CONFIG_H_INCLUDED
/* need this, because some autoconf tests rely on this (e.g. stpcpy)
* and it should be used for new programs */
#define _GNU_SOURCE 1
])
AH_BOTTOM([
#define _GCRYPT_IN_LIBGCRYPT 1
/* If the configure check for endianness has been disabled, get it from
OS macros. This is intended for making fat binary builds on OS X. */
#ifdef DISABLED_ENDIAN_CHECK
# if defined(__BIG_ENDIAN__)
# define WORDS_BIGENDIAN 1
# elif defined(__LITTLE_ENDIAN__)
# undef WORDS_BIGENDIAN
# else
# error "No endianness found"
# endif
#endif /*DISABLED_ENDIAN_CHECK*/
/* We basically use the original Camellia source. Make sure the symbols
properly prefixed. */
#define CAMELLIA_EXT_SYM_PREFIX _gcry_
/* This error code is only available with gpg-error 1.7. Thus
we define it here with the usual gcry prefix. */
#define GCRY_GPG_ERR_NOT_OPERATIONAL 176
#endif /*_GCRYPT_CONFIG_H_INCLUDED*/
])
AH_VERBATIM([_REENTRANT],
[/* To allow the use of Libgcrypt in multithreaded programs we have to use
special features from the library. */
#ifndef _REENTRANT
# define _REENTRANT 1
#endif
])
AC_SUBST(LIBGCRYPT_LT_CURRENT)
AC_SUBST(LIBGCRYPT_LT_AGE)
AC_SUBST(LIBGCRYPT_LT_REVISION)
AC_SUBST(PACKAGE)
AC_SUBST(VERSION)
AC_DEFINE_UNQUOTED(PACKAGE, "$PACKAGE", [Name of this package])
AC_DEFINE_UNQUOTED(VERSION, "$VERSION", [Version of this package])
######################
## Basic checks. ### (we need some results later on (e.g. $GCC)
######################
AC_PROG_MAKE_SET
missing_dir=`cd $ac_aux_dir && pwd`
AM_MISSING_PROG(ACLOCAL, aclocal, $missing_dir)
AM_MISSING_PROG(AUTOCONF, autoconf, $missing_dir)
AM_MISSING_PROG(AUTOMAKE, automake, $missing_dir)
AM_MISSING_PROG(AUTOHEADER, autoheader, $missing_dir)
# AM_MISSING_PROG(MAKEINFO, makeinfo, $missing_dir)
AC_PROG_CC
AC_PROG_CPP
AM_PROG_CC_C_O
AM_PROG_AS
AC_ISC_POSIX
AC_PROG_INSTALL
AC_PROG_AWK
AC_LIBTOOL_WIN32_DLL
AC_LIBTOOL_RC
AM_PROG_LIBTOOL
##########################
## General definitions. ##
##########################
# Used by libgcrypt-config
LIBGCRYPT_CONFIG_LIBS="-lgcrypt"
LIBGCRYPT_CONFIG_CFLAGS=""
# Definitions for symmetric ciphers.
available_ciphers="arcfour blowfish cast5 des aes twofish serpent rfc2268 seed"
available_ciphers="$available_ciphers camellia"
enabled_ciphers=""
# Definitions for public-key ciphers.
available_pubkey_ciphers="dsa elgamal rsa ecc"
enabled_pubkey_ciphers=""
# Definitions for message digests.
available_digests="crc md4 md5 rmd160 sha1 sha256"
available_digests_64="sha512 tiger whirlpool"
enabled_digests=""
# Definitions for random modules.
available_random_modules="linux egd unix"
auto_random_modules="$available_random_modules"
# Supported thread backends.
LIBGCRYPT_THREAD_MODULES=""
# Other definitions.
print_egd_notice=no
have_w32_system=no
# Setup some stuff depending on host.
case "${host}" in
*-*-mingw32*)
available_random_modules="w32"
ac_cv_have_dev_random=no
have_w32_system=yes
AC_DEFINE(USE_ONLY_8DOT3,1,
[set this to limit filenames to the 8.3 format])
AC_DEFINE(HAVE_DRIVE_LETTERS,1,
[defined if we must run on a stupid file system])
AC_DEFINE(HAVE_DOSISH_SYSTEM,1,
[defined if we run on some of the PCDOS like systems
(DOS, Windoze. OS/2) with special properties like
no file modes])
;;
i?86-emx-os2 | i?86-*-os2*emx)
# OS/2 with the EMX environment
ac_cv_have_dev_random=no
AC_DEFINE(HAVE_DRIVE_LETTERS)
AC_DEFINE(HAVE_DOSISH_SYSTEM)
;;
i?86-*-msdosdjgpp*)
# DOS with the DJGPP environment
ac_cv_have_dev_random=no
AC_DEFINE(HAVE_DRIVE_LETTERS)
AC_DEFINE(HAVE_DOSISH_SYSTEM)
;;
*-*-freebsd*)
# FreeBSD
CPPFLAGS="$CPPFLAGS -I/usr/local/include"
LDFLAGS="$LDFLAGS -L/usr/local/lib"
;;
*-*-hpux*)
if test -z "$GCC" ; then
CFLAGS="$CFLAGS -Ae -D_HPUX_SOURCE"
fi
;;
*-dec-osf4*)
if test -z "$GCC" ; then
# Suppress all warnings
# to get rid of the unsigned/signed char mismatch warnings.
CFLAGS="$CFLAGS -w"
fi
;;
m68k-atari-mint)
;;
*)
;;
esac
if test "$have_w32_system" = yes; then
AC_DEFINE(HAVE_W32_SYSTEM,1, [Defined if we run on a W32 API based system])
fi
AM_CONDITIONAL(HAVE_W32_SYSTEM, test "$have_w32_system" = yes)
# A printable OS Name is sometimes useful.
case "${host}" in
*-*-mingw32*)
PRINTABLE_OS_NAME="MingW32"
;;
i?86-emx-os2 | i?86-*-os2*emx )
PRINTABLE_OS_NAME="OS/2"
;;
i?86-*-msdosdjgpp*)
PRINTABLE_OS_NAME="MSDOS/DJGPP"
;;
*-linux*)
PRINTABLE_OS_NAME="GNU/Linux"
;;
*)
PRINTABLE_OS_NAME=`uname -s || echo "Unknown"`
;;
esac
#
# Figure out the name of the random device
#
case "${host}" in
*-openbsd*)
NAME_OF_DEV_RANDOM="/dev/srandom"
NAME_OF_DEV_URANDOM="/dev/urandom"
;;
*)
NAME_OF_DEV_RANDOM="/dev/random"
NAME_OF_DEV_URANDOM="/dev/urandom"
;;
esac
AC_ARG_ENABLE(endian-check,
AC_HELP_STRING([--disable-endian-check],
[disable the endian check and trust the OS provided macros]),
endiancheck=$enableval,endiancheck=yes)
if test x"$endiancheck" = xyes ; then
AC_C_BIGENDIAN
else
AC_DEFINE(DISABLED_ENDIAN_CHECK,1,[configure did not test for endianess])
fi
AC_CHECK_SIZEOF(unsigned short, 2)
AC_CHECK_SIZEOF(unsigned int, 4)
AC_CHECK_SIZEOF(unsigned long, 4)
AC_CHECK_SIZEOF(unsigned long long, 0)
AC_TYPE_UINTPTR_T
if test "$ac_cv_sizeof_unsigned_short" = "0" \
|| test "$ac_cv_sizeof_unsigned_int" = "0" \
|| test "$ac_cv_sizeof_unsigned_long" = "0"; then
AC_MSG_WARN([Hmmm, something is wrong with the sizes - using defaults]);
fi
# Do we have any 64-bit data types?
if test "$ac_cv_sizeof_unsigned_int" != "8" \
&& test "$ac_cv_sizeof_unsigned_long" != "8" \
&& test "$ac_cv_sizeof_unsigned_long_long" != "8" \
&& test "$ac_cv_sizeof_uint64_t" != "8"; then
AC_MSG_WARN([No 64-bit types. Disabling TIGER/192, SHA-384, and SHA-512])
else
available_digests="$available_digests $available_digests_64"
fi
# If not specified otherwise, all available algorithms will be
# included.
default_ciphers="$available_ciphers"
default_pubkey_ciphers="$available_pubkey_ciphers"
default_digests="$available_digests"
############################
## Command line switches. ##
############################
# Implementation of the --enable-ciphers switch.
AC_ARG_ENABLE(ciphers,
AC_HELP_STRING([--enable-ciphers=ciphers],
[select the symmetric ciphers to include]),
[enabled_ciphers=`echo $enableval | tr ',:' ' ' | tr '[A-Z]' '[a-z]'`],
[enabled_ciphers=""])
if test "x$enabled_ciphers" = "x" \
-o "$enabled_ciphers" = "yes" \
-o "$enabled_ciphers" = "no"; then
enabled_ciphers=$default_ciphers
fi
AC_MSG_CHECKING([which symmetric ciphers to include])
for cipher in $enabled_ciphers; do
LIST_MEMBER($cipher, $available_ciphers)
if test "$found" = "0"; then
AC_MSG_ERROR([unsupported cipher "$cipher" specified])
fi
done
AC_MSG_RESULT([$enabled_ciphers])
# Implementation of the --enable-pubkey-ciphers switch.
AC_ARG_ENABLE(pubkey-ciphers,
AC_HELP_STRING([--enable-pubkey-ciphers=ciphers],
[select the public-key ciphers to include]),
[enabled_pubkey_ciphers=`echo $enableval | tr ',:' ' ' | tr '[A-Z]' '[a-z]'`],
[enabled_pubkey_ciphers=""])
if test "x$enabled_pubkey_ciphers" = "x" \
-o "$enabled_pubkey_ciphers" = "yes" \
-o "$enabled_pubkey_ciphers" = "no"; then
enabled_pubkey_ciphers=$default_pubkey_ciphers
fi
AC_MSG_CHECKING([which public-key ciphers to include])
for cipher in $enabled_pubkey_ciphers; do
LIST_MEMBER($cipher, $available_pubkey_ciphers)
if test "$found" = "0"; then
AC_MSG_ERROR([unsupported public-key cipher specified])
fi
done
AC_MSG_RESULT([$enabled_pubkey_ciphers])
# Implementation of the --enable-digests switch.
AC_ARG_ENABLE(digests,
AC_HELP_STRING([--enable-digests=digests],
[select the message digests to include]),
[enabled_digests=`echo $enableval | tr ',:' ' ' | tr '[A-Z]' '[a-z]'`],
[enabled_digests=""])
if test "x$enabled_digests" = "x" \
-o "$enabled_digests" = "yes" \
-o "$enabled_digests" = "no"; then
enabled_digests=$default_digests
fi
AC_MSG_CHECKING([which message digests to include])
for digest in $enabled_digests; do
LIST_MEMBER($digest, $available_digests)
if test "$found" = "0"; then
AC_MSG_ERROR([unsupported message digest specified])
fi
done
AC_MSG_RESULT([$enabled_digests])
# Implementation of the --enable-random switch.
AC_ARG_ENABLE(random,
AC_HELP_STRING([--enable-random=name],
[select which random number generator to use]),
[random=`echo $enableval | tr '[A-Z]' '[a-z]'`],
[])
if test "x$random" = "x" -o "$random" = "yes" -o "$random" = "no"; then
random=default
fi
AC_MSG_CHECKING([which random module to use])
if test "$random" != "default" -a "$random" != "auto"; then
LIST_MEMBER($random, $available_random_modules)
if test "$found" = "0"; then
AC_MSG_ERROR([unsupported random module specified])
fi
fi
AC_MSG_RESULT($random)
# Implementation of the --disable-dev-random switch.
AC_MSG_CHECKING([whether use of /dev/random is requested])
AC_ARG_ENABLE(dev-random,
[ --disable-dev-random disable the use of dev random],
try_dev_random=$enableval, try_dev_random=yes)
AC_MSG_RESULT($try_dev_random)
# Implementation of the --with-egd-socket switch.
AC_ARG_WITH(egd-socket,
[ --with-egd-socket=NAME Use NAME for the EGD socket)],
egd_socket_name="$withval", egd_socket_name="" )
AC_DEFINE_UNQUOTED(EGD_SOCKET_NAME, "$egd_socket_name",
[Define if you don't want the default EGD socket name.
For details see cipher/rndegd.c])
# Implementation of the --enable-random-daemon
AC_MSG_CHECKING([whether the experimental random daemon is requested])
AC_ARG_ENABLE([random-daemon],
AC_HELP_STRING([--enable-random-daemon],
[Build and support the experimental gcryptrnd]),
[use_random_daemon=$enableval],
[use_random_daemon=no])
AC_MSG_RESULT($use_random_daemon)
if test x$use_random_daemon = xyes ; then
AC_DEFINE(USE_RANDOM_DAEMON,1,
[Define to support the experimental random daemon])
fi
AM_CONDITIONAL(USE_RANDOM_DAEMON, test x$use_random_daemon = xyes)
# Implementation of --disable-asm.
AC_MSG_CHECKING([whether MPI assembler modules are requested])
AC_ARG_ENABLE([asm],
AC_HELP_STRING([--disable-asm],
[Disable MPI assembler modules]),
[try_asm_modules=$enableval],
[try_asm_modules=yes])
AC_MSG_RESULT($try_asm_modules)
# Implementation of the --enable-m-guard switch.
AC_MSG_CHECKING([whether memory guard is requested])
AC_ARG_ENABLE(m-guard,
AC_HELP_STRING([--enable-m-guard],
[Enable memory guard facility]),
[use_m_guard=$enableval], [use_m_guard=no])
AC_MSG_RESULT($use_m_guard)
if test "$use_m_guard" = yes ; then
AC_DEFINE(M_GUARD,1,[Define to use the (obsolete) malloc guarding feature])
fi
# Implementation of the --with-capabilities switch.
# Check whether we want to use Linux capabilities
AC_MSG_CHECKING([whether use of capabilities is requested])
AC_ARG_WITH(capabilities,
AC_HELP_STRING([--with-capabilities],
[Use linux capabilities [default=no]]),
[use_capabilities="$withval"],[use_capabilities=no])
AC_MSG_RESULT($use_capabilities)
# Implementation of the --enable-hmac-binary-check.
AC_MSG_CHECKING([whether a HMAC binary check is requested])
AC_ARG_ENABLE(hmac-binary-check,
AC_HELP_STRING([--enable-hmac-binary-check],
[Enable library integrity check]),
[use_hmac_binary_check=$enableval],
[use_hmac_binary_check=no])
AC_MSG_RESULT($use_hmac_binary_check)
if test "$use_hmac_binary_check" = yes ; then
AC_DEFINE(ENABLE_HMAC_BINARY_CHECK,1,
[Define to support an HMAC based integrity check])
fi
# Implementation of the --disable-padlock-support switch.
AC_MSG_CHECKING([whether padlock support is requested])
AC_ARG_ENABLE(padlock-support,
AC_HELP_STRING([--disable-padlock-support],
[Disable support for the PadLock Engine of VIA processors]),
padlocksupport=$enableval,padlocksupport=yes)
AC_MSG_RESULT($padlocksupport)
if test x"$padlocksupport" = xyes ; then
AC_DEFINE(ENABLE_PADLOCK_SUPPORT, 1,
[Enable support for the PadLock engine.])
fi
AC_DEFINE_UNQUOTED(PRINTABLE_OS_NAME, "$PRINTABLE_OS_NAME",
[A human readable text with the name of the OS])
# For some systems we know that we have ld_version scripts.
# Use it then as default.
have_ld_version_script=no
case "${host}" in
*-*-linux*)
have_ld_version_script=yes
;;
*-*-gnu*)
have_ld_version_script=yes
;;
esac
AC_ARG_ENABLE([ld-version-script],
AC_HELP_STRING([--enable-ld-version-script],
[enable/disable use of linker version script.
(default is system dependent)]),
[have_ld_version_script=$enableval],
[ : ] )
AM_CONDITIONAL(HAVE_LD_VERSION_SCRIPT, test "$have_ld_version_script" = "yes")
AC_DEFINE_UNQUOTED(NAME_OF_DEV_RANDOM, "$NAME_OF_DEV_RANDOM",
[defined to the name of the strong random device])
AC_DEFINE_UNQUOTED(NAME_OF_DEV_URANDOM, "$NAME_OF_DEV_URANDOM",
[defined to the name of the weaker random device])
###############################
#### Checks for libraries. ####
###############################
#
# gpg-error is required.
#
AM_PATH_GPG_ERROR("$NEED_GPG_ERROR_VERSION")
if test "x$GPG_ERROR_LIBS" = "x"; then
AC_MSG_ERROR([libgpg-error is needed.
See ftp://ftp.gnupg.org/gcrypt/libgpg-error/ .])
fi
AC_DEFINE(GPG_ERR_SOURCE_DEFAULT, GPG_ERR_SOURCE_GCRYPT,
[The default error source for libgcrypt.])
#
# Check whether the GNU Pth library is available. We require this
# to build the optional gcryptrnd program.
#
AC_ARG_WITH(pth-prefix,
AC_HELP_STRING([--with-pth-prefix=PFX],
[prefix where GNU Pth is installed (optional)]),
pth_config_prefix="$withval", pth_config_prefix="")
if test x$pth_config_prefix != x ; then
PTH_CONFIG="$pth_config_prefix/bin/pth-config"
fi
if test "$use_random_daemon" = "yes"; then
AC_PATH_PROG(PTH_CONFIG, pth-config, no)
if test "$PTH_CONFIG" = "no"; then
AC_MSG_WARN([[
***
*** To build the Libgcrypt's random number daemon
*** we need the support of the GNU Portable Threads Library.
*** Download it from ftp://ftp.gnu.org/gnu/pth/
*** On a Debian GNU/Linux system you might want to try
*** apt-get install libpth-dev
***]])
else
GNUPG_PTH_VERSION_CHECK([1.3.7])
if test $have_pth = yes; then
PTH_CFLAGS=`$PTH_CONFIG --cflags`
PTH_LIBS=`$PTH_CONFIG --ldflags`
PTH_LIBS="$PTH_LIBS `$PTH_CONFIG --libs --all`"
AC_DEFINE(USE_GNU_PTH, 1,
[Defined if the GNU Portable Thread Library should be used])
AC_DEFINE(HAVE_PTH, 1,
[Defined if the GNU Pth is available])
fi
fi
fi
AC_SUBST(PTH_CFLAGS)
AC_SUBST(PTH_LIBS)
# Solaris needs -lsocket and -lnsl. Unisys system includes
# gethostbyname in libsocket but needs libnsl for socket.
AC_SEARCH_LIBS(setsockopt, [socket], ,
[AC_SEARCH_LIBS(setsockopt, [socket], , , [-lnsl])])
AC_SEARCH_LIBS(setsockopt, [nsl])
##################################
#### Checks for header files. ####
##################################
AC_HEADER_STDC
AC_CHECK_HEADERS(unistd.h sys/select.h)
##########################################
#### Checks for typedefs, structures, ####
#### and compiler characteristics. ####
##########################################
AC_C_CONST
AC_C_INLINE
AC_TYPE_SIZE_T
AC_TYPE_SIGNAL
AC_DECL_SYS_SIGLIST
GNUPG_CHECK_TYPEDEF(byte, HAVE_BYTE_TYPEDEF)
GNUPG_CHECK_TYPEDEF(ushort, HAVE_USHORT_TYPEDEF)
GNUPG_CHECK_TYPEDEF(ulong, HAVE_ULONG_TYPEDEF)
GNUPG_CHECK_TYPEDEF(u16, HAVE_U16_TYPEDEF)
GNUPG_CHECK_TYPEDEF(u32, HAVE_U32_TYPEDEF)
gl_TYPE_SOCKLEN_T
case "${host}" in
*-*-mingw32*)
# socklen_t may or may not be defined depending on what headers
# are included. To be safe we use int as this is the actual type.
FALLBACK_SOCKLEN_T="typedef int gcry_socklen_t;"
;;
*)
if test ".$gl_cv_socklen_t_equiv" = "."; then
FALLBACK_SOCKLEN_T="typedef socklen_t gcry_socklen_t;"
else
FALLBACK_SOCKLEN_T="typedef ${gl_cv_socklen_t_equiv} gcry_socklen_t;"
fi
esac
AC_SUBST(FALLBACK_SOCKLEN_T)
#
# Check for ELF visibility support.
#
AC_CACHE_CHECK(whether the visibility attribute is supported,
gcry_cv_visibility_attribute,
[gcry_cv_visibility_attribute=no
AC_LANG_CONFTEST([AC_LANG_SOURCE(
[[int foo __attribute__ ((visibility ("hidden"))) = 1;
int bar __attribute__ ((visibility ("protected"))) = 1;
]])])
if ${CC-cc} -Werror -S conftest.c -o conftest.s \
1>&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD ; then
if grep '\.hidden.*foo' conftest.s >/dev/null 2>&1 ; then
if grep '\.protected.*bar' conftest.s >/dev/null 2>&1; then
gcry_cv_visibility_attribute=yes
fi
fi
fi
])
if test "$gcry_cv_visibility_attribute" = "yes"; then
AC_CACHE_CHECK(for broken visibility attribute,
gcry_cv_broken_visibility_attribute,
[gcry_cv_broken_visibility_attribute=yes
AC_LANG_CONFTEST([AC_LANG_SOURCE(
[[int foo (int x);
int bar (int x) __asm__ ("foo")
__attribute__ ((visibility ("hidden")));
int bar (int x) { return x; }
]])])
if ${CC-cc} -Werror -S conftest.c -o conftest.s \
1>&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD ; then
if grep '\.hidden@<:@ _@:>@foo' conftest.s >/dev/null 2>&1;
then
gcry_cv_broken_visibility_attribute=no
fi
fi
])
fi
if test "$gcry_cv_visibility_attribute" = "yes"; then
AC_CACHE_CHECK(for broken alias attribute,
gcry_cv_broken_alias_attribute,
[gcry_cv_broken_alias_attribute=yes
AC_LANG_CONFTEST([AC_LANG_SOURCE(
[[extern int foo (int x) __asm ("xyzzy");
int bar (int x) { return x; }
extern __typeof (bar) foo __attribute ((weak, alias ("bar")));
extern int dfoo;
extern __typeof (dfoo) dfoo __asm ("abccb");
int dfoo = 1;
]])])
if ${CC-cc} -Werror -S conftest.c -o conftest.s \
1>&AS_MESSAGE_LOG_FD 2>&AS_MESSAGE_LOG_FD ; then
if grep 'xyzzy' conftest.s >/dev/null 2>&1 && \
grep 'abccb' conftest.s >/dev/null 2>&1; then
gcry_cv_broken_alias_attribute=no
fi
fi
])
fi
if test "$gcry_cv_visibility_attribute" = "yes"; then
AC_CACHE_CHECK(if gcc supports -fvisibility=hidden,
gcry_cv_gcc_has_f_visibility,
[gcry_cv_gcc_has_f_visibility=no
_gcc_cflags_save=$CFLAGS
CFLAGS="-fvisibility=hidden"
AC_COMPILE_IFELSE(AC_LANG_PROGRAM([]),
gcry_cv_gcc_has_f_visibility=yes)
CFLAGS=$_gcc_cflags_save;
])
fi
if test "$gcry_cv_visibility_attribute" = "yes" \
&& test "$gcry_cv_broken_visibility_attribute" != "yes" \
&& test "$gcry_cv_broken_alias_attribute" != "yes" \
&& test "$gcry_cv_gcc_has_f_visibility" = "yes"
then
AC_DEFINE(GCRY_USE_VISIBILITY, 1,
[Define to use the GNU C visibility attribute.])
CFLAGS="$CFLAGS -fvisibility=hidden"
fi
#######################################
#### Checks for library functions. ####
#######################################
AC_FUNC_VPRINTF
# We have replacements for these in src/missing-string.c
AC_CHECK_FUNCS(stpcpy strcasecmp)
# We have replacements for these in src/g10lib.h
AC_CHECK_FUNCS(strtoul memmove stricmp atexit raise)
# Other checks
AC_CHECK_FUNCS(strerror rand mmap getpagesize sysconf waitpid wait4)
AC_CHECK_FUNCS(gettimeofday getrusage gethrtime clock_gettime syslog)
AC_CHECK_FUNCS(fcntl ftruncate)
GNUPG_CHECK_MLOCK
#
# Check wether it is necessary to link against libdl.
#
DL_LIBS=""
if test "$use_hmac_binary_check" = yes ; then
_gcry_save_libs="$LIBS"
LIBS=""
AC_SEARCH_LIBS(dlopen, c dl,,,)
DL_LIBS=$LIBS
LIBS="$_gcry_save_libs"
LIBGCRYPT_CONFIG_LIBS="${LIBGCRYPT_CONFIG_LIBS} ${DL_LIBS}"
fi
AC_SUBST(DL_LIBS)
#
# Check whether we can use Linux capabilities as requested.
#
if test "$use_capabilities" = "yes" ; then
use_capabilities=no
AC_CHECK_HEADERS(sys/capability.h)
if test "$ac_cv_header_sys_capability_h" = "yes" ; then
AC_CHECK_LIB(cap, cap_init, ac_need_libcap=1)
if test "$ac_cv_lib_cap_cap_init" = "yes"; then
AC_DEFINE(USE_CAPABILITIES,1,
[define if capabilities should be used])
LIBS="$LIBS -lcap"
use_capabilities=yes
fi
fi
if test "$use_capabilities" = "no" ; then
AC_MSG_WARN([[
***
*** The use of capabilities on this system is not possible.
*** You need a recent Linux kernel and some patches:
*** fcaps-2.2.9-990610.patch (kernel patch for 2.2.9)
*** fcap-module-990613.tar.gz (kernel module)
*** libcap-1.92.tar.gz (user mode library and utilities)
*** And you have to configure the kernel with CONFIG_VFS_CAP_PLUGIN
*** set (filesystems menu). Be warned: This code is *really* ALPHA.
***]])
fi
fi
# Check whether a random device is available.
if test "$try_dev_random" = yes ; then
AC_CACHE_CHECK(for random device, ac_cv_have_dev_random,
[if test -r "$NAME_OF_DEV_RANDOM" && test -r "$NAME_OF_DEV_URANDOM" ; then
ac_cv_have_dev_random=yes; else ac_cv_have_dev_random=no; fi])
if test "$ac_cv_have_dev_random" = yes; then
AC_DEFINE(HAVE_DEV_RANDOM,1,
[defined if the system supports a random device] )
fi
else
AC_MSG_CHECKING(for random device)
ac_cv_have_dev_random=no
AC_MSG_RESULT(has been disabled)
fi
# Figure out the random modules for this configuration.
if test "$random" = "default"; then
# Select default value.
if test "$ac_cv_have_dev_random" = yes; then
# Try Linuxish random device.
random_modules="linux"
else
case "${host}" in
*-*-mingw32*|*-*-cygwin*)
# Windows random device.
random_modules="w32"
;;
*)
# Build everything, allow to select at runtime.
random_modules="$auto_random_modules"
;;
esac
fi
else
if test "$random" = "auto"; then
# Build everything, allow to select at runtime.
random_modules="$auto_random_modules"
else
random_modules="$random"
fi
fi
#
# Setup assembler stuff.
#
GNUPG_SYS_SYMBOL_UNDERSCORE()
AC_ARG_ENABLE(mpi-path,
AC_HELP_STRING([--enable-mpi-path=EXTRA_PATH],
[prepend EXTRA_PATH to list of CPU specific optimizations]),
mpi_extra_path="$enableval",mpi_extra_path="")
AC_MSG_CHECKING(for mpi assembler functions)
if test -f $srcdir/mpi/config.links ; then
. $srcdir/mpi/config.links
AC_CONFIG_LINKS("$mpi_ln_list")
ac_cv_mpi_sflags="$mpi_sflags"
AC_MSG_RESULT(done)
else
AC_MSG_RESULT(failed)
AC_MSG_ERROR([mpi/config.links missing!])
fi
MPI_SFLAGS="$ac_cv_mpi_sflags"
AC_SUBST(MPI_SFLAGS)
AM_CONDITIONAL(MPI_MOD_ASM_MPIH_ADD1, test "$mpi_mod_asm_mpih_add1" = yes)
AM_CONDITIONAL(MPI_MOD_ASM_MPIH_SUB1, test "$mpi_mod_asm_mpih_sub1" = yes)
AM_CONDITIONAL(MPI_MOD_ASM_MPIH_MUL1, test "$mpi_mod_asm_mpih_mul1" = yes)
AM_CONDITIONAL(MPI_MOD_ASM_MPIH_MUL2, test "$mpi_mod_asm_mpih_mul2" = yes)
AM_CONDITIONAL(MPI_MOD_ASM_MPIH_MUL3, test "$mpi_mod_asm_mpih_mul3" = yes)
AM_CONDITIONAL(MPI_MOD_ASM_MPIH_LSHIFT, test "$mpi_mod_asm_mpih_lshift" = yes)
AM_CONDITIONAL(MPI_MOD_ASM_MPIH_RSHIFT, test "$mpi_mod_asm_mpih_rshift" = yes)
AM_CONDITIONAL(MPI_MOD_ASM_UDIV, test "$mpi_mod_asm_udiv" = yes)
AM_CONDITIONAL(MPI_MOD_ASM_UDIV_QRNND, test "$mpi_mod_asm_udiv_qrnnd" = yes)
AM_CONDITIONAL(MPI_MOD_C_MPIH_ADD1, test "$mpi_mod_c_mpih_add1" = yes)
AM_CONDITIONAL(MPI_MOD_C_MPIH_SUB1, test "$mpi_mod_c_mpih_sub1" = yes)
AM_CONDITIONAL(MPI_MOD_C_MPIH_MUL1, test "$mpi_mod_c_mpih_mul1" = yes)
AM_CONDITIONAL(MPI_MOD_C_MPIH_MUL2, test "$mpi_mod_c_mpih_mul2" = yes)
AM_CONDITIONAL(MPI_MOD_C_MPIH_MUL3, test "$mpi_mod_c_mpih_mul3" = yes)
AM_CONDITIONAL(MPI_MOD_C_MPIH_LSHIFT, test "$mpi_mod_c_mpih_lshift" = yes)
AM_CONDITIONAL(MPI_MOD_C_MPIH_RSHIFT, test "$mpi_mod_c_mpih_rshift" = yes)
AM_CONDITIONAL(MPI_MOD_C_UDIV, test "$mpi_mod_c_udiv" = yes)
AM_CONDITIONAL(MPI_MOD_C_UDIV_QRNND, test "$mpi_mod_c_udiv_qrnnd" = yes)
if test "$is_development_version" = "yes"; then
AC_DEFINE(IS_DEVELOPMENT_VERSION,1,
[Defined if this is not a regular release])
fi
AM_CONDITIONAL(CROSS_COMPILING, test x$cross_compiling = xyes)
# This is handy for debugging so the compiler doesn't rearrange
# things and eliminate variables.
AC_ARG_ENABLE(optimization,
AC_HELP_STRING([--disable-optimization],
[disable compiler optimization]),
[if test $enableval = no ; then
CFLAGS=`echo $CFLAGS | sed 's/-O[[0-9]]//'`
fi])
AC_ARG_ENABLE(gcc-warnings,
AC_HELP_STRING([--enable-gcc-warnings],
[enable more verbose gcc warnings]),
[more_gcc_warnings="$enableval"],
[more_gcc_warnings="no"])
if test "$GCC" = yes; then
if test "$USE_MAINTAINER_MODE" = "yes" ||
test "$more_gcc_warnings" = "yes"; then
CFLAGS="$CFLAGS -Wall -Wcast-align -Wshadow -Wstrict-prototypes"
if test "$more_gcc_warnings" = "yes"; then
CFLAGS="$CFLAGS -W -Wextra -Wbad-function-cast"
CFLAGS="$CFLAGS -Wwrite-strings"
CFLAGS="$CFLAGS -Wdeclaration-after-statement"
CFLAGS="$CFLAGS -Wno-missing-field-initializers"
CFLAGS="$CFLAGS -Wno-sign-compare"
# Note: We don't use -Wunreachable-code because this gives
# warnings for all asserts and many inline functions like
# gpg_error (gcc 4.1.2 20060928).
fi
else
CFLAGS="$CFLAGS -Wall"
fi
AC_MSG_CHECKING([if gcc supports -Wpointer-arith])
_gcc_cflags_save=$CFLAGS
CFLAGS="-Wpointer-arith"
AC_COMPILE_IFELSE(AC_LANG_PROGRAM([]),_gcc_wopt=yes,_gcc_wopt=no)
AC_MSG_RESULT($_gcc_wopt)
CFLAGS=$_gcc_cflags_save;
if test x"$_gcc_wopt" = xyes ; then
CFLAGS="$CFLAGS -Wpointer-arith"
fi
fi
# Check whether as(1) supports a noeexecstack feature. This test
# includes an override option.
CL_AS_NOEXECSTACK
AC_SUBST(LIBGCRYPT_CONFIG_API_VERSION)
AC_SUBST(LIBGCRYPT_CONFIG_LIBS)
AC_SUBST(LIBGCRYPT_CONFIG_CFLAGS)
AC_SUBST(LIBGCRYPT_THREAD_MODULES)
AC_CONFIG_COMMANDS([gcrypt-conf],[[
chmod +x src/libgcrypt-config
]],[[
prefix=$prefix
exec_prefix=$exec_prefix
libdir=$libdir
datadir=$datadir
DATADIRNAME=$DATADIRNAME
]])
#####################
#### Conclusion. ####
#####################
# Define conditional sources and config.h symbols depending on the
# selected ciphers, pubkey-ciphers, digests and random modules.
LIST_MEMBER(arcfour, $enabled_ciphers)
if test "$found" = "1"; then
GCRYPT_CIPHERS="$GCRYPT_CIPHERS arcfour.lo"
AC_DEFINE(USE_ARCFOUR, 1, [Defined if this module should be included])
fi
LIST_MEMBER(blowfish, $enabled_ciphers)
if test "$found" = "1" ; then
GCRYPT_CIPHERS="$GCRYPT_CIPHERS blowfish.lo"
AC_DEFINE(USE_BLOWFISH, 1, [Defined if this module should be included])
fi
LIST_MEMBER(cast5, $enabled_ciphers)
if test "$found" = "1" ; then
GCRYPT_CIPHERS="$GCRYPT_CIPHERS cast5.lo"
AC_DEFINE(USE_CAST5, 1, [Defined if this module should be included])
fi
LIST_MEMBER(des, $enabled_ciphers)
if test "$found" = "1" ; then
GCRYPT_CIPHERS="$GCRYPT_CIPHERS des.lo"
AC_DEFINE(USE_DES, 1, [Defined if this module should be included])
fi
LIST_MEMBER(aes, $enabled_ciphers)
if test "$found" = "1" ; then
GCRYPT_CIPHERS="$GCRYPT_CIPHERS rijndael.lo"
AC_DEFINE(USE_AES, 1, [Defined if this module should be included])
fi
LIST_MEMBER(twofish, $enabled_ciphers)
if test "$found" = "1" ; then
GCRYPT_CIPHERS="$GCRYPT_CIPHERS twofish.lo"
AC_DEFINE(USE_TWOFISH, 1, [Defined if this module should be included])
fi
LIST_MEMBER(serpent, $enabled_ciphers)
if test "$found" = "1" ; then
GCRYPT_CIPHERS="$GCRYPT_CIPHERS serpent.lo"
AC_DEFINE(USE_SERPENT, 1, [Defined if this module should be included])
fi
LIST_MEMBER(rfc2268, $enabled_ciphers)
if test "$found" = "1" ; then
GCRYPT_CIPHERS="$GCRYPT_CIPHERS rfc2268.lo"
AC_DEFINE(USE_RFC2268, 1, [Defined if this module should be included])
fi
LIST_MEMBER(seed, $enabled_ciphers)
if test "$found" = "1" ; then
GCRYPT_CIPHERS="$GCRYPT_CIPHERS seed.lo"
AC_DEFINE(USE_SEED, 1, [Defined if this module should be included])
fi
LIST_MEMBER(camellia, $enabled_ciphers)
if test "$found" = "1" ; then
GCRYPT_CIPHERS="$GCRYPT_CIPHERS camellia.lo camellia-glue.lo"
AC_DEFINE(USE_CAMELLIA, 1, [Defined if this module should be included])
fi
LIST_MEMBER(dsa, $enabled_pubkey_ciphers)
if test "$found" = "1" ; then
GCRYPT_PUBKEY_CIPHERS="$GCRYPT_PUBKEY_CIPHERS dsa.lo"
AC_DEFINE(USE_DSA, 1, [Defined if this module should be included])
fi
LIST_MEMBER(rsa, $enabled_pubkey_ciphers)
if test "$found" = "1" ; then
GCRYPT_PUBKEY_CIPHERS="$GCRYPT_PUBKEY_CIPHERS rsa.lo"
AC_DEFINE(USE_RSA, 1, [Defined if this module should be included])
fi
LIST_MEMBER(elgamal, $enabled_pubkey_ciphers)
if test "$found" = "1" ; then
GCRYPT_PUBKEY_CIPHERS="$GCRYPT_PUBKEY_CIPHERS elgamal.lo"
AC_DEFINE(USE_ELGAMAL, 1, [Defined if this module should be included])
fi
LIST_MEMBER(ecc, $enabled_pubkey_ciphers)
if test "$found" = "1" ; then
GCRYPT_PUBKEY_CIPHERS="$GCRYPT_PUBKEY_CIPHERS ecc.lo"
AC_DEFINE(USE_ECC, 1, [Defined if this module should be included])
fi
LIST_MEMBER(crc, $enabled_digests)
if test "$found" = "1" ; then
GCRYPT_DIGESTS="$GCRYPT_DIGESTS crc.lo"
AC_DEFINE(USE_CRC, 1, [Defined if this module should be included])
fi
LIST_MEMBER(md4, $enabled_digests)
if test "$found" = "1" ; then
GCRYPT_DIGESTS="$GCRYPT_DIGESTS md4.lo"
AC_DEFINE(USE_MD4, 1, [Defined if this module should be included])
fi
LIST_MEMBER(md5, $enabled_digests)
if test "$found" = "1" ; then
GCRYPT_DIGESTS="$GCRYPT_DIGESTS md5.lo"
AC_DEFINE(USE_MD5, 1, [Defined if this module should be included])
fi
LIST_MEMBER(sha256, $enabled_digests)
if test "$found" = "1" ; then
GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha256.lo"
AC_DEFINE(USE_SHA256, 1, [Defined if this module should be included])
fi
LIST_MEMBER(sha512, $enabled_digests)
if test "$found" = "1" ; then
GCRYPT_DIGESTS="$GCRYPT_DIGESTS sha512.lo"
AC_DEFINE(USE_SHA512, 1, [Defined if this module should be included])
fi
LIST_MEMBER(tiger, $enabled_digests)
if test "$found" = "1" ; then
GCRYPT_DIGESTS="$GCRYPT_DIGESTS tiger.lo"
AC_DEFINE(USE_TIGER, 1, [Defined if this module should be included])
fi
LIST_MEMBER(whirlpool, $enabled_digests)
if test "$found" = "1" ; then
GCRYPT_DIGESTS="$GCRYPT_DIGESTS whirlpool.lo"
AC_DEFINE(USE_WHIRLPOOL, 1, [Defined if this module should be included])
fi
# rmd160 and sha1 should be included always.
GCRYPT_DIGESTS="$GCRYPT_DIGESTS rmd160.lo sha1.lo"
AC_DEFINE(USE_RMD160, 1, [Defined if this module should be included])
AC_DEFINE(USE_SHA1, 1, [Defined if this module should be included])
LIST_MEMBER(linux, $random_modules)
if test "$found" = "1" ; then
GCRYPT_RANDOM="$GCRYPT_RANDOM rndlinux.lo"
AC_DEFINE(USE_RNDLINUX, 1, [Defined if the /dev/random RNG should be used.])
fi
LIST_MEMBER(unix, $random_modules)
if test "$found" = "1" ; then
GCRYPT_RANDOM="$GCRYPT_RANDOM rndunix.lo"
AC_DEFINE(USE_RNDUNIX, 1, [Defined if the default Unix RNG should be used.])
print_egd_notice=yes
fi
LIST_MEMBER(egd, $random_modules)
if test "$found" = "1" ; then
GCRYPT_RANDOM="$GCRYPT_RANDOM rndegd.lo"
AC_DEFINE(USE_RNDEGD, 1, [Defined if the EGD based RNG should be used.])
fi
LIST_MEMBER(w32, $random_modules)
if test "$found" = "1" ; then
GCRYPT_RANDOM="$GCRYPT_RANDOM rndw32.lo"
AC_DEFINE(USE_RNDW32, 1,
[Defined if the Windows specific RNG should be used.])
fi
AC_SUBST([GCRYPT_CIPHERS])
AC_SUBST([GCRYPT_PUBKEY_CIPHERS])
AC_SUBST([GCRYPT_DIGESTS])
AC_SUBST([GCRYPT_RANDOM])
AC_SUBST(LIBGCRYPT_CIPHERS, $enabled_ciphers)
AC_SUBST(LIBGCRYPT_PUBKEY_CIPHERS, $enabled_pubkey_ciphers)
AC_SUBST(LIBGCRYPT_DIGESTS, $enabled_digests)
# For printing the configuration we need a colon separated list of
# algorithm names.
tmp=`echo "$enabled_ciphers" | tr ' ' : `
AC_DEFINE_UNQUOTED(LIBGCRYPT_CIPHERS, "$tmp",
[List of available cipher algorithms])
tmp=`echo "$enabled_pubkey_ciphers" | tr ' ' : `
AC_DEFINE_UNQUOTED(LIBGCRYPT_PUBKEY_CIPHERS, "$tmp",
[List of available public key cipher algorithms])
tmp=`echo "$enabled_digests" | tr ' ' : `
AC_DEFINE_UNQUOTED(LIBGCRYPT_DIGESTS, "$tmp",
[List of available digest algorithms])
# Generate extended version information for W32.
if test "$have_w32_system" = yes; then
BUILD_TIMESTAMP=`date --iso-8601=minutes`
changequote(,)dnl
BUILD_FILEVERSION=`echo "$VERSION" | sed 's/\([0-9.]*\).*/\1./;s/\./,/g'`
changequote([,])dnl
BUILD_FILEVERSION="${BUILD_FILEVERSION}${BUILD_REVISION}"
fi
AC_SUBST(BUILD_REVISION)
AC_SUBST(BUILD_TIMESTAMP)
AC_SUBST(BUILD_FILEVERSION)
AC_DEFINE_UNQUOTED(BUILD_REVISION, "$BUILD_REVISION",
[Subversion revision used to build this package])
# And create the files.
AC_CONFIG_FILES([
Makefile
m4/Makefile
mpi/Makefile
cipher/Makefile
random/Makefile
doc/Makefile
src/Makefile
src/gcrypt.h
src/libgcrypt-config
src/versioninfo.rc
tests/Makefile
])
AC_OUTPUT
# Give some feedback
echo "
Libgcrypt v${VERSION} has been configured as follows:
Platform: $PRINTABLE_OS_NAME ($host)
"
if test "$print_egd_notice" = "yes"; then
cat <<G10EOF
The performance of the Unix random gatherer module (rndunix) is not
very good and it does not keep the entropy pool over multiple
invocations of Libgcrypt base applications. The suggested way to
overcome this problem is to use the
Entropy Gathering Daemon (EGD)
which provides a entropy source for the whole system. It is written
in Perl and available at the GnuPG FTP servers. To enable EGD you
should rerun configure with the option "--enable-static-rnd=egd".
For more information consult the GnuPG webpages:
http://www.gnupg.org/download.html#egd
G10EOF
fi
if test -n "$gpl"; then
echo "Please note that you are building a version of Libgcrypt with"
echo " $gpl"
echo "included. These parts are licensed under the GPL and thus the"
echo "use of this library has to comply with the conditions of the GPL."
fi
diff --git a/doc/ChangeLog b/doc/ChangeLog
index 903081ff..b619baa6 100644
--- a/doc/ChangeLog
+++ b/doc/ChangeLog
@@ -1,424 +1,429 @@
+2008-09-18 Werner Koch <wk@g10code.com>
+
+ * gcrypt.texi (FIPS Mode): Add state transition Error to Error.
+ * fips-fsm.fig: Ditto.
+
2008-09-18 Werner Koch <wk@g10code.com>
* gcrypt.texi: Add a couple of index items.
(FIPS Mode): Reflect recent changes.
(Controlling the library): Describe gcry_fips_mode_active.
2008-09-16 Werner Koch <wk@g10code.com>
* gcrypt.texi (FIPS Mode): Describe new transitions 18 and 19.
* fips-fsm.fig: Add new transitions.
2008-09-15 Werner Koch <wk@g10code.com>
* gcrypt.texi: Fold the two FIPS appendices into one.
2008-09-11 Werner Koch <wk@g10code.com>
* gcrypt.texi (Public-Key Subsystem Architecture): Explain RSA
blinding.
2008-09-08 Marcus Brinkmann <marcus@g10code.com>
* gcrypt.texi: Some typos fixed.
2008-09-08 Werner Koch <wk@g10code.com>
* gcrypt.texi: Formatting cleanups.
* lgpl.texi (Library Copying): Replace @appendix by @unnumbered.
* gpl.texi (Copying): Ditto.
2008-08-27 Werner Koch <wk@g10code.com>
* Makefile.am (online): Take care of development versions.
2008-08-18 Werner Koch <wk@g10code.com>
* gcrypt.texi (Top): Remove the detailmenu.
(Public Key Cryptographi (II)): Move into a section of the PK
interface description.
(Hashing): Move after the encryption chapters.
2008-08-15 Werner Koch <wk@g10code.com>
* gcrypt.texi (Controlling the library): Remove
GCRYCTL_DUMP_CONFIG because it is not implemented.
(Initializing the library): Describe initialization steps with
regard to secure memory.
* gcrypt.texi (Working with cipher handles): Adjust for
implementation changes of gcry_cipher_setkey, gcry_cipher_setiv and
gcry_cipher_setctr.
2008-01-04 Werner Koch <wk@g10code.com>
* gcrypt.texi (Controlling the library): Add remark that the
theoritical attack on a seed file is not feasible under Linux.
2007-12-11 Werner Koch <wk@g10code.com>
* gcrypt.texi: Various minor corrections as reported by Elie De
Brauer more than a year ago.
2007-06-15 Werner Koch <wk@g10code.com>
* gcrypt.texi (Controlling the library): Clarified the use of
GCRYCTL_ENABLE_QUICK_RANDOM.
2007-04-30 Werner Koch <wk@g10code.com>
* HACKING: New. Two items by Marcus.
* README.apichanges: Move from .. to here.
* Makefile.am (EXTRA_DIST): Add new files.
2007-04-09 Marcus Brinkmann <marcus@g10code.de>
* gcrypt.texi: Fix some typos.
2006-11-05 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (General public-key related Functions): Typo.
2006-09-19 Werner Koch <wk@g10code.com>
* Makefile.am (online): New target.
2006-08-29 Werner Koch <wk@g10code.com>
* gcrypt.texi (Available ciphers): Add missing ciphers.
2006-03-10 Brad Hards <bradh@frogmouth.net> (wk, patch 2005-04-25)
* gcrypt.texi: Document SHA-224 and typo fixes.
2006-01-18 Brad Hards <bradh@frogmouth.net> (wk 2006-03-07)
* gcrypt.texi (Available cipher modes): Typo fix, add a little
more detail on cipher modes vs cipher algorithms.
2006-01-08 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi: Added documentation for more gcry_control commands.
* gcrypt.texi: Fixed several typos; thanks to Tommi Vainikainen.
2005-12-16 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (MPI formats): Fix return types of functions:
gcry_mpi_scan, gcry_mpi_print, gcry_mpi_aprint.
2005-11-26 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi: New chapter: Prime numbers.
2005-11-12 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (MPI formats): Document that for gcry_mpi_scan and
in the case of GCRYMPI_FMT_HEX, BUFLEN must be zero.
2005-10-31 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi: Added more gcry_control related descriptions.
2005-10-16 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Controlling the library): Start documenting the
existing control commands.
2005-04-11 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Available hash algorithms): Add entry for Whirlpool.
2005-03-30 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Working with IO objects): Document ac io objects;
adjust ac scheme functions, which do now use io objects.
2005-03-19 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Working with cipher handles): Clarify CTS mode.
2005-02-08 Werner Koch <wk@g10code.com>
* gcrypt.texi: Fixed direntry.
2005-02-13 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Using cryptographic functions): Document new
encoding and scheme crypto functionality.
2005-02-03 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi: Fixed several typos; thanks to Michele Baldessari.
2005-01-04 Werner Koch <wk@g10code.com>
* gcrypt.texi: Updated to use @copying. Fixed list of copyright
years; we had real changes in 2004. Fixed some formatting issues.
2004-08-24 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Miscellaneous): Document gcry_mpi_randomize.
2004-08-18 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Multi Threading): Document
GCRY_THREAD_OPTION_PTH_IMPL, GCRY_THREAD_OPTION_PTHREAD_IMPL.
2004-05-07 Moritz Schulte <moritz@g10code.de>
* gcrypt.texi: Merged several fixes reported by Umberto Salsi.
2004-04-08 Moritz Schulte <moritz@g10code.de>
* gcrypt.texi (Multi Threading): Typo fix.
2004-03-11 Marcus Brinkmann <marcus@g10code.de>
* gcrypt.texi (Multi Threading): Partially document new thread
support.
2004-02-24 Werner Koch <wk@gnupg.org>
* gcrypt.texi (Calculations): Typo fix.
2004-01-25 Moritz Schulte <mo@g10code.com>
* gcrypt.texi (General cipher functions): Fixed descriptions of
the arguments for GCRYCTL_GET_KEYLEN, GCRYCTL_GET_BLKLEN; reported
by Randy.
2004-01-14 Moritz Schulte <mo@g10code.com>
* gcrypt.texi (Public Key cryptography II): Adjusted to new
gcry_ac_* API; document flags.
2003-12-04 Werner Koch <wk@gnupg.org>
* Makefile.am (gcrypt_TEXINFOS): Removed fdl.texi.
2003-12-03 Werner Koch <wk@gnupg.org>
* gcrypt.texi: Changed license from FDL to GPL because this is a
reference manual only useful along with actual code.
* fdl.texi: Removed.
* gcrypt.texi: Minor cleanups
(Working with keys): Clarified generation of RSA's E parameter.
(Multi Threading): Clarified.
2003-11-11 Werner Koch <wk@gnupg.org>
* gcrypt.texi (Working with S-expressions): Added "%b".
2003-11-04 Werner Koch <wk@gnupg.org>
* gcrypt.texi (Retrieving random numbers): Add gcry_create_nonce.
2003-08-30 Werner Koch <wk@gnupg.org>
* gcrypt.texi (Working with hash algorithms): Clarified that HMAC
does not work with all algorithms.
2003-07-30 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Available asymmetric algorithms): Mention
GCRY_AC_ELG_E.
2003-07-28 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Working with keys): Mention that gcry_pk_testkey
and gcry_ac_key_test only verify private keys.
(Working with keys): Fix typo.
(General public-key related Functions): Fixed some sentences,
thanks to Neil Spring.
2003-07-27 Werner Koch <wk@gnupg.org>
* gcrypt.texi: Adjusted description of gcry_mpi_scan and
gcry_mpi_dump. Add gcry_mpi_dump.
2003-07-22 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi: Added more documentation for the register
mechanism.
2003-07-18 Werner Koch <wk@gnupg.org>
* gcrypt.texi (Misc): Add a warning on the use of opaque values.
2003-07-14 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Overview): Mention the non-thread-safe-nature of
functions modifying context stored in handles.
2003-07-12 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Available ciphers): Added: TWOFISH128.
(Error Handling): Merged a lot of documentation taken from GPGME.
2003-07-08 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Working with sets of data): Documented:
gcry_ac_data_copy.
2003-07-07 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi: Documented module system.
2003-07-05 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Working with cipher handles): Small fix by Simon
Josefsson <jas@extundo.com>.
2003-07-02 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi: Documented ac interface.
2003-06-18 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi: Small fixes.
2003-06-16 Moritz Schulte <moritz@g10code.com>
* cipher-ref.sgml: Removed file.
* digest-ref.sgml: Likewise.
* misc-ref.sgml: Likewise.
* pubkey-ref.sgml: Likewise.
* reference.sgml: Likewise.
* version.sgml.in: Likewise.
2003-06-15 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi: Documented several parts of the library, merged
some documentation from GPGME's manual, re-structured the whole
manual, added more menus.
2003-06-14 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Hash Functions): Adjusteded description of
gcry_md_copy.
2003-06-12 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Public Key Functions): Fix example S-Exp, i.e.:
added the number of following digits as prefix to the number of
bits.
(Public Key Functions): Document the general usage of `flags',
including the no-blinding flag.
2003-06-11 Werner Koch <wk@gnupg.org>
* gcrypt.texi (Hash Functions): Document possible values of HD.
2003-06-09 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Version Check): Changed description of
gcry_check_version; the user now *must* call the function to
initialize the library.
2003-06-08 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi: Change for libgpg-error.
2003-05-22 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Public Key Functions): Fixed typo.
2003-05-17 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Public Key Functions): Mention that only the
checking of secret keys is supported currently.
2003-03-30 Simon Josefsson <jas@extundo.com>
* gcrypt.texi: Add CTR.
2003-03-22 Simon Josefsson <jas@extundo.com>
* gcrypt.texi: Add CBC-MAC.
2003-03-04 Moritz Schulte <moritz@g10code.com>
* gcrypt.texi (Cipher Functions): Added gcry_cipher_reset.
2003-01-23 Werner Koch <wk@gnupg.org>
* gcrypt.texi (gcry_pk_decrypt): Described use of FLAGS
2003-01-20 Simon Josefsson <jas@extundo.com>
* gcrypt.texi (Hash Functions): Add CRC.
2003-01-19 Werner Koch <wk@gnupg.org>
* gcrypt.texi: Most functions are now documented. Still need to
fine tune the menu structure, document some utility functions,
mark up indices and references and add examples.
2002-08-14 Werner Koch <wk@gnupg.org>
* gcrypt.texi: Typo fixes.
2002-05-14 Werner Koch <wk@gnupg.org>
* lgpl.texi: New.
* gcrypt.texi: Included lgpl and commented not yet converted text.
2002-04-16 Werner Koch <wk@gnupg.org>
* version.sgml.in, cipher-ref.sgml, digest-ref.sgml, misc-ref.sgml
* pubkey-ref.sgml, reference.sgml: Removed.
* gcrypt.texi: New. Based on the old sgml version.
* gpl.texi, fdl.texi: New.
* Makefile.am: Adjusted for use with texinfo.
2000-12-21 Werner Koch <wk@gnupg.org>
Renamed the gcryptref.sgml files and removed the GnuPG stuff.
Tue Oct 26 14:10:21 CEST 1999 Werner Koch <wk@gnupg.de>
* Makefile.am (SUBDIRS): Removed gph from this development series
Mon Sep 6 19:59:08 CEST 1999 Werner Koch <wk@isil.d.shuttle.de>
* Makefile.am (SUBDIRS): New subdir gph for the manual.
Thu Jul 22 20:03:03 CEST 1999 Werner Koch <wk@isil.d.shuttle.de>
* gpg.sgml (--always-trust): Added.
Wed Jul 14 19:42:08 CEST 1999 Werner Koch <wk@isil.d.shuttle.de>
* Makefile.am: Create a dummy man page if docbook-to-man is missing.
Wed Jun 16 20:16:21 CEST 1999 Werner Koch <wk@isil.d.shuttle.de>
* gpg1.pod: Removed.
* gpg.sgml: New. Replaces the pod file
* Makefile.am: Add rule to make a man file from sgml
Tue Jun 15 12:21:08 CEST 1999 Werner Koch <wk@isil.d.shuttle.de>
* Makefile.in.in: Use DESTDIR.
Mon May 31 19:41:10 CEST 1999 Werner Koch <wk@isil.d.shuttle.de>
* gpg.1pod: Enhanced the Bugs section (Michael).
Wed Feb 10 17:15:39 CET 1999 Werner Koch <wk@isil.d.shuttle.de>
* gpg.1pod: Spelling and grammar corrections (John A. Martin)
* FAQ: Ditto.
* DETAILS: Ditto.
Copyright 1999, 2000, 2002, 2003, 2008 Free Software Foundation, Inc.
This file is free software; as a special exception the author gives
unlimited permission to copy and/or distribute it, with or without
modifications, as long as this notice is preserved.
This file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
diff --git a/doc/announce.txt b/doc/announce.txt
index 6f2925f2..48c41bf4 100644
--- a/doc/announce.txt
+++ b/doc/announce.txt
@@ -1,87 +1,91 @@
To: gnupg-announce@gnupg.org, info-gnu@gnu.org
Cc: gcrypt-devel@gnupg.org
Hello!
The GNU project is pleased to announce the availability of Libgcrypt
version 1.4.3.
Libgcrypt is a general purpose library of cryptographic building
blocks. It is originally based on code used by GnuPG. It does not
provide any implementation of OpenPGP or other protocols. Thorough
understanding of applied cryptography is required to use Libgcrypt.
Noteworthy changes in version 1.4.3:
* Try to auto-initialize Libgcrypt to minimize the effect of
applications not doing that correctly. This is not a perfect
solution but given that many applicationion would totally fail
without such a hack, we try to help at least with the most common
cases. Folks, please read the manual to learn how to properly
initialize Libgcrypt!
* Auto-initialize the secure memory to 32k instead of aborting the
process.
* Log fatal errors via syslog.
* Changed the name and the semantics of the fips mode config file.
* Add convenience macro gcry_fips_mode_active.
* More self-tests.
* Documentation cleanups.
Source code is hosted at the GnuPG FTP server and its mirrors as
listed at http://www.gnupg.org/download/mirrors.html . On the primary
server the source file and its digital signatures is:
- ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.4.3.tar.bz2 (k)
+ ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.4.3.tar.bz2 (1062k)
ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.4.3.tar.bz2.sig
This file is bzip2 compressed. A gzip compressed version is also
available:
- ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.4.3.tar.gz (k)
+ ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.4.3.tar.gz (1325k)
ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.4.3.tar.gz.sig
Alternativley you may upgrade version 1.4.2 using this patch file:
- ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.4.2-1.4.3.diff.bz2 (k)
+ ftp://ftp.gnupg.org/gcrypt/libgcrypt/libgcrypt-1.4.2-1.4.3.diff.bz2 (42k)
The SHA-1 checksums are:
+bdc67c1fdcec464a94dca691615f2335a12db5ce libgcrypt-1.4.3.tar.bz2
+3d9d583501ce951596fa7dd3667afd357ac7d056 libgcrypt-1.4.3.tar.gz
+e28b74c5824364e20ae7f147f1b89925f5426669 libgcrypt-1.4.2-1.4.3.diff.bz2
+
For help on developing with Libgcrypt you should read the included
manual and optional ask on the gcrypt-devel mailing list [1].
Improving Libgcrypt is costly, but you can help! We are looking for
organizations that find Libgcrypt useful and wish to contribute back.
You can contribute by reporting bugs, improve the software [2], order
extensions or support or more general by donating money to the Free
Software movement [3].
Commercial support contracts for Libgcrypt are available [4], and they
help finance continued maintenance. g10 Code GmbH, a Duesseldorf
based company, is currently funding Libgcrypt development. We are
always looking for interesting development projects.
Many thanks to all who contributed to Libgcrypt development, be it bug
fixes, code, documentation, testing or helping users.
Happy hacking,
Werner
[1] See http://www.gnupg.org/documentation/mailing-lists.html .
[2] Note that copyright assignments to the FSF are required.
[3] For example see http://donate.fsf.org .
[4] See the service directory at http://www.gnupg.org/service.html .
diff --git a/doc/fips-fsm.fig b/doc/fips-fsm.fig
index d3a307aa..a4f0aece 100644
--- a/doc/fips-fsm.fig
+++ b/doc/fips-fsm.fig
@@ -1,193 +1,199 @@
#FIG 3.2
Portrait
Center
Metric
A4
100.00
Single
-2
1200 2
0 32 #9c0000
0 33 #8c8c8c
0 34 #8c8c8c
0 35 #424242
0 36 #8c8c8c
0 37 #424242
0 38 #8c8c8c
0 39 #424242
0 40 #8c8c8c
0 41 #424242
0 42 #8c8c8c
0 43 #424242
6 900 270 8775 9450
5 1 0 2 0 7 50 -1 -1 0.000 1 1 1 0 4837.500 16740.000 6750 6705 4725 6525 2925 6705
1 1 2.00 120.00 240.00
5 1 0 2 0 7 50 -1 -1 0.000 1 1 1 0 3026.138 8399.825 4185 8370 3870 7605 2925 7245
1 1 2.00 120.00 240.00
-5 1 0 2 0 7 50 -1 -1 0.000 1 1 1 0 7708.125 -2028.750 2925 5175 4815 6120 6795 6570
+5 1 0 2 0 7 50 -1 -1 0.000 1 1 1 0 7663.125 -2028.750 2880 5175 4770 6120 6750 6570
+ 1 1 2.00 120.00 240.00
+5 1 0 2 0 7 50 -1 -1 0.000 1 1 1 0 7717.500 7211.250 7155 7470 7740 7830 8280 7470
1 1 2.00 120.00 240.00
6 3096 1593 3380 1877
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 3238 1735 142 142 3238 1735 3103 1690
4 0 0 50 -1 13 12 0.0000 4 105 105 3157 1805 1\001
-6
6 2266 3607 2550 3891
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 2408 3749 142 142 2408 3749 2273 3704
4 0 0 50 -1 13 12 0.0000 4 105 105 2327 3819 2\001
-6
6 1566 5667 1850 5951
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 1708 5809 142 142 1708 5809 1573 5764
4 0 0 50 -1 13 12 0.0000 4 105 105 1627 5879 3\001
-6
6 5706 1543 5990 1827
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 5848 1685 142 142 5848 1685 5713 1640
4 0 0 50 -1 13 12 0.0000 4 105 105 5767 1755 6\001
-6
6 5986 7757 6270 8041
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 6128 7899 142 142 6128 7899 5993 7854
4 0 0 50 -1 13 12 0.0000 4 105 105 6047 7969 7\001
-6
6 7426 4747 7710 5031
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 7568 4889 142 142 7568 4889 7433 4844
4 0 0 50 -1 13 12 0.0000 4 105 105 7487 4959 8\001
-6
6 5866 3737 6150 4021
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 6008 3879 142 142 6008 3879 5873 3834
4 0 0 50 -1 13 12 0.0000 4 105 210 5882 3940 10\001
-6
6 5276 2517 5560 2801
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 5418 2659 142 142 5418 2659 5283 2614
4 0 0 50 -1 13 12 0.0000 4 105 210 5292 2720 11\001
-6
6 4126 3573 4410 3857
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 4268 3715 142 142 4268 3715 4133 3670
4 0 0 50 -1 13 12 0.0000 4 105 210 4142 3776 12\001
-6
6 3066 5723 3350 6007
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 3208 5865 142 142 3208 5865 3073 5820
4 0 0 50 -1 13 12 0.0000 4 105 210 3082 5926 13\001
-6
6 4036 6623 4320 6907
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 4178 6765 142 142 4178 6765 4043 6720
4 0 0 50 -1 13 12 0.0000 4 105 210 4052 6826 14\001
-6
6 4416 7213 4700 7497
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 4558 7355 142 142 4558 7355 4423 7310
4 0 0 50 -1 13 12 0.0000 4 105 210 4432 7416 15\001
-6
6 5066 7223 5350 7507
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 5208 7365 142 142 5208 7365 5073 7320
4 0 0 50 -1 13 12 0.0000 4 105 105 5127 7435 5\001
-6
6 3566 7573 3850 7857
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 3708 7715 142 142 3708 7715 3573 7670
4 0 0 50 -1 13 12 0.0000 4 105 210 3582 7776 16\001
-6
6 2896 7783 3180 8067
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 3038 7925 142 142 3038 7925 2903 7880
4 0 0 50 -1 13 12 0.0000 4 105 105 2957 7995 4\001
-6
6 6426 5753 6710 6037
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 6568 5895 142 142 6568 5895 6433 5850
4 0 0 50 -1 13 12 0.0000 4 105 105 6487 5965 9\001
-6
6 3600 8370 5985 9450
2 4 0 1 0 7 50 -1 -1 0.000 0 0 20 0 0 5
5970 9450 3600 9450 3600 8370 5970 8370 5970 9450
4 0 0 50 -1 0 24 0.0000 4 330 1725 3870 9000 Operational\001
-6
6 900 4320 2970 5445
2 4 0 1 0 7 50 -1 -1 0.000 0 0 20 0 0 5
2940 5445 915 5445 915 4335 2940 4335 2940 5445
4 0 0 50 -1 0 24 0.0000 4 240 510 1620 4995 Init\001
-6
6 900 6345 2970 7470
2 4 0 1 0 7 50 -1 -1 0.000 0 0 20 0 0 5
2955 7455 930 7455 930 6345 2955 6345 2955 7455
4 0 0 50 -1 0 24 0.0000 4 255 1335 1215 7020 Self-Test\001
-6
6 6750 6345 8775 7470
2 4 0 1 0 7 50 -1 -1 0.000 0 0 20 0 0 5
8775 7470 6750 7470 6750 6360 8775 6360 8775 7470
4 0 0 50 -1 0 24 0.0000 4 240 765 7335 7020 Error\001
-6
6 3825 4320 5850 5445
2 4 0 1 0 7 50 -1 -1 0.000 0 0 20 0 0 5
5850 5445 3825 5445 3825 4335 5850 4335 5850 5445
4 0 0 50 -1 0 24 0.0000 4 255 1620 3915 4995 Fatal-Error\001
-6
6 6750 2295 8775 3420
2 4 0 1 0 7 50 -1 -1 0.000 0 0 20 0 0 5
8775 3420 6750 3420 6750 2310 8775 2310 8775 3420
4 0 0 50 -1 0 24 0.0000 4 240 1455 6930 2970 Shutdown\001
-6
6 2475 2295 4500 3420
2 4 0 1 0 7 50 -1 -1 0.000 0 0 20 0 0 5
4500 3405 2475 3405 2475 2295 4500 2295 4500 3405
4 0 0 50 -1 0 24 0.0000 4 240 1470 2655 2970 Power-On\001
-6
6 2475 270 4500 1395
2 4 0 1 0 7 50 -1 -1 0.000 0 0 20 0 0 5
4500 1395 2475 1395 2475 285 4500 285 4500 1395
4 0 0 50 -1 0 24 0.0000 4 240 1530 2565 945 Power-Off\001
-6
6 4050 6196 4334 6480
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 4192 6338 142 142 4192 6338 4057 6293
4 0 0 50 -1 13 12 0.0000 4 105 210 4066 6399 17\001
-6
-6 3188 5033 3486 5331
-1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 3337 5182 142 142 3337 5182 3202 5137
-4 0 0 50 -1 13 12 0.0000 4 105 210 3211 5243 18\001
--6
6 3053 4358 3351 4656
1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 3202 4507 142 142 3202 4507 3067 4462
4 0 0 50 -1 13 12 0.0000 4 105 210 3076 4568 19\001
-6
+6 3032 5012 3330 5310
+1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 3181 5161 142 142 3181 5161 3046 5116
+4 0 0 50 -1 13 12 0.0000 4 105 210 3055 5222 18\001
+-6
+6 7560 7847 7858 8145
+1 3 0 1 0 7 50 -1 -1 0.000 1 0.0000 7709 7996 142 142 7709 7996 7574 7951
+4 0 0 50 -1 13 12 0.0000 4 105 210 7612 8047 20\001
+-6
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
3420 1395 3420 2295
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
3465 3420 4815 4320
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
1890 5445 1890 6345
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
2835 7380 3735 8415
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
4725 8370 4725 5490
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
4950 8370 7335 3420
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
2925 6930 6750 6930
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
2880 6480 3915 5355
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
4500 2835 6750 2835
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
7740 6345 7740 3420
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
3375 3420 1890 4320
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
5760 4410 6840 3330
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
7740 2295 4500 855
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
6840 6435 5760 5355
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
5895 8460 6840 7380
2 1 0 2 0 7 50 -1 -1 0.000 0 1 -1 1 0 2
1 1 2.00 120.00 240.00
2925 4680 3825 4680
-6
diff --git a/doc/gcrypt.texi b/doc/gcrypt.texi
index f1a02bc4..a1bb696b 100644
--- a/doc/gcrypt.texi
+++ b/doc/gcrypt.texi
@@ -1,5699 +1,5726 @@
\input texinfo @c -*- Texinfo -*-
@c %**start of header
@setfilename gcrypt.info
@include version.texi
@settitle The Libgcrypt Reference Manual
@c Unify some of the indices.
@syncodeindex tp fn
@syncodeindex pg fn
@c %**end of header
@copying
This manual is for Libgcrypt
(version @value{VERSION}, @value{UPDATED}),
which is GNU's library of cryptographic building blocks.
Copyright @copyright{} 2000, 2002, 2003, 2004, 2006, 2007, 2008 Free Software Foundation, Inc.
@quotation
Permission is granted to copy, distribute and/or modify this document
under the terms of the GNU General Public License as published by the
Free Software Foundation; either version 2 of the License, or (at your
option) any later version. The text of the license can be found in the
section entitled ``GNU General Public License''.
@end quotation
@end copying
@dircategory GNU Libraries
@direntry
* libgcrypt: (gcrypt). Cryptographic function library.
@end direntry
@c
@c Titlepage
@c
@setchapternewpage odd
@titlepage
@title The Libgcrypt Reference Manual
@subtitle Version @value{VERSION}
@subtitle @value{UPDATED}
@author Werner Koch (@email{wk@@gnupg.org})
@author Moritz Schulte (@email{mo@@g10code.com})
@page
@vskip 0pt plus 1filll
@insertcopying
@end titlepage
@ifnothtml
@summarycontents
@contents
@page
@end ifnothtml
@ifnottex
@node Top
@top The Libgcrypt Library
@insertcopying
@end ifnottex
@menu
* Introduction:: What is Libgcrypt.
* Preparation:: What you should do before using the library.
* Generalities:: General library functions and data types.
* Handler Functions:: Working with handler functions.
* Symmetric cryptography:: How to use symmetric cryptography.
* Public Key cryptography:: How to use public key cryptography.
* Hashing:: How to use hash and MAC algorithms.
* Random Numbers:: How to work with random numbers.
* S-expressions:: How to manage S-expressions.
* MPI library:: How to work with multi-precision-integers.
* Prime numbers:: How to use the Prime number related functions.
* Utilities:: Utility functions.
* Architecture:: How Libgcrypt works internally.
Appendices
* Self-Tests:: Description of the self-tests.
* FIPS Mode:: Description of the FIPS mode.
* Library Copying:: The GNU Lesser General Public License
says how you can copy and share Libgcrypt.
* Copying:: The GNU General Public License says how you
can copy and share some parts of Libgcrypt.
Indices
* Figures and Tables:: Index of figures and tables.
* Concept Index:: Index of concepts and programs.
* Function and Data Index:: Index of functions, variables and data types.
@end menu
@ifhtml
@page
@summarycontents
@contents
@end ifhtml
@c **********************************************************
@c ******************* Introduction ***********************
@c **********************************************************
@node Introduction
@chapter Introduction
Libgcrypt is a library providing cryptographic building blocks.
@menu
* Getting Started:: How to use this manual.
* Features:: A glance at Libgcrypt's features.
* Overview:: Overview about the library.
@end menu
@node Getting Started
@section Getting Started
This manual documents the Libgcrypt library application programming
interface (API). All functions and data types provided by the library
are explained.
@noindent
The reader is assumed to possess basic knowledge about applied
cryptography.
This manual can be used in several ways. If read from the beginning
to the end, it gives a good introduction into the library and how it
can be used in an application. Forward references are included where
necessary. Later on, the manual can be used as a reference manual to
get just the information needed about any particular interface of the
library. Experienced programmers might want to start looking at the
examples at the end of the manual, and then only read up those parts
of the interface which are unclear.
@node Features
@section Features
Libgcrypt might have a couple of advantages over other libraries doing
a similar job.
@table @asis
@item It's Free Software
Anybody can use, modify, and redistribute it under the terms of the GNU
Lesser General Public License (@pxref{Library Copying}). Note, that
some parts (which are in general not needed by applications) are subject
to the terms of the GNU General Public License (@pxref{Copying}); please
see the README file of the distribution for of list of these parts.
@item It encapsulates the low level cryptography
Libgcrypt provides a high level interface to cryptographic
building blocks using an extensible and flexible API.
@end table
@node Overview
@section Overview
@noindent
The Libgcrypt library is fully thread-safe, where it makes
sense to be thread-safe. Not thread-safe are some cryptographic
functions that modify a certain context stored in handles. If the
user really intents to use such functions from different threads on
the same handle, he has to take care of the serialization of such
functions himself. If not described otherwise, every function is
thread-safe.
Libgcrypt depends on the library `libgpg-error', which
contains common error handling related code for GnuPG components.
@c **********************************************************
@c ******************* Preparation ************************
@c **********************************************************
@node Preparation
@chapter Preparation
To use Libgcrypt, you have to perform some changes to your
sources and the build system. The necessary changes are small and
explained in the following sections. At the end of this chapter, it
is described how the library is initialized, and how the requirements
of the library are verified.
@menu
* Header:: What header file you need to include.
* Building sources:: How to build sources using the library.
* Building sources using Automake:: How to build sources with the help of Automake.
* Initializing the library:: How to initialize the library.
* Multi-Threading:: How Libgcrypt can be used in a MT environment.
* Enabling FIPS mode:: How to enable the FIPS mode.
@end menu
@node Header
@section Header
All interfaces (data types and functions) of the library are defined
in the header file @file{gcrypt.h}. You must include this in all source
files using the library, either directly or through some other header
file, like this:
@example
#include <gcrypt.h>
@end example
The name space of Libgcrypt is @code{gcry_*} for function
and type names and @code{GCRY*} for other symbols. In addition the
same name prefixes with one prepended underscore are reserved for
internal use and should never be used by an application. Note that
Libgcrypt uses libgpg-error, which uses @code{gpg_*} as
name space for function and type names and @code{GPG_*} for other
symbols, including all the error codes.
@noindent
Certain parts of gcrypt.h may be excluded by defining these macros:
@table @code
@item GCRYPT_NO_MPI_MACROS
Do not define the shorthand macros @code{mpi_*} for @code{gcry_mpi_*}.
@item GCRYPT_NO_DEPRECATED
Do not include defintions for deprecated features. This is useful to
make sure that no deprecated features are used.
@end table
@node Building sources
@section Building sources
If you want to compile a source file including the `gcrypt.h' header
file, you must make sure that the compiler can find it in the
directory hierarchy. This is accomplished by adding the path to the
directory in which the header file is located to the compilers include
file search path (via the @option{-I} option).
However, the path to the include file is determined at the time the
source is configured. To solve this problem, Libgcrypt ships with a small
helper program @command{libgcrypt-config} that knows the path to the
include file and other configuration options. The options that need
to be added to the compiler invocation at compile time are output by
the @option{--cflags} option to @command{libgcrypt-config}. The following
example shows how it can be used at the command line:
@example
gcc -c foo.c `libgcrypt-config --cflags`
@end example
Adding the output of @samp{libgcrypt-config --cflags} to the compilers
command line will ensure that the compiler can find the Libgcrypt header
file.
A similar problem occurs when linking the program with the library.
Again, the compiler has to find the library files. For this to work,
the path to the library files has to be added to the library search path
(via the @option{-L} option). For this, the option @option{--libs} to
@command{libgcrypt-config} can be used. For convenience, this option
also outputs all other options that are required to link the program
with the Libgcrypt libraries (in particular, the @samp{-lgcrypt}
option). The example shows how to link @file{foo.o} with the Libgcrypt
library to a program @command{foo}.
@example
gcc -o foo foo.o `libgcrypt-config --libs`
@end example
Of course you can also combine both examples to a single command by
specifying both options to @command{libgcrypt-config}:
@example
gcc -o foo foo.c `libgcrypt-config --cflags --libs`
@end example
@node Building sources using Automake
@section Building sources using Automake
It is much easier if you use GNU Automake instead of writing your own
Makefiles. If you do that, you do not have to worry about finding and
invoking the @command{libgcrypt-config} script at all.
Libgcrypt provides an extension to Automake that does all
the work for you.
@c A simple macro for optional variables.
@macro ovar{varname}
@r{[}@var{\varname\}@r{]}
@end macro
@defmac AM_PATH_LIBGCRYPT (@ovar{minimum-version}, @ovar{action-if-found}, @ovar{action-if-not-found})
Check whether Libgcrypt (at least version
@var{minimum-version}, if given) exists on the host system. If it is
found, execute @var{action-if-found}, otherwise do
@var{action-if-not-found}, if given.
Additionally, the function defines @code{LIBGCRYPT_CFLAGS} to the
flags needed for compilation of the program to find the
@file{gcrypt.h} header file, and @code{LIBGCRYPT_LIBS} to the linker
flags needed to link the program to the Libgcrypt library.
@end defmac
You can use the defined Autoconf variables like this in your
@file{Makefile.am}:
@example
AM_CPPFLAGS = $(LIBGCRYPT_CFLAGS)
LDADD = $(LIBGCRYPT_LIBS)
@end example
@node Initializing the library
@section Initializing the library
Before the library can be used, it must initialize itself. This is
achieved by invoking the function @code{gcry_check_version} described
below.
Also, it is often desirable to check that the version of
Libgcrypt used is indeed one which fits all requirements.
Even with binary compatibility, new features may have been introduced,
but due to problem with the dynamic linker an old version may actually
be used. So you may want to check that the version is okay right
after program startup.
@deftypefun {const char *} gcry_check_version (const char *@var{req_version})
The function @code{gcry_check_version} initializes some subsystems used
by Libgcrypt and must be invoked before any other function in the
library, with the exception of the @code{GCRYCTL_SET_THREAD_CBS} command
(called via the @code{gcry_control} function).
@xref{Multi-Threading}.
Furthermore, this function returns the version number of the library.
It can also verify that the version number is higher than a certain
required version number @var{req_version}, if this value is not a null
pointer.
@end deftypefun
Libgcrypt uses a concept known as secure memory, which is a region of
memory set aside for storing sensitive data. Because such memory is a
scarce resource, it needs to be setup in advanced to a fixed size.
Further, most operating systems have special requirements on how that
secure memory can be used. For example, it might be required to install
an application as ``setuid(root)'' to allow allocating such memory.
Libgcrypt requires a sequence of initialization steps to make sure that
this works correctly. The following examples show the necessary steps.
If you don't have a need for secure memory, for example if your
application does not use secret keys or other confidential data or it
runs in a controlled environment where key material floating around in
memory is not a problem, you should initialize Libgcrypt this way:
@example
/* Version check should be the very first call because it
makes sure that important subsystems are intialized. */
if (!gcry_check_version (GCRYPT_VERSION))
@{
fputs ("libgcrypt version mismatch\n", stderr);
exit (2);
@}
/* Disable secure memory. */
gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
/* ... If required, other initialization goes here. */
/* Tell Libgcrypt that initialization has completed. */
gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
@end example
If you have to protect your keys or other information in memory against
being swapped out to disk and to enable an automatic overwrite of used
and freed memory, you need to initialize Libgcrypt this way:
@example
/* Version check should be the very first call because it
makes sure that important subsystems are intialized. */
if (!gcry_check_version (GCRYPT_VERSION))
@{
fputs ("libgcrypt version mismatch\n", stderr);
exit (2);
@}
@anchor{sample-use-suspend-secmem}
/* We don't want to see any warnings, e.g. because we have not yet
parsed program options which might be used to suppress such
warnings. */
gcry_control (GCRYCTL_SUSPEND_SECMEM_WARN);
/* ... If required, other initialization goes here. Note that the
process might still be running with increased privileges and that
the secure memory has not been intialized. */
/* Allocate a pool of 16k secure memory. This make the secure memory
available and also drops privileges where needed. */
gcry_control (GCRYCTL_INIT_SECMEM, 16384, 0);
@anchor{sample-use-resume-secmem}
/* It is now okay to let Libgcrypt complain when there was/is
a problem with the secure memory. */
gcry_control (GCRYCTL_RESUME_SECMEM_WARN);
/* ... If required, other initialization goes here. */
/* Tell Libgcrypt that initialization has completed. */
gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
@end example
It is important that these initialization steps are not done by a
library but by the actual application. A library using Libgcrypt might
want to check for finished initialization using:
@example
if (!gcry_control (GCRYCTL_INITIALIZATION_FINISHED_P))
@{
fputs ("libgcrypt has not been initialized\n", stderr);
abort ();
@}
@end example
Instead of terminating the process, the library may instead print a
warning and try to initialize Libgcrypt itself. See also the section on
multi-threading below for more pitfalls.
@node Multi-Threading
@section Multi-Threading
As mentioned earlier, the Libgcrypt library is
thread-safe if you adhere to the following requirements:
@itemize @bullet
@item
If your application is multi-threaded, you must set the thread support
callbacks with the @code{GCRYCTL_SET_THREAD_CBS} command
@strong{before} any other function in the library.
This is easy enough if you are indeed writing an application using
Libgcrypt. It is rather problematic if you are writing a library
instead. Here are some tips what to do if you are writing a library:
If your library requires a certain thread package, just initialize
Libgcrypt to use this thread package. If your library supports multiple
thread packages, but needs to be configured, you will have to
implement a way to determine which thread package the application
wants to use with your library anyway. Then configure Libgcrypt to use
this thread package.
If your library is fully reentrant without any special support by a
thread package, then you are lucky indeed. Unfortunately, this does
not relieve you from doing either of the two above, or use a third
option. The third option is to let the application initialize Libgcrypt
for you. Then you are not using Libgcrypt transparently, though.
As if this was not difficult enough, a conflict may arise if two
libraries try to initialize Libgcrypt independently of each others, and
both such libraries are then linked into the same application. To
make it a bit simpler for you, this will probably work, but only if
both libraries have the same requirement for the thread package. This
is currently only supported for the non-threaded case, GNU Pth and
pthread. Support for more thread packages is easy to add, so contact
us if you require it.
@item
The function @code{gcry_check_version} must be called before any other
function in the library, except the @code{GCRYCTL_SET_THREAD_CBS}
command (called via the @code{gcry_control} function), because it
initializes the thread support subsystem in Libgcrypt. To
achieve this in multi-threaded programs, you must synchronize the
memory with respect to other threads that also want to use
Libgcrypt. For this, it is sufficient to call
@code{gcry_check_version} before creating the other threads using
Libgcrypt@footnote{At least this is true for POSIX threads,
as @code{pthread_create} is a function that synchronizes memory with
respects to other threads. There are many functions which have this
property, a complete list can be found in POSIX, IEEE Std 1003.1-2003,
Base Definitions, Issue 6, in the definition of the term ``Memory
Synchronization''. For other thread packages, more relaxed or more
strict rules may apply.}.
@item
Just like the function @code{gpg_strerror}, the function
@code{gcry_strerror} is not thread safe. You have to use
@code{gpg_strerror_r} instead.
@end itemize
Libgcrypt contains convenient macros, which define the
necessary thread callbacks for PThread and for GNU Pth:
@table @code
@item GCRY_THREAD_OPTION_PTH_IMPL
This macro defines the following (static) symbols:
@code{gcry_pth_init}, @code{gcry_pth_mutex_init},
@code{gcry_pth_mutex_destroy}, @code{gcry_pth_mutex_lock},
@code{gcry_pth_mutex_unlock}, @code{gcry_pth_read},
@code{gcry_pth_write}, @code{gcry_pth_select},
@code{gcry_pth_waitpid}, @code{gcry_pth_accept},
@code{gcry_pth_connect}, @code{gcry_threads_pth}.
After including this macro, @code{gcry_control()} shall be used with a
command of @code{GCRYCTL_SET_THREAD_CBS} in order to register the
thread callback structure named ``gcry_threads_pth''.
@item GCRY_THREAD_OPTION_PTHREAD_IMPL
This macro defines the following (static) symbols:
@code{gcry_pthread_mutex_init}, @code{gcry_pthread_mutex_destroy},
@code{gcry_pthread_mutex_lock}, @code{gcry_pthread_mutex_unlock},
@code{gcry_threads_pthread}.
After including this macro, @code{gcry_control()} shall be used with a
command of @code{GCRYCTL_SET_THREAD_CBS} in order to register the
thread callback structure named ``gcry_threads_pthread''.
@end table
Note that these macros need to be terminated with a semicolon. Keep
in mind that these are convenient macros for C programmers; C++
programmers might have to wrap these macros in an ``extern C'' body.
@node Enabling FIPS mode
@section How to enable the FIPS mode
@cindex FIPS mode
Libgcrypt may be used in a FIPS 140-2 mode. Note, that this does not
necessary mean that Libcgrypt is an appoved FIPS 140-2 module. Check the
NIST database at @url{http://csrc.nist.gov/groups/STM/cmvp/} to see what
versions of Libgcrypt are approved.
Because FIPS 140 has certain restrictions on the use of cryptography
which are not always wanted, Libgcrypt needs to be put into FIPS mode
explicitly. Three alternative mechanisms are provided to switch
Libgcrypt into this mode:
@itemize
@item
If the file @file{/proc/sys/crypto/fips_enabled} exists and contains a
numeric value other than @code{0}, Libgcrypt is put into FIPS mode at
initialization time. Obviously this works only on systems with a
@code{proc} file system (i.e. GNU/Linux).
@item
If the file @file{/etc/gcrypt/fips_enabled} exists, Libgcrypt is put
into FIPS mode at initialization time. Note that this filename is
hardwired and does not depend on any configuration options.
@item
If the application requests FIPS mode using the control command
@code{GCRYCTL_FORCE_FIPS_MODE}. This must be done prior to any
initialization (i.e. before @code{gcry_check_version}).
@end itemize
@cindex Enforced FIPS mode
In addition to the standard FIPS mode, Libgcrypt may also be put into
an Enforced FIPS mode by writing a non-zero value into the file
@file{/etc/gcrypt/fips_enabled}. The Enforced FIPS mode helps to
detect applications which don't fulfill all requirements for using
Libgcrypt in FIPS mode (@pxref{FIPS Mode}).
Once Libgcrypt has been put into FIPS mode, it is not possible to
switch back to standard mode without terminating the process first.
If the logging verbosity level of Libgcrypt has been set to at least
2, the state transitions and the self-tests are logged.
@c **********************************************************
@c ******************* General ****************************
@c **********************************************************
@node Generalities
@chapter Generalities
@menu
* Controlling the library:: Controlling Libgcrypt's behavior.
* Modules:: Description of extension modules.
* Error Handling:: Error codes and such.
@end menu
@node Controlling the library
@section Controlling the library
@deftypefun gcry_error_t gcry_control (enum gcry_ctl_cmds @var{cmd}, ...)
This function can be used to influence the general behavior of
Libgcrypt in several ways. Depending on @var{cmd}, more
arguments can or have to be provided.
@table @code
@item GCRYCTL_ENABLE_M_GUARD; Arguments: none
This command enables the built-in memory guard. It must not be used to
activate the memory guard after the memory management has already been
used; therefore it can ONLY be used at initialization time. Note that
the memory guard is NOT used when the user of the library has set his
own memory management callbacks.
@item GCRYCTL_ENABLE_QUICK_RANDOM; Arguments: none
This command inhibits the use the very secure random quality level
(@code{GCRY_VERY_STRONG_RANDOM}) and degrades all request down to
@code{GCRY_STRONG_RANDOM}. In general this is not recommened. However,
for some applications the extra quality random Libgcrypt tries to create
is not justified and this option may help to get better performace.
Please check with a crypto expert whether this option can be used for
your application.
This option can only be used at initialization time.
@item GCRYCTL_DUMP_RANDOM_STATS; Arguments: none
This command dumps randum number generator related statistics to the
library's logging stream.
@item GCRYCTL_DUMP_MEMORY_STATS; Arguments: none
This command dumps memory managment related statistics to the library's
logging stream.
@item GCRYCTL_DUMP_SECMEM_STATS; Arguments: none
This command dumps secure memory manamgent related statistics to the
library's logging stream.
@item GCRYCTL_DROP_PRIVS; Arguments: none
This command disables the use of secure memory and drops the priviliges
of the current process. This command has not much use; the suggested way
to disable secure memory is to use @code{GCRYCTL_DISABLE_SECMEM} right
after initialization.
@item GCRYCTL_DISABLE_SECMEM; Arguments: none
This command disables the use of secure memory. If this command is
used in FIPS mode, FIPS mode will be disabled and the fucntion
@code{gcry_fips_mode_active} returns false. However, in Enforced FIPS
mode this command has no effect at all.
Many applications do not require secure memory, so they should disable
it right away. This command should be executed right after
@code{gcry_check_version}.
@item GCRYCTL_INIT_SECMEM; Arguments: int nbytes
This command is used to allocate a pool of secure memory and thus
enabling the use of secure memory. It also drops all extra privileges
the process has (i.e. if it is run as setuid (root)). If the argument
@var{nbytes} is 0, secure memory will be disabled. The minimum amount
of secure memory allocated is currently 16384 bytes; you may thus use a
value of 1 to request that default size.
@item GCRYCTL_TERM_SECMEM; Arguments: none
This command zeroises the secure memory and destroys the handler. The
secure memory pool may not be used anymore after running this command.
If the secure memory pool as already been destroyed, this command has
no effect. Applications might want to run this command from their
exit handler to make sure that the secure memory gets properly
destroyed. This command is not necessarily thread-safe but that
should not be needed in cleanup code. It may be called from a signal
handler.
@item GCRYCTL_DISABLE_SECMEM_WARN; Arguments: none
Disable warning messages about problems with the secure memory
subsystem. This command should be run right after
@code{gcry_check_version}.
@item GCRYCTL_SUSPEND_SECMEM_WARN; Arguments: none
Postpone warning messages from the secure memory subsystem.
@xref{sample-use-suspend-secmem,,the initialization example}, on how to
use it.
@item GCRYCTL_RESUME_SECMEM_WARN; Arguments: none
Resume warning messages from the secure memory subsystem.
@xref{sample-use-resume-secmem,,the initialization example}, on how to
use it.
@item GCRYCTL_USE_SECURE_RNDPOOL; Arguments: none
This command tells the PRNG to store random numbers in secure memory.
This command should be run right after @code{gcry_check_version} and not
later than the command GCRYCTL_INIT_SECMEM. Note that in FIPS mode the
secure memory is always used.
@item GCRYCTL_SET_RANDOM_SEED_FILE; Arguments: const char *filename
This command specifies the file, which is to be used as seed file for
the PRNG. If the seed file is registered prior to initialization of the
PRNG, the seed file's content (if it exists and seems to be valid) is
fed into the PRNG pool. After the seed file has been registered, the
PRNG can be signalled to write out the PRNG pool's content into the seed
file with the following command.
@item GCRYCTL_UPDATE_RANDOM_SEED_FILE; Arguments: none
Write out the PRNG pool's content into the registered seed file.
Multiple instances of the applications sharing the same random seed file
can be started in parallel, in which case they will read out the same
pool and then race for updating it (the last update overwrites earlier
updates). They will differentiate only by the weak entropy that is
added in read_seed_file based on the PID and clock, and up to 16 bytes
of weak random non-blockingly. The consequence is that the output of
these different instances is correlated to some extent. In a perfect
attack scenario, the attacker can control (or at least guess) the PID
and clock of the application, and drain the system's entropy pool to
reduce the "up to 16 bytes" above to 0. Then the dependencies of the
inital states of the pools are completely known. Note that this is not
an issue if random of @code{GCRY_VERY_STRONG_RANDOM} quality is
requested as in this case enough extra entropy gets mixed. It is also
not an issue when using Linux (rndlinux driver), because this one
guarantees to read full 16 bytes from /dev/urandom and thus there is no
way for an attacker without kernel access to control these 16 bytes.
@item GCRYCTL_SET_VERBOSITY; Arguments: int level
This command sets the verbosity of the logging. A level of 0 disables
all extra logging whereas positive numbers enable more verbose logging.
The level may be changed at any time but be aware that no memory
synchronization is done so the effect of this command might not
immediately show up in other threads. This command may even be used
prior to @code{gcry_check_version}.
@item GCRYCTL_SET_DEBUG_FLAGS; Arguments: unsigned int flags
Set the debug flag bits as given by the argument. Be aware that that no
memory synchronization is done so the effect of this command might not
immediately show up in other threads. The debug flags are not
considered part of the API and thus may change without notice. As of
now bit 0 enables debugging of cipher functions and bit 1 debugging of
multi-precision-integers. This command may even be used prior to
@code{gcry_check_version}.
@item GCRYCTL_CLEAR_DEBUG_FLAGS; Arguments: unsigned int flags
Set the debug flag bits as given by the argument. Be aware that that no
memory synchronization is done so the effect of this command might not
immediately show up in other threads. This command may even be used
prior to @code{gcry_check_version}.
@item GCRYCTL_DISABLE_INTERNAL_LOCKING; Arguments: none
This command does nothing. It exists only for backward compatibility.
@item GCRYCTL_ANY_INITIALIZATION_P; Arguments: none
This command returns true if the library has been basically initialized.
Such a basic initialization happens implicitly with many commands to get
certain internal subsystems running. The common and suggested way to
do this basic intialization is by calling gcry_check_version.
@item GCRYCTL_INITIALIZATION_FINISHED; Arguments: none
This command tells the libray that the application has finished the
intialization.
@item GCRYCTL_INITIALIZATION_FINISHED_P; Arguments: none
This command returns true if the command@*
GCRYCTL_INITIALIZATION_FINISHED has already been run.
@item GCRYCTL_SET_THREAD_CBS; Arguments: struct ath_ops *ath_ops
This command registers a thread-callback structure.
@xref{Multi-Threading}.
@item GCRYCTL_FAST_POLL; Arguments: none
Run a fast random poll.
@item GCRYCTL_SET_RNDEGD_SOCKET; Arguments: const char *filename
This command may be used to override the default name of the EGD socket
to connect to. It may be used only during initialization as it is not
thread safe. Changing the socket name again is not supported. The
function may return an error if the given filename is too long for a
local socket name.
EGD is an alternative random gatherer, used only on systems lacking a
proper random device.
@item GCRYCTL_PRINT_CONFIG; Arguments: FILE *stream
This command dumps information pertaining to the configuration of the
library to the given stream. If NULL is given for @var{stream}, the log
system is used. This command may be used before the intialization has
been finished but not before a gcry_version_check.
@item GCRYCTL_OPERATIONAL_P; Arguments: none
This command returns true if the library is in an operational state.
This information makes only sense in FIPS mode. In contrast to other
functions, this is a pure test function and won't put the library into
FIPS mode or change the internal state. This command may be used before
the intialization has been finished but not before a gcry_version_check.
@item GCRYCTL_FIPS_MODE_P; Arguments: none
This command returns true if the library is in FIPS mode. Note, that
this is no indication about the current state of the library. This
command may be used before the intialization has been finished but not
before a gcry_version_check. An application may use this command or
the convenience macro below to check whether FIPS mode is actually
active.
@deftypefun int gcry_fips_mode_active (void)
Returns true if the FIPS mode is active. Note that this is
implemented as a macro.
@end deftypefun
@item GCRYCTL_FORCE_FIPS_MODE; Arguments: none
Running this command puts the library into FIPS mode. If the library is
already in FIPS mode, a self-test is triggered and thus the library will
be put into operational state. This command may be used before a call
to gcry_check_version and that is actually the recommended way to let an
application switch the library into FIPS mode. Note that Libgcrypt will
reject an attempt to switch to fips mode during or after the intialization.
@item GCRYCTL_SELFTEST; Arguments: none
This may be used at anytime to have the library run all implemented
self-tests. It works in standard and in FIPS mode. Returns 0 on
success or an error code on failure.
@end table
@end deftypefun
@node Modules
@section Modules
Libgcrypt supports the use of `extension modules', which
implement algorithms in addition to those already built into the library
directly.
@deftp {Data type} gcry_module_t
This data type represents a `module'.
@end deftp
Functions registering modules provided by the user take a `module
specification structure' as input and return a value of
@code{gcry_module_t} and an ID that is unique in the modules'
category. This ID can be used to reference the newly registered
module. After registering a module successfully, the new functionality
should be able to be used through the normal functions provided by
Libgcrypt until it is unregistered again.
@c **********************************************************
@c ******************* Errors ****************************
@c **********************************************************
@node Error Handling
@section Error Handling
Many functions in Libgcrypt can return an error if they
fail. For this reason, the application should always catch the error
condition and take appropriate measures, for example by releasing the
resources and passing the error up to the caller, or by displaying a
descriptive message to the user and cancelling the operation.
Some error values do not indicate a system error or an error in the
operation, but the result of an operation that failed properly. For
example, if you try to decrypt a tempered message, the decryption will
fail. Another error value actually means that the end of a data
buffer or list has been reached. The following descriptions explain
for many error codes what they mean usually. Some error values have
specific meanings if returned by a certain functions. Such cases are
described in the documentation of those functions.
Libgcrypt uses the @code{libgpg-error} library. This allows to share
the error codes with other components of the GnuPG system, and to pass
error values transparently from the crypto engine, or some helper
application of the crypto engine, to the user. This way no
information is lost. As a consequence, Libgcrypt does not use its own
identifiers for error codes, but uses those provided by
@code{libgpg-error}. They usually start with @code{GPG_ERR_}.
However, Libgcrypt does provide aliases for the functions
defined in libgpg-error, which might be preferred for name space
consistency.
Most functions in Libgcrypt return an error code in the case
of failure. For this reason, the application should always catch the
error condition and take appropriate measures, for example by
releasing the resources and passing the error up to the caller, or by
displaying a descriptive message to the user and canceling the
operation.
Some error values do not indicate a system error or an error in the
operation, but the result of an operation that failed properly.
GnuPG components, including Libgcrypt, use an extra library named
libgpg-error to provide a common error handling scheme. For more
information on libgpg-error, see the according manual.
@menu
* Error Values:: The error value and what it means.
* Error Sources:: A list of important error sources.
* Error Codes:: A list of important error codes.
* Error Strings:: How to get a descriptive string from a value.
@end menu
@node Error Values
@subsection Error Values
@cindex error values
@cindex error codes
@cindex error sources
@deftp {Data type} {gcry_err_code_t}
The @code{gcry_err_code_t} type is an alias for the
@code{libgpg-error} type @code{gpg_err_code_t}. The error code
indicates the type of an error, or the reason why an operation failed.
A list of important error codes can be found in the next section.
@end deftp
@deftp {Data type} {gcry_err_source_t}
The @code{gcry_err_source_t} type is an alias for the
@code{libgpg-error} type @code{gpg_err_source_t}. The error source
has not a precisely defined meaning. Sometimes it is the place where
the error happened, sometimes it is the place where an error was
encoded into an error value. Usually the error source will give an
indication to where to look for the problem. This is not always true,
but it is attempted to achieve this goal.
A list of important error sources can be found in the next section.
@end deftp
@deftp {Data type} {gcry_error_t}
The @code{gcry_error_t} type is an alias for the @code{libgpg-error}
type @code{gpg_error_t}. An error value like this has always two
components, an error code and an error source. Both together form the
error value.
Thus, the error value can not be directly compared against an error
code, but the accessor functions described below must be used.
However, it is guaranteed that only 0 is used to indicate success
(@code{GPG_ERR_NO_ERROR}), and that in this case all other parts of
the error value are set to 0, too.
Note that in Libgcrypt, the error source is used purely for
diagnostic purposes. Only the error code should be checked to test
for a certain outcome of a function. The manual only documents the
error code part of an error value. The error source is left
unspecified and might be anything.
@end deftp
@deftypefun {gcry_err_code_t} gcry_err_code (@w{gcry_error_t @var{err}})
The static inline function @code{gcry_err_code} returns the
@code{gcry_err_code_t} component of the error value @var{err}. This
function must be used to extract the error code from an error value in
order to compare it with the @code{GPG_ERR_*} error code macros.
@end deftypefun
@deftypefun {gcry_err_source_t} gcry_err_source (@w{gcry_error_t @var{err}})
The static inline function @code{gcry_err_source} returns the
@code{gcry_err_source_t} component of the error value @var{err}. This
function must be used to extract the error source from an error value in
order to compare it with the @code{GPG_ERR_SOURCE_*} error source macros.
@end deftypefun
@deftypefun {gcry_error_t} gcry_err_make (@w{gcry_err_source_t @var{source}}, @w{gcry_err_code_t @var{code}})
The static inline function @code{gcry_err_make} returns the error
value consisting of the error source @var{source} and the error code
@var{code}.
This function can be used in callback functions to construct an error
value to return it to the library.
@end deftypefun
@deftypefun {gcry_error_t} gcry_error (@w{gcry_err_code_t @var{code}})
The static inline function @code{gcry_error} returns the error value
consisting of the default error source and the error code @var{code}.
For @acronym{GCRY} applications, the default error source is
@code{GPG_ERR_SOURCE_USER_1}. You can define
@code{GCRY_ERR_SOURCE_DEFAULT} before including @file{gcrypt.h} to
change this default.
This function can be used in callback functions to construct an error
value to return it to the library.
@end deftypefun
The @code{libgpg-error} library provides error codes for all system
error numbers it knows about. If @var{err} is an unknown error
number, the error code @code{GPG_ERR_UNKNOWN_ERRNO} is used. The
following functions can be used to construct error values from system
errno numbers.
@deftypefun {gcry_error_t} gcry_err_make_from_errno (@w{gcry_err_source_t @var{source}}, @w{int @var{err}})
The function @code{gcry_err_make_from_errno} is like
@code{gcry_err_make}, but it takes a system error like @code{errno}
instead of a @code{gcry_err_code_t} error code.
@end deftypefun
@deftypefun {gcry_error_t} gcry_error_from_errno (@w{int @var{err}})
The function @code{gcry_error_from_errno} is like @code{gcry_error},
but it takes a system error like @code{errno} instead of a
@code{gcry_err_code_t} error code.
@end deftypefun
Sometimes you might want to map system error numbers to error codes
directly, or map an error code representing a system error back to the
system error number. The following functions can be used to do that.
@deftypefun {gcry_err_code_t} gcry_err_code_from_errno (@w{int @var{err}})
The function @code{gcry_err_code_from_errno} returns the error code
for the system error @var{err}. If @var{err} is not a known system
error, the function returns @code{GPG_ERR_UNKNOWN_ERRNO}.
@end deftypefun
@deftypefun {int} gcry_err_code_to_errno (@w{gcry_err_code_t @var{err}})
The function @code{gcry_err_code_to_errno} returns the system error
for the error code @var{err}. If @var{err} is not an error code
representing a system error, or if this system error is not defined on
this system, the function returns @code{0}.
@end deftypefun
@node Error Sources
@subsection Error Sources
@cindex error codes, list of
The library @code{libgpg-error} defines an error source for every
component of the GnuPG system. The error source part of an error
value is not well defined. As such it is mainly useful to improve the
diagnostic error message for the user.
If the error code part of an error value is @code{0}, the whole error
value will be @code{0}. In this case the error source part is of
course @code{GPG_ERR_SOURCE_UNKNOWN}.
The list of error sources that might occur in applications using
@acronym{Libgcrypt} is:
@table @code
@item GPG_ERR_SOURCE_UNKNOWN
The error source is not known. The value of this error source is
@code{0}.
@item GPG_ERR_SOURCE_GPGME
The error source is @acronym{GPGME} itself.
@item GPG_ERR_SOURCE_GPG
The error source is GnuPG, which is the crypto engine used for the
OpenPGP protocol.
@item GPG_ERR_SOURCE_GPGSM
The error source is GPGSM, which is the crypto engine used for the
OpenPGP protocol.
@item GPG_ERR_SOURCE_GCRYPT
The error source is @code{libgcrypt}, which is used by crypto engines
to perform cryptographic operations.
@item GPG_ERR_SOURCE_GPGAGENT
The error source is @command{gpg-agent}, which is used by crypto
engines to perform operations with the secret key.
@item GPG_ERR_SOURCE_PINENTRY
The error source is @command{pinentry}, which is used by
@command{gpg-agent} to query the passphrase to unlock a secret key.
@item GPG_ERR_SOURCE_SCD
The error source is the SmartCard Daemon, which is used by
@command{gpg-agent} to delegate operations with the secret key to a
SmartCard.
@item GPG_ERR_SOURCE_KEYBOX
The error source is @code{libkbx}, a library used by the crypto
engines to manage local keyrings.
@item GPG_ERR_SOURCE_USER_1
@item GPG_ERR_SOURCE_USER_2
@item GPG_ERR_SOURCE_USER_3
@item GPG_ERR_SOURCE_USER_4
These error sources are not used by any GnuPG component and can be
used by other software. For example, applications using
Libgcrypt can use them to mark error values coming from callback
handlers. Thus @code{GPG_ERR_SOURCE_USER_1} is the default for errors
created with @code{gcry_error} and @code{gcry_error_from_errno},
unless you define @code{GCRY_ERR_SOURCE_DEFAULT} before including
@file{gcrypt.h}.
@end table
@node Error Codes
@subsection Error Codes
@cindex error codes, list of
The library @code{libgpg-error} defines many error values. The
following list includes the most important error codes.
@table @code
@item GPG_ERR_EOF
This value indicates the end of a list, buffer or file.
@item GPG_ERR_NO_ERROR
This value indicates success. The value of this error code is
@code{0}. Also, it is guaranteed that an error value made from the
error code @code{0} will be @code{0} itself (as a whole). This means
that the error source information is lost for this error code,
however, as this error code indicates that no error occurred, this is
generally not a problem.
@item GPG_ERR_GENERAL
This value means that something went wrong, but either there is not
enough information about the problem to return a more useful error
value, or there is no separate error value for this type of problem.
@item GPG_ERR_ENOMEM
This value means that an out-of-memory condition occurred.
@item GPG_ERR_E...
System errors are mapped to GPG_ERR_EFOO where FOO is the symbol for
the system error.
@item GPG_ERR_INV_VALUE
This value means that some user provided data was out of range.
@item GPG_ERR_UNUSABLE_PUBKEY
This value means that some recipients for a message were invalid.
@item GPG_ERR_UNUSABLE_SECKEY
This value means that some signers were invalid.
@item GPG_ERR_NO_DATA
This value means that data was expected where no data was found.
@item GPG_ERR_CONFLICT
This value means that a conflict of some sort occurred.
@item GPG_ERR_NOT_IMPLEMENTED
This value indicates that the specific function (or operation) is not
implemented. This error should never happen. It can only occur if
you use certain values or configuration options which do not work,
but for which we think that they should work at some later time.
@item GPG_ERR_DECRYPT_FAILED
This value indicates that a decryption operation was unsuccessful.
@item GPG_ERR_WRONG_KEY_USAGE
This value indicates that a key is not used appropriately.
@item GPG_ERR_NO_SECKEY
This value indicates that no secret key for the user ID is available.
@item GPG_ERR_UNSUPPORTED_ALGORITHM
This value means a verification failed because the cryptographic
algorithm is not supported by the crypto backend.
@item GPG_ERR_BAD_SIGNATURE
This value means a verification failed because the signature is bad.
@item GPG_ERR_NO_PUBKEY
This value means a verification failed because the public key is not
available.
@item GPG_ERR_NOT_OPERATIONAL
This value means that the library is not yet in state which allows to
use this function. This error code is in particular returned if
Libgcrypt is operated in FIPS mode and the internal state of the
library does not yet or not anymore allow the use of a service.
This error code is only available with newer libgpg-error versions, thus
you might see ``invalid error code'' when passing this to
@code{gpg_strerror}. The numeric value of this error code is 176.
@item GPG_ERR_USER_1
@item GPG_ERR_USER_2
@item ...
@item GPG_ERR_USER_16
These error codes are not used by any GnuPG component and can be
freely used by other software. Applications using Libgcrypt
might use them to mark specific errors returned by callback handlers
if no suitable error codes (including the system errors) for these
errors exist already.
@end table
@node Error Strings
@subsection Error Strings
@cindex error values, printing of
@cindex error codes, printing of
@cindex error sources, printing of
@cindex error strings
@deftypefun {const char *} gcry_strerror (@w{gcry_error_t @var{err}})
The function @code{gcry_strerror} returns a pointer to a statically
allocated string containing a description of the error code contained
in the error value @var{err}. This string can be used to output a
diagnostic message to the user.
@end deftypefun
@deftypefun {const char *} gcry_strsource (@w{gcry_error_t @var{err}})
The function @code{gcry_strerror} returns a pointer to a statically
allocated string containing a description of the error source
contained in the error value @var{err}. This string can be used to
output a diagnostic message to the user.
@end deftypefun
The following example illustrates the use of the functions described
above:
@example
@{
gcry_cipher_hd_t handle;
gcry_error_t err = 0;
err = gcry_cipher_open (&handle, GCRY_CIPHER_AES,
GCRY_CIPHER_MODE_CBC, 0);
if (err)
@{
fprintf (stderr, "Failure: %s/%s\n",
gcry_strsource (err),
gcry_strerror (err));
@}
@}
@end example
@c **********************************************************
@c ******************* General ****************************
@c **********************************************************
@node Handler Functions
@chapter Handler Functions
Libgcrypt makes it possible to install so called `handler functions',
which get called by Libgcrypt in case of certain events.
@menu
* Progress handler:: Using a progress handler function.
* Allocation handler:: Using special memory allocation functions.
* Error handler:: Using error handler functions.
* Logging handler:: Using a special logging function.
@end menu
@node Progress handler
@section Progress handler
It is often useful to retrieve some feedback while long running
operations are performed.
@deftp {Data type} gcry_handler_progress_t
Progress handler functions have to be of the type
@code{gcry_handler_progress_t}, which is defined as:
@code{void (*gcry_handler_progress_t) (void *, const char *, int, int, int)}
@end deftp
The following function may be used to register a handler function for
this purpose.
@deftypefun void gcry_set_progress_handler (gcry_handler_progress_t @var{cb}, void *@var{cb_data})
This function installs @var{cb} as the `Progress handler' function.
@var{cb} must be defined as follows:
@example
void
my_progress_handler (void *@var{cb_data}, const char *@var{what},
int @var{printchar}, int @var{current}, int @var{total})
@{
/* Do something. */
@}
@end example
A description of the arguments of the progress handler function follows.
@table @var
@item cb_data
The argument provided in the call to @code{gcry_set_progress_handler}.
@item what
A string identifying the type of the progress output. The following
values for @var{what} are defined:
@table @code
@item need_entropy
Not enough entropy is available. @var{total} holds the number of
required bytes.
@item primegen
Values for @var{printchar}:
@table @code
@item \n
Prime generated.
@item !
Need to refresh the pool of prime numbers.
@item <, >
Number of bits adjusted.
@item ^
Searching for a generator.
@item .
Fermat test on 10 candidates failed.
@item :
Restart with a new random value.
@item +
Rabin Miller test passed.
@end table
@end table
@end table
@end deftypefun
@node Allocation handler
@section Allocation handler
It is possible to make Libgcrypt use special memory
allocation functions instead of the built-in ones.
Memory allocation functions are of the following types:
@deftp {Data type} gcry_handler_alloc_t
This type is defined as: @code{void *(*gcry_handler_alloc_t) (size_t n)}.
@end deftp
@deftp {Data type} gcry_handler_secure_check_t
This type is defined as: @code{int *(*gcry_handler_secure_check_t) (const void *)}.
@end deftp
@deftp {Data type} gcry_handler_realloc_t
This type is defined as: @code{void *(*gcry_handler_realloc_t) (void *p, size_t n)}.
@end deftp
@deftp {Data type} gcry_handler_free_t
This type is defined as: @code{void *(*gcry_handler_free_t) (void *)}.
@end deftp
Special memory allocation functions can be installed with the
following function:
@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})
Install the provided functions and use them instead of the built-in
functions for doing memory allocation.
@end deftypefun
@node Error handler
@section Error handler
The following functions may be used to register handler functions that
are called by Libgcrypt in case certain error conditions occur. They
may and should be registered prior to calling @code{gcry_check_version}.
@deftp {Data type} gcry_handler_no_mem_t
This type is defined as: @code{void (*gcry_handler_no_mem_t) (void *, size_t, unsigned int)}
@end deftp
@deftypefun void gcry_set_outofcore_handler (gcry_handler_no_mem_t @var{func_no_mem}, void *@var{cb_data})
This function registers @var{func_no_mem} as `out-of-core handler',
which means that it will be called in the case of not having enough
memory available.
@end deftypefun
@deftp {Data type} gcry_handler_error_t
This type is defined as: @code{void (*gcry_handler_error_t) (void *, int, const char *)}
@end deftp
@deftypefun void gcry_set_fatalerror_handler (gcry_handler_error_t @var{func_error}, void *@var{cb_data})
This function registers @var{func_error} as `error handler',
which means that it will be called in error conditions.
@end deftypefun
@node Logging handler
@section Logging handler
@deftp {Data type} gcry_handler_log_t
This type is defined as: @code{void (*gcry_handler_log_t) (void *, int, const char *, va_list)}
@end deftp
@deftypefun void gcry_set_log_handler (gcry_handler_log_t @var{func_log}, void *@var{cb_data})
This function registers @var{func_log} as `logging handler', which means
that it will be called in case Libgcrypt wants to log a message. This
function may and should be used prior to calling
@code{gcry_check_version}.
@end deftypefun
@c **********************************************************
@c ******************* Ciphers ****************************
@c **********************************************************
@c @include cipher-ref.texi
@node Symmetric cryptography
@chapter Symmetric cryptography
The cipher functions are used for symmetrical cryptography,
i.e. cryptography using a shared key. The programming model follows
an open/process/close paradigm and is in that similar to other
building blocks provided by Libgcrypt.
@menu
* Available ciphers:: List of ciphers supported by the library.
* Cipher modules:: How to work with cipher modules.
* Available cipher modes:: List of cipher modes supported by the library.
* Working with cipher handles:: How to perform operations related to cipher handles.
* General cipher functions:: General cipher functions independent of cipher handles.
@end menu
@node Available ciphers
@section Available ciphers
@table @code
@item GCRY_CIPHER_NONE
This is not a real algorithm but used by some functions as error return.
The value always evaluates to false.
@item GCRY_CIPHER_IDEA
@cindex IDEA
This is the IDEA algorithm. The constant is provided but there is
currently no implementation for it because the algorithm is patented.
@item GCRY_CIPHER_3DES
@cindex 3DES
@cindex Triple-DES
@cindex DES-EDE
@cindex Digital Encryption Standard
Triple-DES with 3 Keys as EDE. The key size of this algorithm is 168 but
you have to pass 192 bits because the most significant bits of each byte
are ignored.
@item GCRY_CIPHER_CAST5
@cindex CAST5
CAST128-5 block cipher algorithm. The key size is 128 bits.
@item GCRY_CIPHER_BLOWFISH
@cindex Blowfish
The blowfish algorithm. The current implementation allows only for a key
size of 128 bits.
@item GCRY_CIPHER_SAFER_SK128
Reserved and not currently implemented.
@item GCRY_CIPHER_DES_SK
Reserved and not currently implemented.
@item GCRY_CIPHER_AES
@itemx GCRY_CIPHER_AES128
@itemx GCRY_CIPHER_RIJNDAEL
@itemx GCRY_CIPHER_RIJNDAEL128
@cindex Rijndael
@cindex AES
@cindex Advanced Encryption Standard
AES (Rijndael) with a 128 bit key.
@item GCRY_CIPHER_AES192
@itemx GCRY_CIPHER_RIJNDAEL192
AES (Rijndael) with a 192 bit key.
@item GCRY_CIPHER_AES256
@itemx GCRY_CIPHER_RIJNDAEL256
AES (Rijndael) with a 256 bit key.
@item GCRY_CIPHER_TWOFISH
@cindex Twofish
The Twofish algorithm with a 256 bit key.
@item GCRY_CIPHER_TWOFISH128
The Twofish algorithm with a 128 bit key.
@item GCRY_CIPHER_ARCFOUR
@cindex Arcfour
@cindex RC4
An algorithm which is 100% compatible with RSA Inc.'s RC4 algorithm.
Note that this is a stream cipher and must be used very carefully to
avoid a couple of weaknesses.
@item GCRY_CIPHER_DES
@cindex DES
Standard DES with a 56 bit key. You need to pass 64 bit but the high
bits of each byte are ignored. Note, that this is a weak algorithm
which can be broken in reasonable time using a brute force approach.
@item GCRY_CIPHER_SERPENT128
@itemx GCRY_CIPHER_SERPENT192
@itemx GCRY_CIPHER_SERPENT256
@cindex Serpent
The Serpent cipher from the AES contest.
@item GCRY_CIPHER_RFC2268_40
@itemx GCRY_CIPHER_RFC2268_128
@cindex rfc-2268
@cindex RC2
Ron's Cipher 2 in the 40 and 128 bit variants. Note, that we currently
only support the 40 bit variant. The identifier for 128 is reserved for
future use.
@item GCRY_CIPHER_SEED
@cindex Seed (cipher)
A 128 bit cipher as described by RFC4269.
@item GCRY_CIPHER_CAMELLIA128
@itemx GCRY_CIPHER_CAMELLIA192
@itemx GCRY_CIPHER_CAMELLIA256
@cindex Camellia
The Camellia cipher by NTT. See
@uref{http://info.isl.ntt.co.jp/@/crypt/@/eng/@/camellia/@/specifications.html}.
@end table
@node Cipher modules
@section Cipher modules
Libgcrypt makes it possible to load additional `cipher modules'; these
ciphers can be used just like the cipher algorithms that are built
into the library directly. For an introduction into extension
modules, see @xref{Modules}.
@deftp {Data type} gcry_cipher_spec_t
This is the `module specification structure' needed for registering
cipher modules, which has to be filled in by the user before it can be
used to register a module. It contains the following members:
@table @code
@item const char *name
The primary name of the algorithm.
@item const char **aliases
A list of strings that are `aliases' for the algorithm. The list must
be terminated with a NULL element.
@item gcry_cipher_oid_spec_t *oids
A list of OIDs that are to be associated with the algorithm. The
list's last element must have it's `oid' member set to NULL. See
below for an explanation of this type.
@item size_t blocksize
The block size of the algorithm, in bytes.
@item size_t keylen
The length of the key, in bits.
@item size_t contextsize
The size of the algorithm-specific `context', that should be allocated
for each handle.
@item gcry_cipher_setkey_t setkey
The function responsible for initializing a handle with a provided
key. See below for a description of this type.
@item gcry_cipher_encrypt_t encrypt
The function responsible for encrypting a single block. See below for
a description of this type.
@item gcry_cipher_decrypt_t decrypt
The function responsible for decrypting a single block. See below for
a description of this type.
@item gcry_cipher_stencrypt_t stencrypt
Like `encrypt', for stream ciphers. See below for a description of
this type.
@item gcry_cipher_stdecrypt_t stdecrypt
Like `decrypt', for stream ciphers. See below for a description of
this type.
@end table
@end deftp
@deftp {Data type} gcry_cipher_oid_spec_t
This type is used for associating a user-provided algorithm
implementation with certain OIDs. It contains the following members:
@table @code
@item const char *oid
Textual representation of the OID.
@item int mode
Cipher mode for which this OID is valid.
@end table
@end deftp
@deftp {Data type} gcry_cipher_setkey_t
Type for the `setkey' function, defined as: gcry_err_code_t
(*gcry_cipher_setkey_t) (void *c, const unsigned char *key, unsigned
keylen)
@end deftp
@deftp {Data type} gcry_cipher_encrypt_t
Type for the `encrypt' function, defined as: gcry_err_code_t
(*gcry_cipher_encrypt_t) (void *c, const unsigned char *outbuf, const
unsigned char *inbuf)
@end deftp
@deftp {Data type} gcry_cipher_decrypt_t
Type for the `decrypt' function, defined as: gcry_err_code_t
(*gcry_cipher_decrypt_t) (void *c, const unsigned char *outbuf, const
unsigned char *inbuf)
@end deftp
@deftp {Data type} gcry_cipher_stencrypt_t
Type for the `stencrypt' function, defined as: gcry_err_code_t
(*gcry_@/cipher_@/stencrypt_@/t) (void *c, const unsigned char *outbuf, const
unsigned char *, unsigned int n)
@end deftp
@deftp {Data type} gcry_cipher_stdecrypt_t
Type for the `stdecrypt' function, defined as: gcry_err_code_t
(*gcry_@/cipher_@/stdecrypt_@/t) (void *c, const unsigned char *outbuf, const
unsigned char *, unsigned int n)
@end deftp
@deftypefun gcry_error_t gcry_cipher_register (gcry_cipher_spec_t *@var{cipher}, unsigned int *algorithm_id, gcry_module_t *@var{module})
Register a new cipher module whose specification can be found in
@var{cipher}. On success, a new algorithm ID is stored in
@var{algorithm_id} and a pointer representing this module is stored
in @var{module}.
@end deftypefun
@deftypefun void gcry_cipher_unregister (gcry_module_t @var{module})
Unregister the cipher identified by @var{module}, which must have been
registered with gcry_cipher_register.
@end deftypefun
@deftypefun gcry_error_t gcry_cipher_list (int *@var{list}, int *@var{list_length})
Get a list consisting of the IDs of the loaded cipher modules. If
@var{list} is zero, write the number of loaded cipher modules to
@var{list_length} and return. If @var{list} is non-zero, the first
*@var{list_length} algorithm IDs are stored in @var{list}, which must
be of according size. In case there are less cipher modules than
*@var{list_length}, *@var{list_length} is updated to the correct
number.
@end deftypefun
@node Available cipher modes
@section Available cipher modes
@table @code
@item GCRY_CIPHER_MODE_NONE
No mode specified. This should not be used. The only exception is that
if Libgcrypt is not used in FIPS mode and if any debug flag has been
set, this mode may be used to bypass the actual encryption.
@item GCRY_CIPHER_MODE_ECB
@cindex ECB, Electronic Codebook mode
Electronic Codebook mode.
@item GCRY_CIPHER_MODE_CFB
@cindex CFB, Cipher Feedback mode
Cipher Feedback mode. The shift size equals the block size of the
cipher (e.g. for AES it is CFB-128).
@item GCRY_CIPHER_MODE_CBC
@cindex CBC, Cipher Block Chaining mode
Cipher Block Chaining mode.
@item GCRY_CIPHER_MODE_STREAM
Stream mode, only to be used with stream cipher algorithms.
@item GCRY_CIPHER_MODE_OFB
@cindex OFB, Output Feedback mode
Output Feedback mode.
@item GCRY_CIPHER_MODE_CTR
@cindex CTR, Counter mode
Counter mode.
@end table
@node Working with cipher handles
@section Working with cipher handles
To use a cipher algorithm, you must first allocate an according
handle. This is to be done using the open function:
@deftypefun gcry_error_t gcry_cipher_open (gcry_cipher_hd_t *@var{hd}, int @var{algo}, int @var{mode}, unsigned int @var{flags})
This function creates the context handle required for most of the
other cipher functions and returns a handle to it in `hd'. In case of
an error, an according error code is returned.
The ID of algorithm to use must be specified via @var{algo}. See
@xref{Available ciphers}, for a list of supported ciphers and the
according constants.
Besides using the constants directly, the function
@code{gcry_cipher_map_name} may be used to convert the textual name of
an algorithm into the according numeric ID.
The cipher mode to use must be specified via @var{mode}. See
@xref{Available cipher modes}, for a list of supported cipher modes
and the according constants. Note that some modes are incompatible
with some algorithms - in particular, stream mode
(@code{GCRY_CIPHER_MODE_STREAM}) only works with stream ciphers. Any
block cipher mode (@code{GCRY_CIPHER_MODE_ECB},
@code{GCRY_CIPHER_MODE_CBC}, @code{GCRY_CIPHER_MODE_CFB},
@code{GCRY_CIPHER_MODE_OFB} or @code{GCRY_CIPHER_MODE_CTR}) will work
with any block cipher algorithm.
The third argument @var{flags} can either be passed as @code{0} or as
the bit-wise OR of the following constants.
@table @code
@item GCRY_CIPHER_SECURE
Make sure that all operations are allocated in secure memory. This is
useful when the key material is highly confidential.
@item GCRY_CIPHER_ENABLE_SYNC
@cindex sync mode (OpenPGP)
This flag enables the CFB sync mode, which is a special feature of
Libgcrypt's CFB mode implementation to allow for OpenPGP's CFB variant.
See @code{gcry_cipher_sync}.
@item GCRY_CIPHER_CBC_CTS
@cindex cipher text stealing
Enable cipher text stealing (CTS) for the CBC mode. Cannot be used
simultaneous as GCRY_CIPHER_CBC_MAC. CTS mode makes it possible to
transform data of almost arbitrary size (only limitation is that it
must be greater than the algorithm's block size).
@item GCRY_CIPHER_CBC_MAC
@cindex CBC-MAC
Compute CBC-MAC keyed checksums. This is the same as CBC mode, but
only output the last block. Cannot be used simultaneous as
GCRY_CIPHER_CBC_CTS.
@end table
@end deftypefun
Use the following function to release an existing handle:
@deftypefun void gcry_cipher_close (gcry_cipher_hd_t @var{h})
This function releases the context created by @code{gcry_cipher_open}.
@end deftypefun
In order to use a handle for performing cryptographic operations, a
`key' has to be set first:
@deftypefun gcry_error_t gcry_cipher_setkey (gcry_cipher_hd_t @var{h}, const void *@var{k}, size_t @var{l})
Set the key @var{k} used for encryption or decryption in the context
denoted by the handle @var{h}. The length @var{l} of the key @var{k}
must match the required length of the algorithm set for this context or
be in the allowed range for algorithms with variable key size. The
function checks this and returns an error if there is a problem. A
caller should always check for an error.
@end deftypefun
Most crypto modes requires an initialization vector (IV), which
usually is a non-secret random string acting as a kind of salt value.
The CTR mode requires a counter, which is also similar to a salt
value. To set the IV or CTR, use these functions:
@deftypefun gcry_error_t gcry_cipher_setiv (gcry_cipher_hd_t @var{h}, const void *@var{k}, size_t @var{l})
Set the initialization vector used for encryption or decryption. The
vector is passed as the buffer @var{K} of length @var{l} and copied to
internal data structures. The function checks that the IV matches the
requirement of the selected algorithm and mode.
@end deftypefun
@deftypefun gcry_error_t gcry_cipher_setctr (gcry_cipher_hd_t @var{h}, const void *@var{c}, size_t @var{l})
Set the counter vector used for encryption or decryption. The counter
is passed as the buffer @var{c} of length @var{l} and copied to
internal data structures. The function checks that the counter
matches the requirement of the selected algorithm (i.e., it must be
the same size as the block size).
@end deftypefun
@deftypefun gcry_error_t gcry_cipher_reset (gcry_cipher_hd_t @var{h})
Set the given handle's context back to the state it had after the last
call to gcry_cipher_setkey and clear the initialization vector.
Note that gcry_cipher_reset is implemented as a macro.
@end deftypefun
The actual encryption and decryption is done by using one of the
following functions. They may be used as often as required to process
all the data.
@deftypefun gcry_error_t gcry_cipher_encrypt (gcry_cipher_hd_t @var{h}, unsigned char *{out}, size_t @var{outsize}, const unsigned char *@var{in}, size_t @var{inlen})
@code{gcry_cipher_encrypt} is used to encrypt the data. This function
can either work in place or with two buffers. It uses the cipher
context already setup and described by the handle @var{h}. There are 2
ways to use the function: If @var{in} is passed as @code{NULL} and
@var{inlen} is @code{0}, in-place encryption of the data in @var{out} or
length @var{outsize} takes place. With @var{in} being not @code{NULL},
@var{inlen} bytes are encrypted to the buffer @var{out} which must have
at least a size of @var{inlen}. @var{outsize} must be set to the
allocated size of @var{out}, so that the function can check that there
is sufficient space. Note that overlapping buffers are not allowed.
Depending on the selected algorithms and encryption mode, the length of
the buffers must be a multiple of the block size.
The function returns @code{0} on success or an error code.
@end deftypefun
@deftypefun gcry_error_t gcry_cipher_decrypt (gcry_cipher_hd_t @var{h}, unsigned char *{out}, size_t @var{outsize}, const unsigned char *@var{in}, size_t @var{inlen})
@code{gcry_cipher_decrypt} is used to decrypt the data. This function
can either work in place or with two buffers. It uses the cipher
context already setup and described by the handle @var{h}. There are 2
ways to use the function: If @var{in} is passed as @code{NULL} and
@var{inlen} is @code{0}, in-place decryption of the data in @var{out} or
length @var{outsize} takes place. With @var{in} being not @code{NULL},
@var{inlen} bytes are decrypted to the buffer @var{out} which must have
at least a size of @var{inlen}. @var{outsize} must be set to the
allocated size of @var{out}, so that the function can check that there
is sufficient space. Note that overlapping buffers are not allowed.
Depending on the selected algorithms and encryption mode, the length of
the buffers must be a multiple of the block size.
The function returns @code{0} on success or an error code.
@end deftypefun
OpenPGP (as defined in RFC-2440) requires a special sync operation in
some places. The following function is used for this:
@deftypefun gcry_error_t gcry_cipher_sync (gcry_cipher_hd_t @var{h})
Perform the OpenPGP sync operation on context @var{h}. Note that this
is a no-op unless the context was created with the flag
@code{GCRY_CIPHER_ENABLE_SYNC}
@end deftypefun
Some of the described functions are implemented as macros utilizing a
catch-all control function. This control function is rarely used
directly but there is nothing which would inhibit it:
@deftypefun gcry_error_t gcry_cipher_ctl (gcry_cipher_hd_t @var{h}, int @var{cmd}, void *@var{buffer}, size_t @var{buflen})
@code{gcry_cipher_ctl} controls various aspects of the cipher module and
specific cipher contexts. Usually some more specialized functions or
macros are used for this purpose. The semantics of the function and its
parameters depends on the the command @var{cmd} and the passed context
handle @var{h}. Please see the comments in the source code
(@code{src/global.c}) for details.
@end deftypefun
@deftypefun gcry_error_t gcry_cipher_info (gcry_cipher_hd_t @var{h}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes})
@code{gcry_cipher_info} is used to retrieve various
information about a cipher context or the cipher module in general.
Currently no information is available.
@end deftypefun
@node General cipher functions
@section General cipher functions
To work with the algorithms, several functions are available to map
algorithm names to the internal identifiers, as well as ways to
retrieve information about an algorithm or the current cipher context.
@deftypefun gcry_error_t gcry_cipher_algo_info (int @var{algo}, int @var{what}, void *@var{buffer}, size_t *@var{nbytes})
This function is used to retrieve information on a specific algorithm.
You pass the cipher algorithm ID as @var{algo} and the type of
information requested as @var{what}. The result is either returned as
the return code of the function or copied to the provided @var{buffer}
whose allocated length must be available in an integer variable with the
address passed in @var{nbytes}. This variable will also receive the
actual used length of the buffer.
Here is a list of supported codes for @var{what}:
@c begin constants for gcry_cipher_algo_info
@table @code
@item GCRYCTL_GET_KEYLEN:
Return the length of the key. If the algorithm supports multiple key
lengths, the maximum supported value is returned. The length is
returned as number of octets (bytes) and not as number of bits in
@var{nbytes}; @var{buffer} must be zero.
@item GCRYCTL_GET_BLKLEN:
Return the block length of the algorithm. The length is returned as a
number of octets in @var{nbytes}; @var{buffer} must be zero.
@item GCRYCTL_TEST_ALGO:
Returns @code{0} when the specified algorithm is available for use.
@var{buffer} and @var{nbytes} must be zero.
@end table
@c end constants for gcry_cipher_algo_info
@end deftypefun
@c end gcry_cipher_algo_info
@deftypefun {const char *} gcry_cipher_algo_name (int @var{algo})
@code{gcry_cipher_algo_name} returns a string with the name of the
cipher algorithm @var{algo}. If the algorithm is not known or another
error occurred, the string @code{"?"} is returned. This function should
not be used to test for the availability of an algorithm.
@end deftypefun
@deftypefun int gcry_cipher_map_name (const char *@var{name})
@code{gcry_cipher_map_name} returns the algorithm identifier for the
cipher algorithm described by the string @var{name}. If this algorithm
is not available @code{0} is returned.
@end deftypefun
@deftypefun int gcry_cipher_mode_from_oid (const char *@var{string})
Return the cipher mode associated with an @acronym{ASN.1} object
identifier. The object identifier is expected to be in the
@acronym{IETF}-style dotted decimal notation. The function returns
@code{0} for an unknown object identifier or when no mode is associated
with it.
@end deftypefun
@c **********************************************************
@c ******************* Public Key *************************
@c **********************************************************
@node Public Key cryptography
@chapter Public Key cryptography
Public key cryptography, also known as asymmetric cryptography, is an
easy way for key management and to provide digital signatures.
Libgcrypt provides two completely different interfaces to
public key cryptography, this chapter explains the one based on
S-expressions.
@menu
* Available algorithms:: Algorithms supported by the library.
* Used S-expressions:: Introduction into the used S-expression.
* Public key modules:: How to work with public key modules.
* Cryptographic Functions:: Functions for performing the cryptographic actions.
* General public-key related Functions:: General functions, not implementing any cryptography.
* AC Interface:: Alternative interface to public key functions.
@end menu
@node Available algorithms
@section Available algorithms
Libgcrypt supports the RSA (Rivest-Shamir-Adleman) algorithms as well
as DSA (Digital Signature Algorithm) and Elgamal. The versatile
interface allows to add more algorithms in the future.
@node Used S-expressions
@section Used S-expressions
Libgcrypt's API for asymmetric cryptography is based on data structures
called S-expressions (see
@uref{http://people.csail.mit.edu/@/rivest/@/sexp.html}) and does not work
with contexts as most of the other building blocks of Libgcrypt do.
@noindent
The following information are stored in S-expressions:
@itemize @asis
@item keys
@item plain text data
@item encrypted data
@item signatures
@end itemize
@noindent
To describe how Libgcrypt expect keys, we use examples. Note that
words in
@ifnottex
uppercase
@end ifnottex
@iftex
italics
@end iftex
indicate parameters whereas lowercase words are literals.
Note that all MPI (multi-precision-integers) values are expected to be in
@code{GCRYMPI_FMT_USG} format. An easy way to create S-expressions is
by using @code{gcry_sexp_build} which allows to pass a string with
printf-like escapes to insert MPI values.
@menu
* RSA key parameters:: Parameters used with an RSA key.
* DSA key parameters:: Parameters used with a DSA key.
* ECC key parameters:: Parameters used with ECC keys.
@end menu
@node RSA key parameters
@subsection RSA key parameters
@noindent
An RSA private key is described by this S-expression:
@example
(private-key
(rsa
(n @var{n-mpi})
(e @var{e-mpi})
(d @var{d-mpi})
(p @var{p-mpi})
(q @var{q-mpi})
(u @var{u-mpi})))
@end example
@noindent
An RSA public key is described by this S-expression:
@example
(public-key
(rsa
(n @var{n-mpi})
(e @var{e-mpi})))
@end example
@table @var
@item n-mpi
RSA public modulus @math{n}.
@item e-mpi
RSA public exponent @math{e}.
@item d-mpi
RSA secret exponent @math{d = e^{-1} \bmod (p-1)(q-1)}.
@item p-mpi
RSA secret prime @math{p}.
@item q-mpi
RSA secret prime @math{q} with @math{p < q}.
@item u-mpi
Multiplicative inverse @math{u = p^{-1} \bmod q}.
@end table
For signing and decryption the parameters @math{(p, q, u)} are optional
but greatly improve the performance. Either all of these optional
parameters must be given or none of them. They are mandatory for
gcry_pk_testkey.
Note that OpenSSL uses slighly different parameters: @math{q < p} and
@math{u = q^{-1} \bmod p}. To use these parameters you will need to
swap the values and recompute @math{u}. Here is example code to do this:
@example
if (gcry_mpi_cmp (p, q) > 0)
@{
gcry_mpi_swap (p, q);
gcry_mpi_invm (u, p, q);
@}
@end example
@node DSA key parameters
@subsection DSA key parameters
@noindent
A DSA private key is described by this S-expression:
@example
(private-key
(dsa
(p @var{p-mpi})
(q @var{q-mpi})
(g @var{g-mpi})
(y @var{y-mpi})
(x @var{x-mpi})))
@end example
@table @var
@item p-mpi
DSA prime @math{p}.
@item q-mpi
DSA group order @math{q} (which is a prime divisor of @math{p-1}).
@item g-mpi
DSA group generator @math{g}.
@item y-mpi
DSA public key value @math{y = g^x \bmod p}.
@item x-mpi
DSA secret exponent x.
@end table
The public key is similar with "private-key" replaced by "public-key"
and no @var{x-mpi}.
@node ECC key parameters
@subsection ECC key parameters
@noindent
An ECC private key is described by this S-expression:
@example
(private-key
(ecc
(p @var{p-mpi})
(a @var{a-mpi})
(b @var{b-mpi})
(g @var{g-point})
(n @var{n-mpi})
(q @var{q-point})
(d @var{d-mpi})))
@end example
@table @var
@item p-mpi
Prime specifying the field @math{GF(p)}.
@item a-mpi
@itemx b-mpi
The two coefficients of the Weierstrass equation @math{y^2 = x^3 + ax + b}
@item g-point
Base point @math{g}.
@item n-mpi
Order of @math{g}
@item q-point
The point representing the public key @math{Q = dP}.
@item d-mpi
The private key @math{d}
@end table
All point values are encoded in standard format; Libgcrypt does
currently only support uncompressed points, thus the first byte needs to
be @code{0x04}.
The public key is similar with "private-key" replaced by "public-key"
and no @var{d-mpi}.
If the domain parameters are well-known, the name of this curve may be
used. For example
@example
(private-key
(ecc
(curve "NIST P-192")
(q @var{q-point})
(d @var{d-mpi})))
@end example
The @code{curve} parameter may be given in any case and is used to replace
missing parameters.
@noindent
Currently implemented curves are:
@table @code
@item NIST P-192
@itemx 1.2.840.10045.3.1.1
@itemx prime192v1
@itemx secp192r1
The NIST 192 bit curve, its OID, X9.62 and SECP aliases.
@item NIST P-224
@itemx secp224r1
The NIST 224 bit curve and its SECP alias.
@item NIST P-256
@itemx 1.2.840.10045.3.1.7
@itemx prime256v1
@itemx secp256r1
The NIST 256 bit curve, its OID, X9.62 and SECP aliases.
@item NIST P-384
@itemx secp384r1
The NIST 384 bit curve and its SECP alias.
@item NIST P-521
@itemx secp521r1
The NIST 521 bit curve and its SECP alias.
@end table
As usual the OIDs may optionally be prefixed with the string @code{OID.}
or @code{oid.}.
@node Public key modules
@section Public key modules
Libgcrypt makes it possible to load additional `public key
modules'; these public key algorithms can be used just like the
algorithms that are built into the library directly. For an
introduction into extension modules, see @xref{Modules}.
@deftp {Data type} gcry_pk_spec_t
This is the `module specification structure' needed for registering
public key modules, which has to be filled in by the user before it
can be used to register a module. It contains the following members:
@table @code
@item const char *name
The primary name of this algorithm.
@item char **aliases
A list of strings that are `aliases' for the algorithm. The list
must be terminated with a NULL element.
@item const char *elements_pkey
String containing the one-letter names of the MPI values contained in
a public key.
@item const char *element_skey
String containing the one-letter names of the MPI values contained in
a secret key.
@item const char *elements_enc
String containing the one-letter names of the MPI values that are the
result of an encryption operation using this algorithm.
@item const char *elements_sig
String containing the one-letter names of the MPI values that are the
result of a sign operation using this algorithm.
@item const char *elements_grip
String containing the one-letter names of the MPI values that are to
be included in the `key grip'.
@item int use
The bitwise-OR of the following flags, depending on the abilities of
the algorithm:
@table @code
@item GCRY_PK_USAGE_SIGN
The algorithm supports signing and verifying of data.
@item GCRY_PK_USAGE_ENCR
The algorithm supports the encryption and decryption of data.
@end table
@item gcry_pk_generate_t generate
The function responsible for generating a new key pair. See below for
a description of this type.
@item gcry_pk_check_secret_key_t check_secret_key
The function responsible for checking the sanity of a provided secret
key. See below for a description of this type.
@item gcry_pk_encrypt_t encrypt
The function responsible for encrypting data. See below for a
description of this type.
@item gcry_pk_decrypt_t decrypt
The function responsible for decrypting data. See below for a
description of this type.
@item gcry_pk_sign_t sign
The function responsible for signing data. See below for a description
of this type.
@item gcry_pk_verify_t verify
The function responsible for verifying that the provided signature
matches the provided data. See below for a description of this type.
@item gcry_pk_get_nbits_t get_nbits
The function responsible for returning the number of bits of a provided
key. See below for a description of this type.
@end table
@end deftp
@deftp {Data type} gcry_pk_generate_t
Type for the `generate' function, defined as: gcry_err_code_t
(*gcry_pk_generate_t) (int algo, unsigned int nbits, unsigned long
use_e, gcry_mpi_t *skey, gcry_mpi_t **retfactors)
@end deftp
@deftp {Data type} gcry_pk_check_secret_key_t
Type for the `check_secret_key' function, defined as: gcry_err_code_t
(*gcry_pk_check_secret_key_t) (int algo, gcry_mpi_t *skey)
@end deftp
@deftp {Data type} gcry_pk_encrypt_t
Type for the `encrypt' function, defined as: gcry_err_code_t
(*gcry_pk_encrypt_t) (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
gcry_mpi_t *pkey, int flags)
@end deftp
@deftp {Data type} gcry_pk_decrypt_t
Type for the `decrypt' function, defined as: gcry_err_code_t
(*gcry_pk_decrypt_t) (int algo, gcry_mpi_t *result, gcry_mpi_t *data,
gcry_mpi_t *skey, int flags)
@end deftp
@deftp {Data type} gcry_pk_sign_t
Type for the `sign' function, defined as: gcry_err_code_t
(*gcry_pk_sign_t) (int algo, gcry_mpi_t *resarr, gcry_mpi_t data,
gcry_mpi_t *skey)
@end deftp
@deftp {Data type} gcry_pk_verify_t
Type for the `verify' function, defined as: gcry_err_code_t
(*gcry_pk_verify_t) (int algo, gcry_mpi_t hash, gcry_mpi_t *data,
gcry_mpi_t *pkey, int (*cmp) (void *, gcry_mpi_t), void *opaquev)
@end deftp
@deftp {Data type} gcry_pk_get_nbits_t
Type for the `get_nbits' function, defined as: unsigned
(*gcry_pk_get_nbits_t) (int algo, gcry_mpi_t *pkey)
@end deftp
@deftypefun gcry_error_t gcry_pk_register (gcry_pk_spec_t *@var{pubkey}, unsigned int *algorithm_id, gcry_module_t *@var{module})
Register a new public key module whose specification can be found in
@var{pubkey}. On success, a new algorithm ID is stored in
@var{algorithm_id} and a pointer representing this module is stored
in @var{module}.
@end deftypefun
@deftypefun void gcry_pk_unregister (gcry_module_t @var{module})
Unregister the public key module identified by @var{module}, which
must have been registered with gcry_pk_register.
@end deftypefun
@deftypefun gcry_error_t gcry_pk_list (int *@var{list}, int *@var{list_length})
Get a list consisting of the IDs of the loaded pubkey modules. If
@var{list} is zero, write the number of loaded pubkey modules to
@var{list_length} and return. If @var{list} is non-zero, the first
*@var{list_length} algorithm IDs are stored in @var{list}, which must
be of according size. In case there are less pubkey modules than
*@var{list_length}, *@var{list_length} is updated to the correct
number.
@end deftypefun
@node Cryptographic Functions
@section Cryptographic Functions
@noindent
Note that we will in future allow to use keys without p,q and u
specified and may also support other parameters for performance
reasons.
@noindent
Some functions operating on S-expressions support `flags', that
influence the operation. These flags have to be listed in a
sub-S-expression named `flags'; the following flags are known:
@table @code
@item pkcs1
Use PKCS#1 block type 2 padding.
@item no-blinding
Do not use a technique called `blinding', which is used by default in
order to prevent leaking of secret information. Blinding is only
implemented by RSA, but it might be implemented by other algorithms in
the future as well, when necessary.
@end table
@noindent
Now that we know the key basics, we can carry on and explain how to
encrypt and decrypt data. In almost all cases the data is a random
session key which is in turn used for the actual encryption of the real
data. There are 2 functions to do this:
@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}})
Obviously a public key must be provided for encryption. It is
expected as an appropriate S-expression (see above) in @var{pkey}.
The data to be encrypted can either be in the simple old format, which
is a very simple S-expression consisting only of one MPI, or it may be
a more complex S-expression which also allows to specify flags for
operation, like e.g. padding rules.
@noindent
If you don't want to let Libgcrypt handle the padding, you must pass an
appropriate MPI using this expression for @var{data}:
@example
(data
(flags raw)
(value @var{mpi}))
@end example
@noindent
This has the same semantics as the old style MPI only way. @var{MPI} is
the actual data, already padded appropriate for your protocol. Most
systems however use PKCS#1 padding and so you can use this S-expression
for @var{data}:
@example
(data
(flags pkcs1)
(value @var{block}))
@end example
@noindent
Here, the "flags" list has the "pkcs1" flag which let the function know
that it should provide PKCS#1 block type 2 padding. The actual data to
be encrypted is passed as a string of octets in @var{block}. The
function checks that this data actually can be used with the given key,
does the padding and encrypts it.
If the function could successfully perform the encryption, the return
value will be 0 and a new S-expression with the encrypted result is
allocated and assigned to the variable at the address of @var{r_ciph}.
The caller is responsible to release this value using
@code{gcry_sexp_release}. In case of an error, an error code is
returned and @var{r_ciph} will be set to @code{NULL}.
@noindent
The returned S-expression has this format when used with RSA:
@example
(enc-val
(rsa
(a @var{a-mpi})))
@end example
@noindent
Where @var{a-mpi} is an MPI with the result of the RSA operation. When
using the Elgamal algorithm, the return value will have this format:
@example
(enc-val
(elg
(a @var{a-mpi})
(b @var{b-mpi})))
@end example
@noindent
Where @var{a-mpi} and @var{b-mpi} are MPIs with the result of the
Elgamal encryption operation.
@end deftypefun
@c end gcry_pk_encrypt
@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}})
Obviously a private key must be provided for decryption. It is expected
as an appropriate S-expression (see above) in @var{skey}. The data to
be decrypted must match the format of the result as returned by
@code{gcry_pk_encrypt}, but should be enlarged with a @code{flags}
element:
@example
(enc-val
(flags)
(elg
(a @var{a-mpi})
(b @var{b-mpi})))
@end example
@noindent
Note that this function currently does not know of any padding
methods and the caller must do any un-padding on his own.
@noindent
The function returns 0 on success or an error code. The variable at the
address of @var{r_plain} will be set to NULL on error or receive the
decrypted value on success. The format of @var{r_plain} is a
simple S-expression part (i.e. not a valid one) with just one MPI if
there was no @code{flags} element in @var{data}; if at least an empty
@code{flags} is passed in @var{data}, the format is:
@example
(value @var{plaintext})
@end example
@end deftypefun
@c end gcry_pk_decrypt
Another operation commonly performed using public key cryptography is
signing data. In some sense this is even more important than
encryption because digital signatures are an important instrument for
key management. Libgcrypt supports digital signatures using
2 functions, similar to the encryption functions:
@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}})
This function creates a digital signature for @var{data} using the
private key @var{skey} and place it into the variable at the address of
@var{r_sig}. @var{data} may either be the simple old style S-expression
with just one MPI or a modern and more versatile S-expression which
allows to let Libgcrypt handle padding:
@example
(data
(flags pkcs1)
(hash @var{hash-algo} @var{block}))
@end example
@noindent
This example requests to sign the data in @var{block} after applying
PKCS#1 block type 1 style padding. @var{hash-algo} is a string with the
hash algorithm to be encoded into the signature, this may be any hash
algorithm name as supported by Libgcrypt. Most likely, this will be
"sha1", "rmd160" or "md5". It is obvious that the length of @var{block}
must match the size of that message digests; the function checks that
this and other constraints are valid.
@noindent
If PKCS#1 padding is not required (because the caller does already
provide a padded value), either the old format or better the following
format should be used:
@example
(data
(flags raw)
(value @var{mpi}))
@end example
@noindent
Here, the data to be signed is directly given as an @var{MPI}.
@noindent
The signature is returned as a newly allocated S-expression in
@var{r_sig} using this format for RSA:
@example
(sig-val
(rsa
(s @var{s-mpi})))
@end example
Where @var{s-mpi} is the result of the RSA sign operation. For DSA the
S-expression returned is:
@example
(sig-val
(dsa
(r @var{r-mpi})
(s @var{s-mpi})))
@end example
Where @var{r-mpi} and @var{s-mpi} are the result of the DSA sign
operation. For Elgamal signing (which is slow, yields large numbers
and probably is not as secure as the other algorithms), the same format is
used with "elg" replacing "dsa".
@end deftypefun
@c end gcry_pk_sign
@noindent
The operation most commonly used is definitely the verification of a
signature. Libgcrypt provides this function:
@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}})
This is used to check whether the signature @var{sig} matches the
@var{data}. The public key @var{pkey} must be provided to perform this
verification. This function is similar in its parameters to
@code{gcry_pk_sign} with the exceptions that the public key is used
instead of the private key and that no signature is created but a
signature, in a format as created by @code{gcry_pk_sign}, is passed to
the function in @var{sig}.
@noindent
The result is 0 for success (i.e. the data matches the signature), or an
error code where the most relevant code is @code{GCRYERR_BAD_SIGNATURE}
to indicate that the signature does not match the provided data.
@end deftypefun
@c end gcry_pk_verify
@node General public-key related Functions
@section General public-key related Functions
@noindent
A couple of utility functions are available to retrieve the length of
the key, map algorithm identifiers and perform sanity checks:
@deftypefun {const char *} gcry_pk_algo_name (int @var{algo})
Map the public key algorithm id @var{algo} to a string representation of
the algorithm name. For unknown algorithms this functions returns the
string @code{"?"}. This function should not be used to test for the
availability of an algorithm.
@end deftypefun
@deftypefun int gcry_pk_map_name (const char *@var{name})
Map the algorithm @var{name} to a public key algorithm Id. Returns 0 if
the algorithm name is not known.
@end deftypefun
@deftypefun int gcry_pk_test_algo (int @var{algo})
Return 0 if the public key algorithm @var{algo} is available for use.
Note that this is implemented as a macro.
@end deftypefun
@deftypefun {unsigned int} gcry_pk_get_nbits (gcry_sexp_t @var{key})
Return what is commonly referred as the key length for the given
public or private in @var{key}.
@end deftypefun
@deftypefun {unsigned char *} gcry_pk_get_keygrip (@w{gcry_sexp_t @var{key}}, @w{unsigned char *@var{array}})
Return the so called "keygrip" which is the SHA-1 hash of the public key
parameters expressed in a way depended on the algorithm. @var{array}
must either provide space for 20 bytes or be @code{NULL}. In the latter
case a newly allocated array of that size is returned. On success a
pointer to the newly allocated space or to @var{array} is returned.
@code{NULL} is returned to indicate an error which is most likely an
unknown algorithm or one where a "keygrip" has not yet been defined.
The function accepts public or secret keys in @var{key}.
@end deftypefun
@deftypefun gcry_error_t gcry_pk_testkey (gcry_sexp_t @var{key})
Return zero if the private key @var{key} is `sane', an error code otherwise.
Note that it is not possible to check the `saneness' of a public key.
@end deftypefun
@deftypefun gcry_error_t gcry_pk_algo_info (@w{int @var{algo}}, @w{int @var{what}}, @w{void *@var{buffer}}, @w{size_t *@var{nbytes}})
Depending on the value of @var{what} return various information about
the public key algorithm with the id @var{algo}. Note that the
function returns @code{-1} on error and the actual error code must be
retrieved using the function @code{gcry_errno}. The currently defined
values for @var{what} are:
@table @code
@item GCRYCTL_TEST_ALGO:
Return 0 if the specified algorithm is available for use.
@var{buffer} must be @code{NULL}, @var{nbytes} may be passed as
@code{NULL} or point to a variable with the required usage of the
algorithm. This may be 0 for "don't care" or the bit-wise OR of these
flags:
@table @code
@item GCRY_PK_USAGE_SIGN
Algorithm is usable for signing.
@item GCRY_PK_USAGE_ENCR
Algorithm is usable for encryption.
@end table
Unless you need to test for the allowed usage, it is in general better
to use the macro gcry_pk_test_algo instead.
@item GCRYCTL_GET_ALGO_USAGE:
Return the usage flags for the given algorithm. An invalid algorithm
return 0. Disabled algorithms are ignored here because we
want to know whether the algorithm is at all capable of a certain usage.
@item GCRYCTL_GET_ALGO_NPKEY
Return the number of elements the public key for algorithm @var{algo}
consist of. Return 0 for an unknown algorithm.
@item GCRYCTL_GET_ALGO_NSKEY
Return the number of elements the private key for algorithm @var{algo}
consist of. Note that this value is always larger than that of the
public key. Return 0 for an unknown algorithm.
@item GCRYCTL_GET_ALGO_NSIGN
Return the number of elements a signature created with the algorithm
@var{algo} consists of. Return 0 for an unknown algorithm or for an
algorithm not capable of creating signatures.
@item GCRYCTL_GET_ALGO_NENC
Return the number of elements a encrypted message created with the algorithm
@var{algo} consists of. Return 0 for an unknown algorithm or for an
algorithm not capable of encryption.
@end table
@noindent
Please note that parameters not required should be passed as @code{NULL}.
@end deftypefun
@c end gcry_pk_algo_info
@deftypefun gcry_error_t gcry_pk_ctl (@w{int @var{cmd}}, @w{void *@var{buffer}}, @w{size_t @var{buflen}})
This is a general purpose function to perform certain control
operations. @var{cmd} controls what is to be done. The return value is
0 for success or an error code. Currently supported values for
@var{cmd} are:
@table @code
@item GCRYCTL_DISABLE_ALGO
Disable the algorithm given as an algorithm id in @var{buffer}.
@var{buffer} must point to an @code{int} variable with the algorithm id
and @var{buflen} must have the value @code{sizeof (int)}.
@end table
@end deftypefun
@c end gcry_pk_ctl
@noindent
-Libgcrypt also provides a function for generating public key
+Libgcrypt also provides a function to generate public key
pairs:
@deftypefun gcry_error_t gcry_pk_genkey (@w{gcry_sexp_t *@var{r_key}}, @w{gcry_sexp_t @var{parms}})
This function create a new public key pair using information given in
the S-expression @var{parms} and stores the private and the public key
in one new S-expression at the address given by @var{r_key}. In case of
an error, @var{r_key} is set to @code{NULL}. The return code is 0 for
success or an error code otherwise.
@noindent
-Here is an example for @var{parms} for creating a 1024 bit RSA key:
+Here is an example for @var{parms} to create an 2048 bit RSA key:
@example
(genkey
(rsa
- (nbits 4:1024)))
+ (nbits 4:2048)))
@end example
@noindent
To create an Elgamal key, substitute "elg" for "rsa" and to create a DSA
key use "dsa". Valid ranges for the key length depend on the
algorithms; all commonly used key lengths are supported. Currently
supported parameters are:
@table @code
@item nbits
This is always required to specify the length of the key. The argument
is a string with a number in C-notation. The value should be a multiple
of 8.
@item curve @var{name}
For ECC a named curve may be used instead of giving the number of
requested bits. This allows to request a specific curve to override a
default selection Libgcrypt would have taken if @code{nbits} has been
given. The available names are listed with the description of the ECC
public key parameters.
@item rsa-use-e
This is only used with RSA to give a hint for the public exponent. The
value will be used as a base to test for a usable exponent. Some values
are special:
@table @samp
@item 0
Use a secure and fast value. This is currently the number 41.
@item 1
-Use a secure value as required by some specification. This is currently
+Use a value as required by some crypto policies. This is currently
the number 65537.
@item 2
Reserved
+@item > 2
+Use the given value.
@end table
@noindent
If this parameter is not used, Libgcrypt uses for historic reasons
65537.
@item qbits
This is only meanigful for DSA keys. If it is given the DSA key is
generated with a Q parameyer of this size. If it is not given or zero
Q is deduced from NBITS in this way:
@table @samp
@item 512 <= N <= 1024
Q = 160
@item N = 2048
Q = 224
@item N = 3072
Q = 256
@item N = 7680
Q = 384
@item N = 15360
Q = 512
@end table
Note that in this case only the values for N, as given in the table,
are allowed. When specifying Q all values of N in the range 512 to
15680 are valid as long as they are multiples of 8.
@item transient-key
This is only meaningful for RSA keys. This is a flag with no value. If
given the RSA key is created using a faster and a somewhat less secure
random number generator. This flag may be used for keys which are only
used for a short time and do not require full cryptographic strength.
+@item domain
+This is only meaningful for DLP algorithms. If specified keys are
+generated with domain parameters taken from this list. The exact
+format of this parameter depends on the actual algorithm. It is
+currently only implemented for DSA using this format:
+
+@example
+(genkey
+ (dsa
+ (domain
+ (p @var{p-mpi})
+ (q @var{q-mpi})
+ (g @var{q-mpi})
+ (seed @var{seed-mpi})
+ (counter @var{counter-mpi})
+ (h @var{h-mpi}))))
+@end example
+
+The @code{seed}, @code{counter} and @code{h} domain parameters are
+optional and currently not used.
@end table
@c end table of parameters
@noindent
The key pair is returned in a format depending on the algorithm. Both
private and public keys are returned in one container and may be
accompanied by some miscellaneous information.
@noindent
As an example, here is what the Elgamal key generation returns:
@example
(key-data
(public-key
(elg
(p @var{p-mpi})
(g @var{g-mpi})
(y @var{y-mpi})))
(private-key
(elg
(p @var{p-mpi})
(g @var{g-mpi})
(y @var{y-mpi})
(x @var{x-mpi})))
(misc-key-info
(pm1-factors @var{n1 n2 ... nn})))
@end example
@noindent
As you can see, some of the information is duplicated, but this provides
an easy way to extract either the public or the private key. Note that
the order of the elements is not defined, e.g. the private key may be
stored before the public key. @var{n1 n2 ... nn} is a list of prime
numbers used to composite @var{p-mpi}; this is in general not a very
useful information.
@end deftypefun
@c end gcry_pk_genkey
@node AC Interface
@section Alternative Public Key Interface
This section documents the alternative interface to asymmetric
cryptography (ac) that is not based on S-expressions, but on native C
data structures. As opposed to the pk interface described in the
former chapter, this one follows an open/use/close paradigm like other
building blocks of the library.
@strong{This interface has a few known problems; most noteworthy an
inherent tendency to leak memory. It might not be available in
forthcoming versions Libgcrypt.}
@menu
* Available asymmetric algorithms:: List of algorithms supported by the library.
* Working with sets of data:: How to work with sets of data.
* Working with IO objects:: How to work with IO objects.
* Working with handles:: How to use handles.
* Working with keys:: How to work with keys.
* Using cryptographic functions:: How to perform cryptographic operations.
* Handle-independent functions:: General functions independent of handles.
@end menu
@node Available asymmetric algorithms
@subsection Available asymmetric algorithms
Libgcrypt supports the RSA (Rivest-Shamir-Adleman)
algorithms as well as DSA (Digital Signature Algorithm) and Elgamal.
The versatile interface allows to add more algorithms in the future.
@deftp {Data type} gcry_ac_id_t
The following constants are defined for this type:
@table @code
@item GCRY_AC_RSA
Rivest-Shamir-Adleman
@item GCRY_AC_DSA
Digital Signature Algorithm
@item GCRY_AC_ELG
Elgamal
@item GCRY_AC_ELG_E
Elgamal, encryption only.
@end table
@end deftp
@node Working with sets of data
@subsection Working with sets of data
In the context of this interface the term `data set' refers to a list
of `named MPI values' that is used by functions performing
cryptographic operations; a named MPI value is a an MPI value,
associated with a label.
Such data sets are used for representing keys, since keys simply
consist of a variable amount of numbers. Furthermore some functions
return data sets to the caller that are to be provided to other
functions.
This section documents the data types, symbols and functions that are
relevant for working with data sets.
@deftp {Data type} gcry_ac_data_t
A single data set.
@end deftp
The following flags are supported:
@table @code
@item GCRY_AC_FLAG_DEALLOC
Used for storing data in a data set. If given, the data will be
released by the library. Note that whenever one of the ac functions
is about to release objects because of this flag, the objects are
expected to be stored in memory allocated through the Libgcrypt memory
management. In other words: gcry_free() is used instead of free().
@item GCRY_AC_FLAG_COPY
Used for storing/retrieving data in/from a data set. If given, the
library will create copies of the provided/contained data, which will
then be given to the user/associated with the data set.
@end table
@deftypefun gcry_error_t gcry_ac_data_new (gcry_ac_data_t *@var{data})
Creates a new, empty data set and stores it in @var{data}.
@end deftypefun
@deftypefun void gcry_ac_data_destroy (gcry_ac_data_t @var{data})
Destroys the data set @var{data}.
@end deftypefun
@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})
Add the value @var{mpi} to @var{data} with the label @var{name}. If
@var{flags} contains GCRY_AC_FLAG_COPY, the data set will contain
copies of @var{name} and @var{mpi}. If @var{flags} contains
GCRY_AC_FLAG_DEALLOC or GCRY_AC_FLAG_COPY, the values
contained in the data set will be deallocated when they are to be
removed from the data set.
@end deftypefun
@deftypefun gcry_error_t gcry_ac_data_copy (gcry_ac_data_t *@var{data_cp}, gcry_ac_data_t @var{data})
Create a copy of the data set @var{data} and store it in
@var{data_cp}. FIXME: exact semantics undefined.
@end deftypefun
@deftypefun {unsigned int} gcry_ac_data_length (gcry_ac_data_t @var{data})
Returns the number of named MPI values inside of the data set
@var{data}.
@end deftypefun
@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})
Store the value labelled with @var{name} found in @var{data} in
@var{mpi}. If @var{flags} contains GCRY_AC_FLAG_COPY, store a copy of
the @var{mpi} value contained in the data set. @var{mpi} may be NULL
(this might be useful for checking the existence of an MPI with
extracting it).
@end deftypefun
@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})
Stores in @var{name} and @var{mpi} the named @var{mpi} value contained
in the data set @var{data} with the index @var{idx}. If @var{flags}
contains GCRY_AC_FLAG_COPY, store copies of the values contained in
the data set. @var{name} or @var{mpi} may be NULL.
@end deftypefun
@deftypefun void gcry_ac_data_clear (gcry_ac_data_t @var{data})
Destroys any values contained in the data set @var{data}.
@end deftypefun
@deftypefun gcry_error_t gcry_ac_data_to_sexp (gcry_ac_data_t @var{data}, gcry_sexp_t *@var{sexp}, const char **@var{identifiers})
This function converts the data set @var{data} into a newly created
S-Expression, which is to be stored in @var{sexp}; @var{identifiers}
is a NULL terminated list of C strings, which specifies the structure
of the S-Expression.
Example:
If @var{identifiers} is a list of pointers to the strings ``foo'' and
``bar'' and if @var{data} is a data set containing the values ``val1 =
0x01'' and ``val2 = 0x02'', then the resulting S-Expression will look
like this: (foo (bar ((val1 0x01) (val2 0x02))).
@end deftypefun
@deftypefun gcry_error gcry_ac_data_from_sexp (gcry_ac_data_t *@var{data}, gcry_sexp_t @var{sexp}, const char **@var{identifiers})
This function converts the S-Expression @var{sexp} into a newly
created data set, which is to be stored in @var{data};
@var{identifiers} is a NULL terminated list of C strings, which
specifies the structure of the S-Expression. If the list of
identifiers does not match the structure of the S-Expression, the
function fails.
@end deftypefun
@node Working with IO objects
@subsection Working with IO objects
Note: IO objects are currently only used in the context of message
encoding/decoding and encryption/signature schemes.
@deftp {Data type} {gcry_ac_io_t}
@code{gcry_ac_io_t} is the type to be used for IO objects.
@end deftp
IO objects provide an uniform IO layer on top of different underlying
IO mechanisms; either they can be used for providing data to the
library (mode is GCRY_AC_IO_READABLE) or they can be used for
retrieving data from the library (mode is GCRY_AC_IO_WRITABLE).
IO object need to be initialized by calling on of the following
functions:
@deftypefun void gcry_ac_io_init (gcry_ac_io_t *@var{ac_io}, gcry_ac_io_mode_t @var{mode}, gcry_ac_io_type_t @var{type}, ...);
Initialize @var{ac_io} according to @var{mode}, @var{type} and the
variable list of arguments. The list of variable arguments to specify
depends on the given @var{type}.
@end deftypefun
@deftypefun void gcry_ac_io_init_va (gcry_ac_io_t *@var{ac_io}, gcry_ac_io_mode_t @var{mode}, gcry_ac_io_type_t @var{type}, va_list @var{ap});
Initialize @var{ac_io} according to @var{mode}, @var{type} and the
variable list of arguments @var{ap}. The list of variable arguments
to specify depends on the given @var{type}.
@end deftypefun
The following types of IO objects exist:
@table @code
@item GCRY_AC_IO_STRING
In case of GCRY_AC_IO_READABLE the IO object will provide data from a
memory string. Arguments to specify at initialization time:
@table @code
@item unsigned char *
Pointer to the beginning of the memory string
@item size_t
Size of the memory string
@end table
In case of GCRY_AC_IO_WRITABLE the object will store retrieved data in
a newly allocated memory string. Arguments to specify at
initialization time:
@table @code
@item unsigned char **
Pointer to address, at which the pointer to the newly created memory
string is to be stored
@item size_t *
Pointer to address, at which the size of the newly created memory
string is to be stored
@end table
@item GCRY_AC_IO_CALLBACK
In case of GCRY_AC_IO_READABLE the object will forward read requests
to a provided callback function. Arguments to specify at
initialization time:
@table @code
@item gcry_ac_data_read_cb_t
Callback function to use
@item void *
Opaque argument to provide to the callback function
@end table
In case of GCRY_AC_IO_WRITABLE the object will forward write requests
to a provided callback function. Arguments to specify at
initialization time:
@table @code
@item gcry_ac_data_write_cb_t
Callback function to use
@item void *
Opaque argument to provide to the callback function
@end table
@end table
@node Working with handles
@subsection Working with handles
In order to use an algorithm, an according handle must be created.
This is done using the following function:
@deftypefun gcry_error_t gcry_ac_open (gcry_ac_handle_t *@var{handle}, int @var{algorithm}, int @var{flags})
Creates a new handle for the algorithm @var{algorithm} and stores it
in @var{handle}. @var{flags} is not used currently.
@var{algorithm} must be a valid algorithm ID, see @xref{Available
asymmetric algorithms}, for a list of supported algorithms and the
according constants. Besides using the listed constants directly, the
functions @code{gcry_pk_name_to_id} may be used to convert the textual
name of an algorithm into the according numeric ID.
@end deftypefun
@deftypefun void gcry_ac_close (gcry_ac_handle_t @var{handle})
Destroys the handle @var{handle}.
@end deftypefun
@node Working with keys
@subsection Working with keys
@deftp {Data type} gcry_ac_key_type_t
Defined constants:
@table @code
@item GCRY_AC_KEY_SECRET
Specifies a secret key.
@item GCRY_AC_KEY_PUBLIC
Specifies a public key.
@end table
@end deftp
@deftp {Data type} gcry_ac_key_t
This type represents a single `key', either a secret one or a public
one.
@end deftp
@deftp {Data type} gcry_ac_key_pair_t
This type represents a `key pair' containing a secret and a public key.
@end deftp
Key data structures can be created in two different ways; a new key
pair can be generated, resulting in ready-to-use key. Alternatively a
key can be initialized from a given data set.
@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})
Creates a new key of type @var{type}, consisting of the MPI values
contained in the data set @var{data} and stores it in @var{key}.
@end deftypefun
@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})
Generates a new key pair via the handle @var{handle} of @var{NBITS}
bits and stores it in @var{key_pair}.
In case non-standard settings are wanted, a pointer to a structure of
type @code{gcry_ac_key_spec_<algorithm>_t}, matching the selected
algorithm, can be given as @var{key_spec}. @var{misc_data} is not
used yet. Such a structure does only exist for RSA. A description
of the members of the supported structures follows.
@table @code
@item gcry_ac_key_spec_rsa_t
@table @code
@item gcry_mpi_t e
Generate the key pair using a special @code{e}. The value of @code{e}
has the following meanings:
@table @code
@item = 0
Let Libgcrypt decide what exponent should be used.
@item = 1
Request the use of a ``secure'' exponent; this is required by some
specification to be 65537.
@item > 2
Try starting at this value until a working exponent is found. Note
that the current implementation leaks some information about the
private key because the incrementation used is not randomized. Thus,
this function will be changed in the future to return a random
exponent of the given size.
@end table
@end table
@end table
Example code:
@example
@{
gcry_ac_key_pair_t key_pair;
gcry_ac_key_spec_rsa_t rsa_spec;
rsa_spec.e = gcry_mpi_new (0);
gcry_mpi_set_ui (rsa_spec.e, 1);
err = gcry_ac_open (&handle, GCRY_AC_RSA, 0);
assert (! err);
err = gcry_ac_key_pair_generate (handle, 1024, &rsa_spec,
&key_pair, NULL);
assert (! err);
@}
@end example
@end deftypefun
@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})
Returns the key of type @var{which} out of the key pair
@var{key_pair}.
@end deftypefun
@deftypefun void gcry_ac_key_destroy (gcry_ac_key_t @var{key})
Destroys the key @var{key}.
@end deftypefun
@deftypefun void gcry_ac_key_pair_destroy (gcry_ac_key_pair_t @var{key_pair})
Destroys the key pair @var{key_pair}.
@end deftypefun
@deftypefun gcry_ac_data_t gcry_ac_key_data_get (gcry_ac_key_t @var{key})
Returns the data set contained in the key @var{key}.
@end deftypefun
@deftypefun gcry_error_t gcry_ac_key_test (gcry_ac_handle_t @var{handle}, gcry_ac_key_t @var{key})
Verifies that the private key @var{key} is sane via @var{handle}.
@end deftypefun
@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})
Stores the number of bits of the key @var{key} in @var{nbits} via @var{handle}.
@end deftypefun
@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})
Writes the 20 byte long key grip of the key @var{key} to
@var{key_grip} via @var{handle}.
@end deftypefun
@node Using cryptographic functions
@subsection Using cryptographic functions
The following flags might be relevant:
@table @code
@item GCRY_AC_FLAG_NO_BLINDING
Disable any blinding, which might be supported by the chosen
algorithm; blinding is the default.
@end table
There exist two kinds of cryptographic functions available through the
ac interface: primitives, and high-level functions.
Primitives deal with MPIs (data sets) directly; what they provide is
direct access to the cryptographic operations provided by an algorithm
implementation.
High-level functions deal with octet strings, according to a specified
``scheme''. Schemes make use of ``encoding methods'', which are
responsible for converting the provided octet strings into MPIs, which
are then forwared to the cryptographic primitives. Since schemes are
to be used for a special purpose in order to achieve a particular
security goal, there exist ``encryption schemes'' and ``signature
schemes''. Encoding methods can be used seperately or implicitly
through schemes.
What follows is a description of the cryptographic primitives.
@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})
Encrypts the plain text MPI value @var{data_plain} with the key public
@var{key} under the control of the flags @var{flags} and stores the
resulting data set into @var{data_encrypted}.
@end deftypefun
@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})
Decrypts the encrypted data contained in the data set
@var{data_encrypted} with the secret key KEY under the control of the
flags @var{flags} and stores the resulting plain text MPI value in
@var{DATA_PLAIN}.
@end deftypefun
@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})
Signs the data contained in @var{data} with the secret key @var{key}
and stores the resulting signature in the data set
@var{data_signature}.
@end deftypefun
@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})
Verifies that the signature contained in the data set
@var{data_signature} is indeed the result of signing the data
contained in @var{data} with the secret key belonging to the public
key @var{key}.
@end deftypefun
What follows is a description of the high-level functions.
The type ``gcry_ac_em_t'' is used for specifying encoding methods; the
following methods are supported:
@table @code
@item GCRY_AC_EME_PKCS_V1_5
PKCS-V1_5 Encoding Method for Encryption. Options must be provided
through a pointer to a correctly initialized object of type
gcry_ac_eme_pkcs_v1_5_t.
@item GCRY_AC_EMSA_PKCS_V1_5
PKCS-V1_5 Encoding Method for Signatures with Appendix. Options must
be provided through a pointer to a correctly initialized object of
type gcry_ac_emsa_pkcs_v1_5_t.
@end table
Option structure types:
@table @code
@item gcry_ac_eme_pkcs_v1_5_t
@table @code
@item gcry_ac_key_t key
@item gcry_ac_handle_t handle
@end table
@item gcry_ac_emsa_pkcs_v1_5_t
@table @code
@item gcry_md_algo_t md
@item size_t em_n
@end table
@end table
Encoding methods can be used directly through the following functions:
@deftypefun gcry_error_t gcry_ac_data_encode (gcry_ac_em_t @var{method}, unsigned int @var{flags}, void *@var{options}, unsigned char *@var{m}, size_t @var{m_n}, unsigned char **@var{em}, size_t *@var{em_n})
Encodes the message contained in @var{m} of size @var{m_n} according
to @var{method}, @var{flags} and @var{options}. The newly created
encoded message is stored in @var{em} and @var{em_n}.
@end deftypefun
@deftypefun gcry_error_t gcry_ac_data_decode (gcry_ac_em_t @var{method}, unsigned int @var{flags}, void *@var{options}, unsigned char *@var{em}, size_t @var{em_n}, unsigned char **@var{m}, size_t *@var{m_n})
Decodes the message contained in @var{em} of size @var{em_n} according
to @var{method}, @var{flags} and @var{options}. The newly created
decoded message is stored in @var{m} and @var{m_n}.
@end deftypefun
The type ``gcry_ac_scheme_t'' is used for specifying schemes; the
following schemes are supported:
@table @code
@item GCRY_AC_ES_PKCS_V1_5
PKCS-V1_5 Encryption Scheme. No options can be provided.
@item GCRY_AC_SSA_PKCS_V1_5
PKCS-V1_5 Signature Scheme (with Appendix). Options can be provided
through a pointer to a correctly initialized object of type
gcry_ac_ssa_pkcs_v1_5_t.
@end table
Option structure types:
@table @code
@item gcry_ac_ssa_pkcs_v1_5_t
@table @code
@item gcry_md_algo_t md
@end table
@end table
The functions implementing schemes:
@deftypefun gcry_error_t gcry_ac_data_encrypt_scheme (gcry_ac_handle_t @var{handle}, gcry_ac_scheme_t @var{scheme}, unsigned int @var{flags}, void *@var{opts}, gcry_ac_key_t @var{key}, gcry_ac_io_t *@var{io_message}, gcry_ac_io_t *@var{io_cipher})
Encrypts the plain text readable from @var{io_message} through
@var{handle} with the public key @var{key} according to @var{scheme},
@var{flags} and @var{opts}. If @var{opts} is not NULL, it has to be a
pointer to a structure specific to the chosen scheme (gcry_ac_es_*_t).
The encrypted message is written to @var{io_cipher}.
@end deftypefun
@deftypefun gcry_error_t gcry_ac_data_decrypt_scheme (gcry_ac_handle_t @var{handle}, gcry_ac_scheme_t @var{scheme}, unsigned int @var{flags}, void *@var{opts}, gcry_ac_key_t @var{key}, gcry_ac_io_t *@var{io_cipher}, gcry_ac_io_t *@var{io_message})
Decrypts the cipher text readable from @var{io_cipher} through
@var{handle} with the secret key @var{key} according to @var{scheme},
@var{flags} and @var{opts}. If @var{opts} is not NULL, it has to be a
pointer to a structure specific to the chosen scheme (gcry_ac_es_*_t).
The decrypted message is written to @var{io_message}.
@end deftypefun
@deftypefun gcry_error_t gcry_ac_data_sign_scheme (gcry_ac_handle_t @var{handle}, gcry_ac_scheme_t @var{scheme}, unsigned int @var{flags}, void *@var{opts}, gcry_ac_key_t @var{key}, gcry_ac_io_t *@var{io_message}, gcry_ac_io_t *@var{io_signature})
Signs the message readable from @var{io_message} through @var{handle}
with the secret key @var{key} according to @var{scheme}, @var{flags}
and @var{opts}. If @var{opts} is not NULL, it has to be a pointer to
a structure specific to the chosen scheme (gcry_ac_ssa_*_t). The
signature is written to @var{io_signature}.
@end deftypefun
@deftypefun gcry_error_t gcry_ac_data_verify_scheme (gcry_ac_handle_t @var{handle}, gcry_ac_scheme_t @var{scheme}, unsigned int @var{flags}, void *@var{opts}, gcry_ac_key_t @var{key}, gcry_ac_io_t *@var{io_message}, gcry_ac_io_t *@var{io_signature})
Verifies through @var{handle} that the signature readable from
@var{io_signature} is indeed the result of signing the message
readable from @var{io_message} with the secret key belonging to the
public key @var{key} according to @var{scheme} and @var{opts}. If
@var{opts} is not NULL, it has to be an anonymous structure
(gcry_ac_ssa_*_t) specific to the chosen scheme.
@end deftypefun
@node Handle-independent functions
@subsection Handle-independent functions
These two functions are deprecated; do not use them for new code.
@deftypefun gcry_error_t gcry_ac_id_to_name (gcry_ac_id_t @var{algorithm}, const char **@var{name})
Stores the textual representation of the algorithm whose id is given
in @var{algorithm} in @var{name}. Deprecated; use @code{gcry_pk_algo_name}.
@end deftypefun
@deftypefun gcry_error_t gcry_ac_name_to_id (const char *@var{name}, gcry_ac_id_t *@var{algorithm})
Stores the numeric ID of the algorithm whose textual representation is
contained in @var{name} in @var{algorithm}. Deprecated; use
@code{gcry_pk_map_name}.
@end deftypefun
@c **********************************************************
@c ******************* Hash Functions *********************
@c **********************************************************
@node Hashing
@chapter Hashing
Libgcrypt provides an easy and consistent to use interface for hashing.
Hashing is buffered and several hash algorithms can be updated at once.
It is possible to compute a MAC using the same routines. The
programming model follows an open/process/close paradigm and is in that
similar to other building blocks provided by Libgcrypt.
For convenience reasons, a few cyclic redundancy check value operations
are also supported.
@menu
* Available hash algorithms:: List of hash algorithms supported by the library.
* Hash algorithm modules:: How to work with hash algorithm modules.
* Working with hash algorithms:: List of functions related to hashing.
@end menu
@node Available hash algorithms
@section Available hash algorithms
@c begin table of hash algorithms
@cindex SHA-1
@cindex SHA-224, SHA-256, SHA-384, SHA-512
@cindex RIPE-MD-160
@cindex MD2, MD4, MD5
@cindex TIGER
@cindex HAVAL
@cindex Whirlpool
@cindex CRC32
@table @code
@item GCRY_MD_NONE
This is not a real algorithm but used by some functions as an error
return value. This constant is guaranteed to have the value @code{0}.
@item GCRY_MD_SHA1
This is the SHA-1 algorithm which yields a message digest of 20 bytes.
@item GCRY_MD_RMD160
This is the 160 bit version of the RIPE message digest (RIPE-MD-160).
Like SHA-1 it also yields a digest of 20 bytes.
@item GCRY_MD_MD5
This is the well known MD5 algorithm, which yields a message digest of
16 bytes.
@item GCRY_MD_MD4
This is the MD4 algorithm, which yields a message digest of 16 bytes.
@item GCRY_MD_MD2
This is an reserved identifier for MD-2; there is no implementation yet.
@item GCRY_MD_TIGER
This is the TIGER/192 algorithm which yields a message digest of 24 bytes.
@item GCRY_MD_HAVAL
This is an reserved for the HAVAL algorithm with 5 passes and 160
bit. It yields a message digest of 20 bytes. Note that there is no
implementation yet available.
@item GCRY_MD_SHA224
This is the SHA-224 algorithm which yields a message digest of 28 bytes.
See Change Notice 1 for FIPS 180-2 for the specification.
@item GCRY_MD_SHA256
This is the SHA-256 algorithm which yields a message digest of 32 bytes.
See FIPS 180-2 for the specification.
@item GCRY_MD_SHA384
This is the SHA-384 algorithm which yields a message digest of 48 bytes.
See FIPS 180-2 for the specification.
@item GCRY_MD_SHA512
This is the SHA-384 algorithm which yields a message digest of 64 bytes.
See FIPS 180-2 for the specification.
@item GCRY_MD_CRC32
This is the ISO 3309 and ITU-T V.42 cyclic redundancy check. It
yields an output of 4 bytes.
@item GCRY_MD_CRC32_RFC1510
This is the above cyclic redundancy check function, as modified by RFC
1510. It yields an output of 4 bytes.
@item GCRY_MD_CRC24_RFC2440
This is the OpenPGP cyclic redundancy check function. It yields an
output of 3 bytes.
@item GCRY_MD_WHIRLPOOL
This is the Whirlpool algorithm which yields a message digest of 64
bytes.
@end table
@c end table of hash algorithms
@node Hash algorithm modules
@section Hash algorithm modules
Libgcrypt makes it possible to load additional `message
digest modules'; these digests can be used just like the message digest
algorithms that are built into the library directly. For an
introduction into extension modules, see @xref{Modules}.
@deftp {Data type} gcry_md_spec_t
This is the `module specification structure' needed for registering
message digest modules, which has to be filled in by the user before
it can be used to register a module. It contains the following
members:
@table @code
@item const char *name
The primary name of this algorithm.
@item unsigned char *asnoid
Array of bytes that form the ASN OID.
@item int asnlen
Length of bytes in `asnoid'.
@item gcry_md_oid_spec_t *oids
A list of OIDs that are to be associated with the algorithm. The
list's last element must have it's `oid' member set to NULL. See
below for an explanation of this type. See below for an explanation
of this type.
@item int mdlen
Length of the message digest algorithm. See below for an explanation
of this type.
@item gcry_md_init_t init
The function responsible for initializing a handle. See below for an
explanation of this type.
@item gcry_md_write_t write
The function responsible for writing data into a message digest
context. See below for an explanation of this type.
@item gcry_md_final_t final
The function responsible for `finalizing' a message digest context.
See below for an explanation of this type.
@item gcry_md_read_t read
The function responsible for reading out a message digest result. See
below for an explanation of this type.
@item size_t contextsize
The size of the algorithm-specific `context', that should be
allocated for each handle.
@end table
@end deftp
@deftp {Data type} gcry_md_oid_spec_t
This type is used for associating a user-provided algorithm
implementation with certain OIDs. It contains the following members:
@table @code
@item const char *oidstring
Textual representation of the OID.
@end table
@end deftp
@deftp {Data type} gcry_md_init_t
Type for the `init' function, defined as: void (*gcry_md_init_t) (void
*c)
@end deftp
@deftp {Data type} gcry_md_write_t
Type for the `write' function, defined as: void (*gcry_md_write_t)
(void *c, unsigned char *buf, size_t nbytes)
@end deftp
@deftp {Data type} gcry_md_final_t
Type for the `final' function, defined as: void (*gcry_md_final_t)
(void *c)
@end deftp
@deftp {Data type} gcry_md_read_t
Type for the `read' function, defined as: unsigned char
*(*gcry_md_read_t) (void *c)
@end deftp
@deftypefun gcry_error_t gcry_md_register (gcry_md_spec_t *@var{digest}, unsigned int *algorithm_id, gcry_module_t *@var{module})
Register a new digest module whose specification can be found in
@var{digest}. On success, a new algorithm ID is stored in
@var{algorithm_id} and a pointer representing this module is stored
in @var{module}.
@end deftypefun
@deftypefun void gcry_md_unregister (gcry_module_t @var{module})
Unregister the digest identified by @var{module}, which must have been
registered with gcry_md_register.
@end deftypefun
@deftypefun gcry_error_t gcry_md_list (int *@var{list}, int *@var{list_length})
Get a list consisting of the IDs of the loaded message digest modules.
If @var{list} is zero, write the number of loaded message digest
modules to @var{list_length} and return. If @var{list} is non-zero,
the first *@var{list_length} algorithm IDs are stored in @var{list},
which must be of according size. In case there are less message
digests modules than *@var{list_length}, *@var{list_length} is updated
to the correct number.
@end deftypefun
@node Working with hash algorithms
@section Working with hash algorithms
To use most of these function it is necessary to create a context;
this is done using:
@deftypefun gcry_error_t gcry_md_open (gcry_md_hd_t *@var{hd}, int @var{algo}, unsigned int @var{flags})
Create a message digest object for algorithm @var{algo}. @var{flags}
may be given as an bitwise OR of constants described below. @var{algo}
may be given as @code{0} if the algorithms to use are later set using
@code{gcry_md_enable}. @var{hd} is guaranteed to either receive a valid
handle or NULL.
For a list of supported algorithms, see @xref{Available hash
algorithms}.
The flags allowed for @var{mode} are:
@c begin table of hash flags
@table @code
@item GCRY_MD_FLAG_SECURE
Allocate all buffers and the resulting digest in "secure memory". Use
this is the hashed data is highly confidential.
@item GCRY_MD_FLAG_HMAC
@cindex HMAC
Turn the algorithm into a HMAC message authentication algorithm. This
only works if just one algorithm is enabled for the handle. Note that
the function @code{gcry_md_setkey} must be used to set the MAC key.
The size of the MAC is equal to the message digest of the underlying
hash algorithm. If you want CBC message authentication codes based on
a cipher, see @xref{Working with cipher handles}.
@end table
@c begin table of hash flags
You may use the function @code{gcry_md_is_enabled} to later check
whether an algorithm has been enabled.
@end deftypefun
@c end function gcry_md_open
If you want to calculate several hash algorithms at the same time, you
have to use the following function right after the @code{gcry_md_open}:
@deftypefun gcry_error_t gcry_md_enable (gcry_md_hd_t @var{h}, int @var{algo})
Add the message digest algorithm @var{algo} to the digest object
described by handle @var{h}. Duplicated enabling of algorithms is
detected and ignored.
@end deftypefun
If the flag @code{GCRY_MD_FLAG_HMAC} was used, the key for the MAC must
be set using the function:
@deftypefun gcry_error_t gcry_md_setkey (gcry_md_hd_t @var{h}, const void *@var{key}, size_t @var{keylen})
For use with the HMAC feature, set the MAC key to the value of @var{key}
of length @var{keylen}. There is no restriction on the length of the key.
@end deftypefun
After you are done with the hash calculation, you should release the
resources by using:
@deftypefun void gcry_md_close (gcry_md_hd_t @var{h})
Release all resources of hash context @var{h}. @var{h} should not be
used after a call to this function. A @code{NULL} passed as @var{h} is
ignored.
@end deftypefun
Often you have to do several hash operations using the same algorithm.
To avoid the overhead of creating and releasing context, a reset function
is provided:
@deftypefun void gcry_md_reset (gcry_md_hd_t @var{h})
Reset the current context to its initial state. This is effectively
identical to a close followed by an open and enabling all currently
active algorithms.
@end deftypefun
Often it is necessary to start hashing some data and then continue to
hash different data. To avoid hashing the same data several times (which
might not even be possible if the data is received from a pipe), a
snapshot of the current hash context can be taken and turned into a new
context:
@deftypefun gcry_error_t gcry_md_copy (gcry_md_hd_t *@var{handle_dst}, gcry_md_hd_t @var{handle_src})
Create a new digest object as an exact copy of the object described by
handle @var{handle_src} and store it in @var{handle_dst}. The context
is not reset and you can continue to hash data using this context and
independently using the original context.
@end deftypefun
Now that we have prepared everything to calculate hashes, it is time to
see how it is actually done. There are two ways for this, one to
update the hash with a block of memory and one macro to update the hash
by just one character. Both methods can be used on the same hash context.
@deftypefun void gcry_md_write (gcry_md_hd_t @var{h}, const void *@var{buffer}, size_t @var{length})
Pass @var{length} bytes of the data in @var{buffer} to the digest object
with handle @var{h} to update the digest values. This
function should be used for large blocks of data.
@end deftypefun
@deftypefun void gcry_md_putc (gcry_md_hd_t @var{h}, int @var{c})
Pass the byte in @var{c} to the digest object with handle @var{h} to
update the digest value. This is an efficient function, implemented as
a macro to buffer the data before an actual update.
@end deftypefun
The semantics of the hash functions do not provide for reading out intermediate
message digests because the calculation must be finalized first. This
finalization may for example include the number of bytes hashed in the
message digest or some padding.
@deftypefun void gcry_md_final (gcry_md_hd_t @var{h})
Finalize the message digest calculation. This is not really needed
because @code{gcry_md_read} does this implicitly. After this has been
done no further updates (by means of @code{gcry_md_write} or
@code{gcry_md_putc} are allowed. Only the first call to this function
has an effect. It is implemented as a macro.
@end deftypefun
The way to read out the calculated message digest is by using the
function:
@deftypefun {unsigned char *} gcry_md_read (gcry_md_hd_t @var{h}, int @var{algo})
@code{gcry_md_read} returns the message digest after finalizing the
calculation. This function may be used as often as required but it will
always return the same value for one handle. The returned message digest
is allocated within the message context and therefore valid until the
handle is released or reseted (using @code{gcry_md_close} or
@code{gcry_md_reset}. @var{algo} may be given as 0 to return the only
enabled message digest or it may specify one of the enabled algorithms.
The function does return @code{NULL} if the requested algorithm has not
been enabled.
@end deftypefun
Because it is often necessary to get the message digest of one block of
memory, a fast convenience function is available for this task:
@deftypefun void gcry_md_hash_buffer (int @var{algo}, void *@var{digest}, const void *@var{buffer}, size_t @var{length});
@code{gcry_md_hash_buffer} is a shortcut function to calculate a message
digest of a buffer. This function does not require a context and
immediately returns the message digest of the @var{length} bytes at
@var{buffer}. @var{digest} must be allocated by the caller, large
enough to hold the message digest yielded by the the specified algorithm
@var{algo}. This required size may be obtained by using the function
@code{gcry_md_get_algo_dlen}.
Note that this function will abort the process if an unavailable
algorithm is used.
@end deftypefun
@c ***********************************
@c ***** MD info functions ***********
@c ***********************************
Hash algorithms are identified by internal algorithm numbers (see
@code{gcry_md_open} for a list). However, in most applications they are
used by names, so two functions are available to map between string
representations and hash algorithm identifiers.
@deftypefun {const char *} gcry_md_algo_name (int @var{algo})
Map the digest algorithm id @var{algo} to a string representation of the
algorithm name. For unknown algorithms this function returns the
string @code{"?"}. This function should not be used to test for the
availability of an algorithm.
@end deftypefun
@deftypefun int gcry_md_map_name (const char *@var{name})
Map the algorithm with @var{name} to a digest algorithm identifier.
Returns 0 if the algorithm name is not known. Names representing
@acronym{ASN.1} object identifiers are recognized if the @acronym{IETF}
dotted format is used and the OID is prefixed with either "@code{oid.}"
or "@code{OID.}". For a list of supported OIDs, see the source code at
@file{cipher/md.c}. This function should not be used to test for the
availability of an algorithm.
@end deftypefun
@deftypefun gcry_error_t gcry_md_get_asnoid (int @var{algo}, void *@var{buffer}, size_t *@var{length})
Return an DER encoded ASN.1 OID for the algorithm @var{algo} in the
user allocated @var{buffer}. @var{length} must point to variable with
the available size of @var{buffer} and receives after return the
actual size of the returned OID. The returned error code may be
@code{GPG_ERR_TOO_SHORT} if the provided buffer is to short to receive
the OID; it is possible to call the function with @code{NULL} for
@var{buffer} to have it only return the required size. The function
returns 0 on success.
@end deftypefun
To test whether an algorithm is actually available for use, the
following macro should be used:
@deftypefun gcry_error_t gcry_md_test_algo (int @var{algo})
The macro returns 0 if the algorithm @var{algo} is available for use.
@end deftypefun
If the length of a message digest is not known, it can be retrieved
using the following function:
@deftypefun {unsigned int} gcry_md_get_algo_dlen (int @var{algo})
Retrieve the length in bytes of the digest yielded by algorithm
@var{algo}. This is often used prior to @code{gcry_md_read} to allocate
sufficient memory for the digest.
@end deftypefun
In some situations it might be hard to remember the algorithm used for
the ongoing hashing. The following function might be used to get that
information:
@deftypefun int gcry_md_get_algo (gcry_md_hd_t @var{h})
Retrieve the algorithm used with the handle @var{h}. Note that this
does not work reliable if more than one algorithm is enabled in @var{h}.
@end deftypefun
The following macro might also be useful:
@deftypefun int gcry_md_is_secure (gcry_md_hd_t @var{h})
This function returns true when the digest object @var{h} is allocated
in "secure memory"; i.e. @var{h} was created with the
@code{GCRY_MD_FLAG_SECURE}.
@end deftypefun
@deftypefun int gcry_md_is_enabled (gcry_md_hd_t @var{h}, int @var{algo})
This function returns true when the algorithm @var{algo} has been
enabled for the digest object @var{h}.
@end deftypefun
Tracking bugs related to hashing is often a cumbersome task which
requires to add a lot of printf statements into the code.
Libgcrypt provides an easy way to avoid this. The actual data
hashed can be written to files on request.
@deftypefun void gcry_md_debug (gcry_md_hd_t @var{h}, const char *@var{suffix})
Enable debugging for the digest object with handle @var{h}. This
creates create files named @file{dbgmd-<n>.<string>} while doing the
actual hashing. @var{suffix} is the string part in the filename. The
number is a counter incremented for each new hashing. The data in the
file is the raw data as passed to @code{gcry_md_write} or
@code{gcry_md_putc}. If @code{NULL} is used for @var{suffix}, the
debugging is stopped and the file closed. This is only rarely required
because @code{gcry_md_close} implicitly stops debugging.
@end deftypefun
The following two deprecated macros are used for debugging by old code.
They shopuld be replaced by @code{gcry_md_debug}.
@deftypefun void gcry_md_start_debug (gcry_md_hd_t @var{h}, const char *@var{suffix})
Enable debugging for the digest object with handle @var{h}. This
creates create files named @file{dbgmd-<n>.<string>} while doing the
actual hashing. @var{suffix} is the string part in the filename. The
number is a counter incremented for each new hashing. The data in the
file is the raw data as passed to @code{gcry_md_write} or
@code{gcry_md_putc}.
@end deftypefun
@deftypefun void gcry_md_stop_debug (gcry_md_hd_t @var{h}, int @var{reserved})
Stop debugging on handle @var{h}. @var{reserved} should be specified as
0. This function is usually not required because @code{gcry_md_close}
does implicitly stop debugging.
@end deftypefun
@c **********************************************************
@c ******************* Random *****************************
@c **********************************************************
@node Random Numbers
@chapter Random Numbers
@menu
* Quality of random numbers:: Libgcrypt uses different quality levels.
* Retrieving random numbers:: How to retrieve random numbers.
@end menu
@node Quality of random numbers
@section Quality of random numbers
@acronym{Libgcypt} offers random numbers of different quality levels:
@deftp {Data type} gcry_random_level_t
The constants for the random quality levels are of this enum type.
@end deftp
@table @code
@item GCRY_WEAK_RANDOM
For all functions, except for @code{gcry_mpi_randomize}, this level maps
to GCRY_STRONG_RANDOM. If you do not want this, consider using
@code{gcry_create_nonce}.
@item GCRY_STRONG_RANDOM
Use this level for session keys and similar purposes.
@item GCRY_VERY_STRONG_RANDOM
Use this level for long term key material.
@end table
@node Retrieving random numbers
@section Retrieving random numbers
@deftypefun void gcry_randomize (unsigned char *@var{buffer}, size_t @var{length}, enum gcry_random_level @var{level})
Fill @var{buffer} with @var{length} random bytes using a random quality
as defined by @var{level}.
@end deftypefun
@deftypefun {void *} gcry_random_bytes (size_t @var{nbytes}, enum gcry_random_level @var{level})
Convenience function to allocate a memory block consisting of
@var{nbytes} fresh random bytes using a random quality as defined by
@var{level}.
@end deftypefun
@deftypefun {void *} gcry_random_bytes_secure (size_t @var{nbytes}, enum gcry_random_level @var{level})
Convenience function to allocate a memory block consisting of
@var{nbytes} fresh random bytes using a random quality as defined by
@var{level}. This function differs from @code{gcry_random_bytes} in
that the returned buffer is allocated in a ``secure'' area of the
memory.
@end deftypefun
@deftypefun void gcry_create_nonce (unsigned char *@var{buffer}, size_t @var{length})
Fill @var{buffer} with @var{length} unpredictable bytes. This is
commonly called a nonce and may also be used for initialization
vectors and padding. This is an extra function nearly independent of
the other random function for 3 reasons: It better protects the
regular random generator's internal state, provides better performance
and does not drain the precious entropy pool.
@end deftypefun
@c **********************************************************
@c ******************* S-Expressions ***********************
@c **********************************************************
@node S-expressions
@chapter S-expressions
S-expressions are used by the public key functions to pass complex data
structures around. These LISP like objects are used by some
cryptographic protocols (cf. RFC-2692) and Libgcrypt provides functions
to parse and construct them. For detailed information, see
@cite{Ron Rivest, code and description of S-expressions,
@uref{http://theory.lcs.mit.edu/~rivest/sexp.html}}.
@menu
* Data types for S-expressions:: Data types related with S-expressions.
* Working with S-expressions:: How to work with S-expressions.
@end menu
@node Data types for S-expressions
@section Data types for S-expressions
@deftp {Data type} gcry_sexp_t
The @code{gcry_sexp_t} type describes an object with the Libgcrypt internal
representation of an S-expression.
@end deftp
@node Working with S-expressions
@section Working with S-expressions
@noindent
There are several functions to create an Libgcrypt S-expression object
from its external representation or from a string template. There is
also a function to convert the internal representation back into one of
the external formats:
@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}})
This is the generic function to create an new S-expression object from
its external representation in @var{buffer} of @var{length} bytes. On
success the result is stored at the address given by @var{r_sexp}.
With @var{autodetect} set to 0, the data in @var{buffer} is expected to
be in canonized format, with @var{autodetect} set to 1 the parses any of
the defined external formats. If @var{buffer} does not hold a valid
S-expression an error code is returned and @var{r_sexp} set to
@code{NULL}.
Note that the caller is responsible for releasing the newly allocated
S-expression using @code{gcry_sexp_release}.
@end deftypefun
@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*)})
This function is identical to @code{gcry_sexp_new} but has an extra
argument @var{freefnc}, which, when not set to @code{NULL}, is expected
to be a function to release the @var{buffer}; most likely the standard
@code{free} function is used for this argument. This has the effect of
transferring the ownership of @var{buffer} to the created object in
@var{r_sexp}. The advantage of using this function is that Libgcrypt
might decide to directly use the provided buffer and thus avoid extra
copying.
@end deftypefun
@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}})
This is another variant of the above functions. It behaves nearly
identical but provides an @var{erroff} argument which will receive the
offset into the buffer where the parsing stopped on error.
@end deftypefun
@deftypefun gcry_error_t gcry_sexp_build (@w{gcry_sexp_t *@var{r_sexp}}, @w{size_t *@var{erroff}}, @w{const char *@var{format}, ...})
This function creates an internal S-expression from the string template
@var{format} and stores it at the address of @var{r_sexp}. If there is a
parsing error, the function returns an appropriate error code and stores
the offset into @var{format} where the parsing stopped in @var{erroff}.
The function supports a couple of printf-like formatting characters and
expects arguments for some of these escape sequences right after
@var{format}. The following format characters are defined:
@table @samp
@item %m
The next argument is expected to be of type @code{gcry_mpi_t} and a copy of
its value is inserted into the resulting S-expression.
@item %s
The next argument is expected to be of type @code{char *} and that
string is inserted into the resulting S-expression.
@item %d
The next argument is expected to be of type @code{int} and its value is
inserted into the resulting S-expression.
@item %b
The next argument is expected to be of type @code{int} directly
followed by an argument of type @code{char *}. This represents a
buffer of given length to be inserted into the resulting regular
expression.
@end table
@noindent
No other format characters are defined and would return an error. Note
that the format character @samp{%%} does not exists, because a percent
sign is not a valid character in an S-expression.
@end deftypefun
@deftypefun void gcry_sexp_release (@w{gcry_sexp_t @var{sexp}})
Release the S-expression object @var{sexp}.
@end deftypefun
@noindent
The next 2 functions are used to convert the internal representation
back into a regular external S-expression format and to show the
structure for debugging.
@deftypefun size_t gcry_sexp_sprint (@w{gcry_sexp_t @var{sexp}}, @w{int @var{mode}}, @w{char *@var{buffer}}, @w{size_t @var{maxlength}})
Copies the S-expression object @var{sexp} into @var{buffer} using the
format specified in @var{mode}. @var{maxlength} must be set to the
allocated length of @var{buffer}. The function returns the actual
length of valid bytes put into @var{buffer} or 0 if the provided buffer
is too short. Passing @code{NULL} for @var{buffer} returns the required
length for @var{buffer}. For convenience reasons an extra byte with
value 0 is appended to the buffer.
@noindent
The following formats are supported:
@table @code
@item GCRYSEXP_FMT_DEFAULT
Returns a convenient external S-expression representation.
@item GCRYSEXP_FMT_CANON
Return the S-expression in canonical format.
@item GCRYSEXP_FMT_BASE64
Not currently supported.
@item GCRYSEXP_FMT_ADVANCED
Returns the S-expression in advanced format.
@end table
@end deftypefun
@deftypefun void gcry_sexp_dump (@w{gcry_sexp_t @var{sexp}})
Dumps @var{sexp} in a format suitable for debugging to Libgcrypt's
logging stream.
@end deftypefun
@noindent
Often canonical encoding is used in the external representation. The
following function can be used to check for valid encoding and to learn
the length of the S-expression"
@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}})
Scan the canonical encoded @var{buffer} with implicit length values and
return the actual length this S-expression uses. For a valid S-expression
it should never return 0. If @var{length} is not 0, the maximum
length to scan is given; this can be used for syntax checks of
data passed from outside. @var{errcode} and @var{erroff} may both be
passed as @code{NULL}.
@end deftypefun
@noindent
There are a couple of functions to parse S-expressions and retrieve
elements:
@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}})
Scan the S-expression for a sublist with a type (the car of the list)
matching the string @var{token}. If @var{toklen} is not 0, the token is
assumed to be raw memory of this length. The function returns a newly
allocated S-expression consisting of the found sublist or @code{NULL}
when not found.
@end deftypefun
@deftypefun int gcry_sexp_length (@w{const gcry_sexp_t @var{list}})
Return the length of the @var{list}. For a valid S-expression this
should be at least 1.
@end deftypefun
@deftypefun gcry_sexp_t gcry_sexp_nth (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}})
Create and return a new S-expression from the element with index @var{number} in
@var{list}. Note that the first element has the index 0. If there is
no such element, @code{NULL} is returned.
@end deftypefun
@deftypefun gcry_sexp_t gcry_sexp_car (@w{const gcry_sexp_t @var{list}})
Create and return a new S-expression from the first element in
@var{list}; this called the "type" and should always exist and be a
string. @code{NULL} is returned in case of a problem.
@end deftypefun
@deftypefun gcry_sexp_t gcry_sexp_cdr (@w{const gcry_sexp_t @var{list}})
Create and return a new list form all elements except for the first one.
Note that this function may return an invalid S-expression because it
is not guaranteed, that the type exists and is a string. However, for
parsing a complex S-expression it might be useful for intermediate
lists. Returns @code{NULL} on error.
@end deftypefun
@deftypefun {const char *} gcry_sexp_nth_data (@w{const gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{size_t *@var{datalen}})
This function is used to get data from a @var{list}. A pointer to the
actual data with index @var{number} is returned and the length of this
data will be stored to @var{datalen}. If there is no data at the given
index or the index represents another list, @code{NULL} is returned.
@strong{Caution:} The returned pointer is valid as long as @var{list} is
not modified or released.
@noindent
Here is an example on how to extract and print the surname (Meier) from
the S-expression @samp{(Name Otto Meier (address Burgplatz 3))}:
@example
size_t len;
const char *name;
name = gcry_sexp_nth_data (list, 2, &len);
printf ("my name is %.*s\n", (int)len, name);
@end example
@end deftypefun
@deftypefun {char *} gcry_sexp_nth_string (@w{gcry_sexp_t @var{list}}, @w{int @var{number}})
This function is used to get and convert data from a @var{list}. The
data is assumed to be a Nul terminated string. The caller must
release this returned value using @code{gcry_free}. If there is
no data at the given index, the index represents a list or the value
can't be converted to a string, @code{NULL} is returned.
@end deftypefun
@deftypefun gcry_mpi_t gcry_sexp_nth_mpi (@w{gcry_sexp_t @var{list}}, @w{int @var{number}}, @w{int @var{mpifmt}})
This function is used to get and convert data from a @var{list}. This
data is assumed to be an MPI stored in the format described by
@var{mpifmt} and returned as a standard Libgcrypt MPI. The caller must
release this returned value using @code{gcry_mpi_release}. If there is
no data at the given index, the index represents a list or the value
can't be converted to an MPI, @code{NULL} is returned.
@end deftypefun
@c **********************************************************
@c ******************* MPIs ******** ***********************
@c **********************************************************
@node MPI library
@chapter MPI library
@menu
* Data types:: MPI related data types.
* Basic functions:: First steps with MPI numbers.
* MPI formats:: External representation of MPIs.
* Calculations:: Performing MPI calculations.
* Comparisons:: How to compare MPI values.
* Bit manipulations:: How to access single bits of MPI values.
* Miscellaneous:: Miscellaneous MPI functions.
@end menu
Public key cryptography is based on mathematics with large numbers. To
implement the public key functions, a library for handling these large
numbers is required. Because of the general usefulness of such a
library, its interface is exposed by Libgcrypt.
In the context of Libgcrypt and in most other applications, these large
numbers are called MPIs (multi-precision-integers).
@node Data types
@section Data types
@deftp {Data type} {gcry_mpi_t}
This type represents an object to hold an MPI.
@end deftp
@node Basic functions
@section Basic functions
@noindent
To work with MPIs, storage must be allocated and released for the
numbers. This can be done with one of these functions:
@deftypefun gcry_mpi_t gcry_mpi_new (@w{unsigned int @var{nbits}})
Allocate a new MPI object, initialize it to 0 and initially allocate
enough memory for a number of at least @var{nbits}. This pre-allocation is
only a small performance issue and not actually necessary because
Libgcrypt automatically re-allocates the required memory.
@end deftypefun
@deftypefun gcry_mpi_t gcry_mpi_snew (@w{unsigned int @var{nbits}})
This is identical to @code{gcry_mpi_new} but allocates the MPI in the so
called "secure memory" which in turn will take care that all derived
values will also be stored in this "secure memory". Use this for highly
confidential data like private key parameters.
@end deftypefun
@deftypefun gcry_mpi_t gcry_mpi_copy (@w{const gcry_mpi_t @var{a}})
Create a new MPI as the exact copy of @var{a}.
@end deftypefun
@deftypefun void gcry_mpi_release (@w{gcry_mpi_t @var{a}})
Release the MPI @var{a} and free all associated resources. Passing
@code{NULL} is allowed and ignored. When a MPI stored in the "secure
memory" is released, that memory gets wiped out immediately.
@end deftypefun
@noindent
The simplest operations are used to assign a new value to an MPI:
@deftypefun gcry_mpi_t gcry_mpi_set (@w{gcry_mpi_t @var{w}}, @w{const gcry_mpi_t @var{u}})
Assign the value of @var{u} to @var{w} and return @var{w}. If
@code{NULL} is passed for @var{w}, a new MPI is allocated, set to the
value of @var{u} and returned.
@end deftypefun
@deftypefun gcry_mpi_t gcry_mpi_set_ui (@w{gcry_mpi_t @var{w}}, @w{unsigned long @var{u}})
Assign the value of @var{u} to @var{w} and return @var{w}. If
@code{NULL} is passed for @var{w}, a new MPI is allocated, set to the
value of @var{u} and returned. This function takes an @code{unsigned
int} as type for @var{u} and thus it is only possible to set @var{w} to
small values (usually up to the word size of the CPU).
@end deftypefun
@deftypefun void gcry_mpi_swap (@w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}})
Swap the values of @var{a} and @var{b}.
@end deftypefun
@node MPI formats
@section MPI formats
@noindent
The following functions are used to convert between an external
representation of an MPI and the internal one of Libgcrypt.
@deftypefun gcry_error_t gcry_mpi_scan (@w{gcry_mpi_t *@var{r_mpi}}, @w{enum gcry_mpi_format @var{format}}, @w{const unsigned char *@var{buffer}}, @w{size_t @var{buflen}}, @w{size_t *@var{nscanned}})
Convert the external representation of an integer stored in @var{buffer}
with a length of @var{buflen} into a newly created MPI returned which
will be stored at the address of @var{r_mpi}. For certain formats the
length argument is not required and should be passed as @code{0}. After a
successful operation the variable @var{nscanned} receives the number of
bytes actually scanned unless @var{nscanned} was given as
@code{NULL}. @var{format} describes the format of the MPI as stored in
@var{buffer}:
@table @code
@item GCRYMPI_FMT_STD
2-complement stored without a length header.
@item GCRYMPI_FMT_PGP
As used by OpenPGP (only defined as unsigned). This is basically
@code{GCRYMPI_FMT_STD} with a 2 byte big endian length header.
@item GCRYMPI_FMT_SSH
As used in the Secure Shell protocol. This is @code{GCRYMPI_FMT_STD}
with a 4 byte big endian header.
@item GCRYMPI_FMT_HEX
Stored as a C style string with each byte of the MPI encoded as 2 hex
digits. When using this format, @var{buflen} must be zero.
@item GCRYMPI_FMT_USG
Simple unsigned integer.
@end table
@noindent
Note that all of the above formats store the integer in big-endian
format (MSB first).
@end deftypefun
@deftypefun gcry_error_t gcry_mpi_print (@w{enum gcry_mpi_format @var{format}}, @w{unsigned char *@var{buffer}}, @w{size_t @var{buflen}}, @w{size_t *@var{nwritten}}, @w{const gcry_mpi_t @var{a}})
Convert the MPI @var{a} into an external representation described by
@var{format} (see above) and store it in the provided @var{buffer}
which has a usable length of at least the @var{buflen} bytes. If
@var{nwritten} is not NULL, it will receive the number of bytes
actually stored in @var{buffer} after a successful operation.
@end deftypefun
@deftypefun gcry_error_t gcry_mpi_aprint (@w{enum gcry_mpi_format @var{format}}, @w{unsigned char **@var{buffer}}, @w{size_t *@var{nbytes}}, @w{const gcry_mpi_t @var{a}})
Convert the MPI @var{a} into an external representation described by
@var{format} (see above) and store it in a newly allocated buffer which
address will be stored in the variable @var{buffer} points to. The
number of bytes stored in this buffer will be stored in the variable
@var{nbytes} points to, unless @var{nbytes} is @code{NULL}.
@end deftypefun
@deftypefun void gcry_mpi_dump (@w{const gcry_mpi_t @var{a}})
Dump the value of @var{a} in a format suitable for debugging to
Libgcrypt's logging stream. Note that one leading space but no trailing
space or linefeed will be printed. It is okay to pass @code{NULL} for
@var{a}.
@end deftypefun
@node Calculations
@section Calculations
@noindent
Basic arithmetic operations:
@deftypefun void gcry_mpi_add (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
@math{@var{w} = @var{u} + @var{v}}.
@end deftypefun
@deftypefun void gcry_mpi_add_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
@math{@var{w} = @var{u} + @var{v}}. Note that @var{v} is an unsigned integer.
@end deftypefun
@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}})
@math{@var{w} = @var{u} + @var{v} \bmod @var{m}}.
@end deftypefun
@deftypefun void gcry_mpi_sub (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
@math{@var{w} = @var{u} - @var{v}}.
@end deftypefun
@deftypefun void gcry_mpi_sub_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
@math{@var{w} = @var{u} - @var{v}}. @var{v} is an unsigned integer.
@end deftypefun
@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}})
@math{@var{w} = @var{u} - @var{v} \bmod @var{m}}.
@end deftypefun
@deftypefun void gcry_mpi_mul (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{gcry_mpi_t @var{v}})
@math{@var{w} = @var{u} * @var{v}}.
@end deftypefun
@deftypefun void gcry_mpi_mul_ui (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
@math{@var{w} = @var{u} * @var{v}}. @var{v} is an unsigned integer.
@end deftypefun
@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}})
@math{@var{w} = @var{u} * @var{v} \bmod @var{m}}.
@end deftypefun
@deftypefun void gcry_mpi_mul_2exp (@w{gcry_mpi_t @var{w}}, @w{gcry_mpi_t @var{u}}, @w{unsigned long @var{e}})
@c FIXME: I am in need for a real TeX{info} guru:
@c I don't know why TeX can grok @var{e} here.
@math{@var{w} = @var{u} * 2^e}.
@end deftypefun
@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}})
@math{@var{q} = @var{dividend} / @var{divisor}}, @math{@var{r} =
@var{dividend} \bmod @var{divisor}}. @var{q} and @var{r} may be passed
as @code{NULL}. @var{round} should be negative or 0.
@end deftypefun
@deftypefun void gcry_mpi_mod (@w{gcry_mpi_t @var{r}}, @w{gcry_mpi_t @var{dividend}}, @w{gcry_mpi_t @var{divisor}})
@math{@var{r} = @var{dividend} \bmod @var{divisor}}.
@end deftypefun
@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}})
@c I don't know why TeX can grok @var{e} here.
@math{@var{w} = @var{b}^e \bmod @var{m}}.
@end deftypefun
@deftypefun int gcry_mpi_gcd (@w{gcry_mpi_t @var{g}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{b}})
Set @var{g} to the greatest common divisor of @var{a} and @var{b}.
Return true if the @var{g} is 1.
@end deftypefun
@deftypefun int gcry_mpi_invm (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{gcry_mpi_t @var{m}})
Set @var{x} to the multiplicative inverse of @math{@var{a} \bmod @var{m}}.
Return true if the inverse exists.
@end deftypefun
@node Comparisons
@section Comparisons
@noindent
The next 2 functions are used to compare MPIs:
@deftypefun int gcry_mpi_cmp (@w{const gcry_mpi_t @var{u}}, @w{const gcry_mpi_t @var{v}})
Compare the multi-precision-integers number @var{u} and @var{v}
returning 0 for equality, a positive value for @var{u} > @var{v} and a
negative for @var{u} < @var{v}.
@end deftypefun
@deftypefun int gcry_mpi_cmp_ui (@w{const gcry_mpi_t @var{u}}, @w{unsigned long @var{v}})
Compare the multi-precision-integers number @var{u} with the unsigned
integer @var{v} returning 0 for equality, a positive value for @var{u} >
@var{v} and a negative for @var{u} < @var{v}.
@end deftypefun
@node Bit manipulations
@section Bit manipulations
@noindent
There are a couple of functions to get information on arbitrary bits
in an MPI and to set or clear them:
@deftypefun {unsigned int} gcry_mpi_get_nbits (@w{gcry_mpi_t @var{a}})
Return the number of bits required to represent @var{a}.
@end deftypefun
@deftypefun int gcry_mpi_test_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
Return true if bit number @var{n} (counting from 0) is set in @var{a}.
@end deftypefun
@deftypefun void gcry_mpi_set_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
Set bit number @var{n} in @var{a}.
@end deftypefun
@deftypefun void gcry_mpi_clear_bit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
Clear bit number @var{n} in @var{a}.
@end deftypefun
@deftypefun void gcry_mpi_set_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
Set bit number @var{n} in @var{a} and clear all bits greater than @var{n}.
@end deftypefun
@deftypefun void gcry_mpi_clear_highbit (@w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
Clear bit number @var{n} in @var{a} and all bits greater than @var{n}.
@end deftypefun
@deftypefun void gcry_mpi_rshift (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
Shift the value of @var{a} by @var{n} bits to the right and store the
result in @var{x}.
@end deftypefun
@deftypefun void gcry_mpi_lshift (@w{gcry_mpi_t @var{x}}, @w{gcry_mpi_t @var{a}}, @w{unsigned int @var{n}})
Shift the value of @var{a} by @var{n} bits to the left and store the
result in @var{x}.
@end deftypefun
@node Miscellaneous
@section Miscellaneous
@deftypefun gcry_mpi_t gcry_mpi_set_opaque (@w{gcry_mpi_t @var{a}}, @w{void *@var{p}}, @w{unsigned int @var{nbits}})
Store @var{nbits} of the value @var{p} points to in @var{a} and mark
@var{a} as an opaque value (i.e. an value that can't be used for any
math calculation and is only used to store an arbitrary bit pattern in
@var{a}).
WARNING: Never use an opaque MPI for actual math operations. The only
valid functions are gcry_mpi_get_opaque and gcry_mpi_release. Use
gcry_mpi_scan to convert a string of arbitrary bytes into an MPI.
@end deftypefun
@deftypefun {void *} gcry_mpi_get_opaque (@w{gcry_mpi_t @var{a}}, @w{unsigned int *@var{nbits}})
Return a pointer to an opaque value stored in @var{a} and return its
size in @var{nbits}. Note that the returned pointer is still owned by
@var{a} and that the function should never be used for an non-opaque
MPI.
@end deftypefun
@deftypefun void gcry_mpi_set_flag (@w{gcry_mpi_t @var{a}}, @w{enum gcry_mpi_flag @var{flag}})
Set the @var{flag} for the MPI @var{a}. Currently only the flag
@code{GCRYMPI_FLAG_SECURE} is allowed to convert @var{a} into an MPI
stored in "secure memory".
@end deftypefun
@deftypefun void gcry_mpi_clear_flag (@w{gcry_mpi_t @var{a}}, @w{enum gcry_mpi_flag @var{flag}})
Clear @var{flag} for the multi-precision-integers @var{a}. Note that
this function is currently useless as no flags are allowed.
@end deftypefun
@deftypefun int gcry_mpi_get_flag (@w{gcry_mpi_t @var{a}}, @w{enum gcry_mpi_flag @var{flag}})
Return true when the @var{flag} is set for @var{a}.
@end deftypefun
@deftypefun void gcry_mpi_randomize (@w{gcry_mpi_t @var{w}}, @w{unsigned int @var{nbits}}, @w{enum gcry_random_level @var{level}})
Set the multi-precision-integers @var{w} to a random value of
@var{nbits}, using random data quality of level @var{level}. In case
@var{nbits} is not a multiple of a byte, @var{nbits} is rounded up to
the next byte boundary. When using a @var{level} of
@code{GCRY_WEAK_RANDOM} this function makes use of
@code{gcry_create_nonce}.
@end deftypefun
@c **********************************************************
@c ******************** Prime numbers ***********************
@c **********************************************************
@node Prime numbers
@chapter Prime numbers
@menu
* Generation:: Generation of new prime numbers.
* Checking:: Checking if a given number is prime.
@end menu
@node Generation
@section Generation
@deftypefun gcry_error_t gcry_prime_generate (gcry_mpi_t *@var{prime},unsigned int @var{prime_bits}, unsigned int @var{factor_bits}, gcry_mpi_t **@var{factors}, gcry_prime_check_func_t @var{cb_func}, void *@var{cb_arg}, gcry_random_level_t @var{random_level}, unsigned int @var{flags})
Generate a new prime number of @var{prime_bits} bits and store it in
@var{prime}. If @var{factor_bits} is non-zero, one of the prime factors
of (@var{prime} - 1) / 2 must be @var{factor_bits} bits long. If
@var{factors} is non-zero, allocate a new, @code{NULL}-terminated array
holding the prime factors and store it in @var{factors}. @var{flags}
might be used to influence the prime number generation process.
@end deftypefun
@deftypefun gcry_error_t gcry_prime_group_generator (gcry_mpi_t *@var{r_g}, gcry_mpi_t @var{prime}, gcry_mpi_t *@var{factors}, gcry_mpi_t @var{start_g})
Find a generator for @var{prime} where the factorization of
(@var{prime}-1) is in the @code{NULL} terminated array @var{factors}.
Return the generator as a newly allocated MPI in @var{r_g}. If
@var{start_g} is not NULL, use this as the start for the search.
@end deftypefun
@deftypefun void gcry_prime_release_factors (gcry_mpi_t *@var{factors})
Convenience function to release the @var{factors} array.
@end deftypefun
@node Checking
@section Checking
@deftypefun gcry_error_t gcry_prime_check (gcry_mpi_t @var{p}, unsigned int @var{flags})
Check wether the number @var{p} is prime. Returns zero in case @var{p}
is indeed a prime, returns @code{GPG_ERR_NO_PRIME} in case @var{p} is
not a prime and a different error code in case something went horribly
wrong.
@end deftypefun
@c **********************************************************
@c ******************** Utilities ***************************
@c **********************************************************
@node Utilities
@chapter Utilities
@menu
* Memory allocation:: Functions related with memory allocation.
@end menu
@node Memory allocation
@section Memory allocation
@deftypefun {void *} gcry_malloc (size_t @var{n})
This function tries to allocate @var{n} bytes of memory. On success
it returns a pointer to the memory area, in an out-of-core condition,
it returns NULL.
@end deftypefun
@deftypefun {void *} gcry_malloc_secure (size_t @var{n})
Like @code{gcry_malloc}, but uses secure memory.
@end deftypefun
@deftypefun {void *} gcry_calloc (size_t @var{n})
This function tries to allocate @var{n} bytes of cleared memory
(i.e. memory that is initialized with zero bytes). On success it
returns a pointer to the memory area, in an out-of-core condition, it
returns NULL.
@end deftypefun
@deftypefun {void *} gcry_calloc_secure (size_t @var{n})
Like @code{gcry_calloc}, but uses secure memory.
@end deftypefun
@deftypefun {void *} gcry_realloc (void *@var{p}, size_t @var{n})
This function tries to resize the memory area pointed to by @var{p} to
@var{n} bytes. On success it returns a pointer to the new memory
area, in an out-of-core condition, it returns NULL. Depending on
whether the memory pointed to by @var{p} is secure memory or not,
gcry_realloc tries to use secure memory as well.
@end deftypefun
@deftypefun void gcry_free (void *@var{p})
Release the memory area pointed to by @var{p}.
@end deftypefun
@c **********************************************************
@c ***************** Architecure Overview *****************
@c **********************************************************
@node Architecture
@chapter Architecture
This chapter describes the internal architecture of Libgcrypt.
Libgcrypt is a function library written in ISO C-90. Any compliant
compiler should be able to build Libgcrypt as long as the target is
either a POSIX platform or compatible to the API used by Windows NT.
Provisions have been take so that the library can be directly used from
C++ applications; however building with a C++ compiler is not supported.
Building Libgcrypt is done by using the common @code{./configure && make}
approach. The configure command is included in the source distribution
and as a portable shell script it works on any Unix-alike system. The
result of running the configure script are a C header file
(@file{config.h}), customized Makefiles, the setup of symbolic links and
a few other things. After that the make tool builds and optionally
installs the library and the documentation. See the files
@file{INSTALL} and @file{README} in the source distribution on how to do
this.
Libgcrypt is developed using a Subversion@footnote{A version control
system available for many platforms} repository. Although all released
versions are tagged in this repository, they should not be used to build
production versions of Libgcrypt. Instead released tarballs should be
used. These tarballs are available from several places with the master
copy at @indicateurl{ftp://ftp.gnupg.org/gcrypt/libgcrypt/}.
Announcements of new releases are posted to the
@indicateurl{gnupg-announce@@gnupg.org} mailing list@footnote{See
@url{http://www.gnupg.org/documentation/mailing-lists.en.html} for
details.}.
@float Figure,fig:subsystems
@caption{Libgcrypt subsystems}
@center @image{libgcrypt-modules, 150mm,,Libgcrypt subsystems}
@end float
Libgcrypt consists of several subsystems (@pxref{fig:subsystems}) and
all these subsystems provide a public API; this includes the helper
subsystems like the one for S-expressions. The API style depends on the
subsystem; in general an open-use-close approach is implemented. The
open returns a handle to a context used for all further operations on
this handle, several functions may then be used on this handle and a
final close function releases all resources associated with the handle.
@menu
* Public-Key Subsystem Architecture:: About public keys.
* Symmetric Encryption Subsystem Architecture:: About standard ciphers.
* Hashing and MACing Subsystem Architecture:: About hashing.
* Multi-Precision-Integer Subsystem Architecture:: About big integers.
* Prime-Number-Generator Subsystem Architecture:: About prime numbers.
* Random-Number Subsystem Architecture:: About random stuff.
@c * Helper Subsystems Architecture:: About other stuff.
@end menu
@node Public-Key Subsystem Architecture
@section Public-Key Architecture
Libgcrypt implements two interfaces for public key cryptography: The
standard interface is PK interface using functions in the
@code{gcry_pk_} name space. The AC interface in an alternative one
which is now deprecated and will not be further described. The AC
interface is also disabled in FIPS mode.
Because public key cryptography is almost always used to process small
amounts of data (hash values or session keys), the interface is not
implemented using the open-use-close paradigm, but with single
self-contained functions. Due to the wide variety of parameters
required by different algorithms S-expressions, as flexible way to
convey these parameters, are used. There is a set of helper functions
to work with these S-expressions.
@c see @xref{S-expression Subsystem Architecture}.
Aside of functions to register new algorithms, map algorithms names to
algorithms identifiers and to lookup properties of a key, the
following main functions are available:
@table @code
@item gcry_pk_encrypt
Encrypt data using a public key.
@item gcry_pk_decrypt
Decrypt data using a private key.
@item gcry_pk_sign
Sign data using a private key.
@item gcry_pk_verify
Verify that a signature matches the data.
@item gcry_pk_testkey
Perform a consistency over a public or private key.
@item gcry_pk_genkey
Create a new public/private key pair.
@end table
With the help of the module registration system all these functions
lookup the module implementing the algorithm and pass the actual work
to that module. The parsing of the S-expression input and the
construction of S-expression for the return values is done by the high
level code (@file{cipher/pubkey.c}). Thus the internal interface
between the algorithm modules and the high level functions passes data
in a custom format. The interface to the modules is published
(@file{gcrypt-modules.h}) so that it can used to register external
implementations of algorithms with Libgcrypt. However, for some
algorithms this module interface is to limited and thus for the
internal modules an extra interface is sometimes used to convey more
information.
By default Libgcrypt uses a blinding technique for RSA decryption to
mitigate real world timing attacks over a network: Instead of using
the RSA decryption directly, a blinded value @math{y = x r^{e} \bmod n}
is decrypted and the unblinded value @math{x' = y' r^{-1} \bmod n}
returned. The blinding value @math{r} is a random value with the size
of the modulus @math{n} and generated with @code{GCRY_STRONG_RANDOM}
random level.
@node Symmetric Encryption Subsystem Architecture
@section Symmetric Encryption Subsystem Architecture
The interface to work with symmetric encryption algorithms is made up
of functions from the @code{gcry_cipher_} name space. The
implementation follows the open-use-close paradigm and uses registered
algorithm modules for the actual work. Unless a module implements
optimized cipher mode implementations, the high level code
(@file{cipher/cipher.c}) implements the modes and calls the core
algorithm functions to process each block.
The most important functions are:
@table @code
@item gcry_cipher_open
Create a new instance to encrypt or decrypt using a specified
algorithm and mode.
@item gcry_cipher_close
Release an instance.
@item gcry_cipher_setkey
Set a key to be used for encryption or decryption.
@item gcry_cipher_setiv
Set an initialization vector to be used for encryption or decryption.
@item gcry_cipher_encrypt
@itemx gcry_cipher_decrypt
Encrypt or decrypt data. These functions may be called with arbitrary
amounts of data and as often as needed to encrypt or decrypt all data.
@end table
There are also functions to query properties of algorithms or context,
like block length, key length, map names or to enable features like
padding methods.
@node Hashing and MACing Subsystem Architecture
@section Hashing and MACing Subsystem Architecture
The interface to work with message digests and CRC algorithms is made
up of functions from the @code{gcry_md_} name space. The
implementation follows the open-use-close paradigm and uses registered
algorithm modules for the actual work. Although CRC algorithms are
not considered cryptographic hash algorithms, they share enough
properties so that it makes sense to handle them in the same way.
It is possible to use several algorithms at once with one context and
thus compute them all on the same data.
The most important functions are:
@table @code
@item gcry_md_open
Create a new message digest instance and optionally enable one
algorithm. A flag may be used to turn the message digest algorithm
into a HMAC algorithm.
@item gcry_md_enable
Enable an additional algorithm for the instance.
@item gcry_md_setkey
Set the key for the MAC.
@item gcry_md_write
Pass more data for computing the message digest to an instance.
@item gcry_md_putc
Buffered version of @code{gcry_md_write} implemented as a macro.
@item gcry_md_read
Finalize the computation of the message digest or HMAC and return the
result.
@item gcry_md_close
Release an instance
@item gcry_md_hash_buffer
Convenience function to directly compute a message digest over a
memory buffer without the need to create an instance first.
@end table
There are also functions to query properties of algorithms or the
instance, like enabled algorithms, digest length, map algorithm names.
it is also possible to reset an instance or to copy the current state
of an instance at any time. Debug functions to write the hashed data
to files are available as well.
@node Multi-Precision-Integer Subsystem Architecture
@section Multi-Precision-Integer Subsystem Architecture
The implementation of Libgcrypt's big integer computation code is
based on an old release of GNU Multi-Precision Library (GMP). The
decision not to use the GMP library directly was due to stalled
development at that time and due to security requirements which could
not be provided by the code in GMP. As GMP does, Libgcrypt provides
high performance assembler implementations of low level code for
several CPUS to gain much better performance than with a generic C
implementation.
@noindent
Major features of Libgcrypt's multi-precision-integer code compared to
GMP are:
@itemize
@item
Avoidance of stack based allocations to allow protection against
swapping out of sensitive data and for easy zeroing of sensitive
intermediate results.
@item
Optional use of secure memory and tracking of its use so that results
are also put into secure memory.
@item
MPIs are identified by a handle (implemented as a pointer) to give
better control over allocations and to augment them with extra
properties like opaque data.
@item
Removal of unnecessary code to reduce complexity.
@item
Functions specialized for public key cryptography.
@end itemize
@node Prime-Number-Generator Subsystem Architecture
@section Prime-Number-Generator Subsystem Architecture
Libgcrypt provides an interface to its prime number generator. These
functions make use of the internal prime number generator which is
required for the generation for public key key pairs. The plain prime
checking function is exported as well.
The generation of random prime numbers is based on the Lim and Lee
algorithm to create practically save primes.@footnote{Chae Hoon Lim
and Pil Joong Lee. A key recovery attack on discrete log-based shemes
using a prime order subgroup. In Burton S. Kaliski Jr., editor,
Advances in Cryptology: Crypto '97, pages 249ツュ-263, Berlin /
Heidelberg / New York, 1997. Springer-Verlag. Described on page 260.}
This algorithm creates a pool of smaller primes, select a few of them
to create candidate primes of the form @math{2 * p_0 * p_1 * ... * p_n
+ 1}, tests the candidate for primality and permutates the pool until
a prime has been found. It is possible to clamp one of the small
primes to a certain size to help DSA style algorithms. Because most
of the small primes in the pool are not used for the resulting prime
number, they are saved for later use (see @code{save_pool_prime} and
@code{get_pool_prime} in @file{cipher/primegen.c}). The prime
generator optionally supports the finding of an appropriate generator.
@noindent
The primality test works in three steps:
@enumerate
@item
The standard sieve algorithm using the primes up to 4999 is used as a
quick first check.
@item
A Fermat test filters out almost all non-primes.
@item
A 5 round Rabin-Miller test is finally used. The first round uses a
witness of 2, whereas the next rounds use a random witness.
@end enumerate
@node Random-Number Subsystem Architecture
@section Random-Number Subsystem Architecture
Libgcrypt provides 3 levels or random quality: The level
@code{GCRY_VERY_STRONG_RANDOM} usually used for key generation, the
level @code{GCRY_STRONG_RANDOM} for all other strong random
requirements and the function @code{gcry_create_nonce} which is used
for weaker usages like nonces. There is also a level
@code{GCRY_WEAK_RANDOM} which in general maps to
@code{GCRY_STRONG_RANDOM} except when used with the function
@code{gcry_mpi_randomize}, where it randomizes an
multi-precision-integer using the @code{gcry_create_nonce} function.
@noindent
There are two distinct random generators available:
@itemize
@item
The Continuously Seeded Pseudo Random Number Generator (CSPRNG), which
is based on the classic GnuPG derived big pool implementation.
Implemented in @code{random/random-csprng.c} and used by default.
@item
A FIPS approved ANSI X9.31 PRNG using AES with a 128 bit key. Implemented in
@code{random/random-fips.c} and used if Libgcrypt is in FIPS mode.
@end itemize
@noindent
Both generators make use of so-called entropy gathering modules:
@table @asis
@item rndlinux
Uses the operating system provided
@file{/dev/random} and @file{/dev/urandom} devices.
@item rndunix
Runs several operating system commands to collect entropy from sources
like virtual machine and process statistics. It is a kind of
poor-man's @code{/dev/random} implementation. It is not available in
FIPS mode.
@item rndegd
Uses the operating system provided Entropy Gathering Daemon (EGD).
The EGD basically uses the same algorithms as rndunix does. However
as a system daemon it keeps on running and thus can serve several
processes requiring entropy input and does not waste collected entropy
if the application does not need all the collected entropy. It is not
available in FIPS mode.
@item rndw32
Targeted for the Microsoft Windows OS. It uses certain properties of
that system and is the only gathering module available for that OS.
@item rndhw
Extra module to collect additional entropy by utilizing a hardware
random number generator. As of now the only supported hardware RNG is
the Padlock engine of VIA (Centaur) CPUs. It is not available in FIPS
mode.
@end table
@menu
* CSPRNG Description:: Description of the CSPRNG.
* FIPS PRNG Description:: Description of the FIPS X9.31 PRNG.
@end menu
@node CSPRNG Description
@subsection Description of the CSPRNG
This random number generator is loosely modelled after the one
described in Peter Gutmann's paper: "Software Generation of
Practically Strong Random Numbers".@footnote{Also described in chapter
6 of his book "Cryptographic Security Architecture", New York, 2004,
ISBN 0-387-95387-6.}
A pool of 600 bytes is used and mixed using the core RIPE-MD160 hash
transform function. Several extra features are used to make the
robust against a wide variety of attacks and to protect against
failures of subsystems. The state of the generator may be saved to a
file and initially seed form a file.
Depending on how Libgcrypt was build the generator is able to select
the best working entropy gathering module. It makes use of the slow
and fast collection methods and requires the pool to initially seeded
form the slow gatherer or a seed file. An entropy estimation is used
to mix in enough data from the gather modules before returning the
actual random output. Process fork detection and protection is
implemented.
@c FIXME: The design and implementaion needs a more verbose description.
The implementation of the nonce generator (for
@code{gcry_create_nonce}) is a straightforward repeated hash design: A
28 byte buffer is initially seeded with the PID and the time in
seconds in the first 20 bytes and with 8 bytes of random taken from
the @code{GCRY_STRONG_RANDOM} generator. Random numbers are then
created by hashing all the 28 bytes with SHA-1 and saving that again
in the first 20 bytes. The hash is also returned as result.
@node FIPS PRNG Description
@subsection Description of the FIPS X9.31 PRNG
The core of this deterministic random number generator is implemented
according to the document ``NIST-Recommended Random Number Generator
Based on ANSI X9.31 Appendix A.2.4 Using the 3-Key Triple DES and AES
Algorithms'', dated 2005-01-31. This implementation uses the AES
variant.
The generator is based on contexts to utilize the same core functions
for all random levels as required by the high-level interface. All
random generators return their data in 128 bit blocks. If the caller
requests less bits, the extra bits are not used. The key for each
generator is only set once at the first time a generator context is
used. The seed value is set along with the key and again after 1000
output blocks.
On Unix like systems the @code{GCRY_VERY_STRONG_RANDOM} and
@code{GCRY_STRONG_RANDOM} generators are keyed and seeded using the
rndlinux module with the @file{/dev/radnom} device. Thus these
generators may block until the OS kernel has collected enough entropy.
When used with Microsoft Windows the rndw32 module is used instead.
The generator used for @code{gcry_create_nonce} is keyed and seeded
from the @code{GCRY_STRONG_RANDOM} generator. Thus is may also block
if the @code{GCRY_STRONG_RANDOM} generator has not yet been used
before and thus gets initialized on the first use by
@code{gcry_create_nonce}. This special treatment is justified by the
weaker requirements for a nonce generator and to save precious kernel
entropy for use by the ``real'' random generators.
A self-test facility uses a separate context to check the
functionality of the core X9.31 functions using a known answers test.
During runtime each output block is compared to the previous one to
detect a stucked generator.
The DT value for the generator is made up of the current time down to
microseconds (if available) and a free running 64 bit counter. When
used with the test context the DT value is taken from the context and
incremented on each use.
@c @node Helper Subsystems Architecture
@c @section Helper Subsystems Architecture
@c
@c There are a few smaller subsystems which are mainly used internally by
@c Libgcrypt but also available to applications.
@c
@c @menu
@c * S-expression Subsystem Architecture:: Details about the S-expression architecture.
@c * Memory Subsystem Architecture:: Details about the memory allocation architecture.
@c * Miscellaneous Subsystems Architecture:: Details about other subsystems.
@c @end menu
@c
@c @node S-expression Subsystem Architecture
@c @subsection S-expression Subsystem Architecture
@c
@c Libgcrypt provides an interface to S-expression to create and parse
@c them. To use an S-expression with Libgcrypt it needs first be
@c converted into the internal representation used by Libgcrypt (the type
@c @code{gcry_sexp_t}). The conversion functions support a large subset
@c of the S-expression specification and further fature a printf like
@c function to convert a list of big integers or other binary data into
@c an S-expression.
@c
@c Libgcrypt currently implements S-expressions using a tagged linked
@c list. However this is not exposed to an application and may be
@c changed in future releases to reduce overhead when already working
@c with canonically encoded S-expressions. Secure memory is supported by
@c this S-expressions implementation.
@c
@c @node Memory Subsystem Architecture
@c @subsection Memory Subsystem Architecture
@c
@c TBD.
@c
@c
@c @node Miscellaneous Subsystems Architecture
@c @subsection Miscellaneous Subsystems Architecture
@c
@c TBD.
@c
@c
@c **********************************************************
@c ******************* Appendices *************************
@c **********************************************************
@c ********************************************
@node Self-Tests
@appendix Description of the Self-Tests
In addition to the build time regression test suite, Libgcrypt
implements self-tests to be performed at runtime. Which self-tests
are actually used depends on the mode Libgcrypt is used in. In
standard mode a limited set of self-tests is run at the time an
algorithm is first used. Note that not all algorithms feature a
self-test in standard mode. The @code{GCRYCTL_SELFTEST} control
command may be used to run all implemented self-tests at any time;
this will even run more tests than those run in FIPS mode.
If any of the self-tests fails, the library immediately returns an
error code to the caller. If Libgcrypt is in FIPS mode the self-tests
will be performed within the ``Self-Test'' state and any failure puts
the library into the ``Error'' state.
@c --------------------------------
@section Power-Up Tests
Power-up tests are only performed if Libgcrypt is in FIPS mode.
@subsection Symmetric Cipher Algorithm Power-Up Tests
The following symmetric encryption algorithm tests are run during
power-up:
@table @asis
@item 3DES
To test the 3DES 3-key EDE encryption in ECB mode these tests are
run:
@enumerate
@item
A known answer test is run on a 64 bit test vector processed by 64
rounds of Single-DES block encryption and decryption using a key
changed with each round.
@item
A known answer test is run on a 64 bit test vector processed by 16
rounds of 2-key and 3-key Triple-DES block encryption and decryptions
using a key changed with each round.
@item
10 known answer tests using 3-key Triple-DES EDE encryption, comparing
the ciphertext to the known value, then running a decryption and
comparing it to the initial plaintext.
@end enumerate
(@code{cipher/des.c:selftest})
@item AES-128
A known answer tests is run using one test vector and one test
key with AES in ECB mode. (@code{cipher/rijndael.c:selftest_basic_128})
@item AES-192
A known answer tests is run using one test vector and one test
key with AES in ECB mode. (@code{cipher/rijndael.c:selftest_basic_192})
@item AES-256
A known answer tests is run using one test vector and one test key
with AES in ECB mode. (@code{cipher/rijndael.c:selftest_basic_256})
@end table
@subsection Hash Algorithm Power-Up Tests
The following hash algorithm tests are run during power-up:
@table @asis
@item SHA-1
A known answer test using the string @code{"abc"} is run.
(@code{cipher/@/sha1.c:@/selftests_sha1})
@item SHA-224
A known answer test using the string @code{"abc"} is run.
(@code{cipher/@/sha256.c:@/selftests_sha224})
@item SHA-256
A known answer test using the string @code{"abc"} is run.
(@code{cipher/@/sha256.c:@/selftests_sha256})
@item SHA-384
A known answer test using the string @code{"abc"} is run.
(@code{cipher/@/sha512.c:@/selftests_sha384})
@item SHA-512
A known answer test using the string @code{"abc"} is run.
(@code{cipher/@/sha512.c:@/selftests_sha512})
@end table
@subsection MAC Algorithm Power-Up Tests
The following MAC algorithm tests are run during power-up:
@table @asis
@item HMAC SHA-1
A known answer test using 9 byte of data and a 64 byte key is run.
(@code{cipher/hmac-tests.c:selftests_sha1})
@item HMAC SHA-224
A known answer test using 28 byte of data and a 4 byte key is run.
(@code{cipher/hmac-tests.c:selftests_sha224})
@item HMAC SHA-256
A known answer test using 28 byte of data and a 4 byte key is run.
(@code{cipher/hmac-tests.c:selftests_sha256})
@item HMAC SHA-384
A known answer test using 28 byte of data and a 4 byte key is run.
(@code{cipher/hmac-tests.c:selftests_sha384})
@item HMAC SHA-512
A known answer test using 28 byte of data and a 4 byte key is run.
(@code{cipher/hmac-tests.c:selftests_sha512})
@end table
@subsection Random Number Power-Up Test
The DRNG is tested during power-up this way:
@enumerate
@item
Requesting one block of random using the public interface to check
general working and the duplicated block detection.
@item
3 know answer tests using pre-defined keys, seed and initial DT
values. For each test 3 blocks of 16 bytes are requested and compared
to the expected result. The DT value is incremented for each block.
@end enumerate
@subsection Public Key Algorithm Power-Up Tests
The public key algorithms are tested during power-up:
@table @asis
@item RSA
A pre-defined 1024 bit RSA key is used and these tests are run
in turn:
@enumerate
@item
Conversion of S-expression to internal format.
(@code{cipher/@/rsa.c:@/selftests_rsa})
@item
Private key consistency check.
(@code{cipher/@/rsa.c:@/selftests_rsa})
@item
A pre-defined 20 byte value is signed with PKCS#1 padding for SHA-1.
The result is verified using the public key against the original data
and against modified data. (@code{cipher/@/rsa.c:@/selftest_sign_1024})
@item
A 1000 bit random value is encrypted and checked that it does not
match the orginal random value. The encrtypted result is then
decrypted and checked that it macthes the original random value.
(@code{cipher/@/rsa.c:@/selftest_encr_1024})
@end enumerate
@item DSA
A pre-defined 1024 bit DSA key is used and these tests are run in turn:
@enumerate
@item
Conversion of S-expression to internal format.
(@code{cipher/@/dsa.c:@/selftests_dsa})
@item
Private key consistency check.
(@code{cipher/@/dsa.c:@/selftests_dsa})
@item
A pre-defined 20 byte value is signed with PKCS#1 padding for
SHA-1. The result is verified using the public key against the
original data and against modified data.
(@code{cipher/@/dsa.c:@/selftest_sign_1024})
@end enumerate
@end table
@subsection Integrity Power-Up Tests
The integrity of the Libgcrypt is tested during power-up but only if
checking has been enabled at build time. The check works by computing
a HMAC SHA-256 checksum over the file used to load Libgcrypt into
memory. That checksum is compared against a checksum stored in a file
of the same name but with a single dot as a prefix and a suffix of
@file{.hmac}.
@subsection Critical Functions Power-Up Tests
The 3DES weak key detection is tested during power-up by calling the
detection function with keys taken from a table listening all weak
keys. The table itself is protected using a SHA-1 hash.
(@code{cipher/@/des.c:@/selftest})
@c --------------------------------
@section Conditional Tests
The conditional tests are performed if a certain contidion is met.
This may occur at any time; the library does not necessary enter the
``Self-Test'' state to run these tests but will transit to the
``Error'' state if a test failed.
@subsection Key-Pair Generation Tests
After an asymmetric key-pair has been generated, Libgcrypt runs a
pair-wise consistency tests on the generated key. On failure the
generated key is not used, an error code is returned and, if in FIPS
mode, the library is put into the ``Error'' state.
@table @asis
@item RSA
The test uses a random number 64 bits less the size of the modulus as
plaintext and runs an encryption and decryption operation in turn. The
encrypted value is checked to not match the plaintext and the result
of the decryption is checked to match the plaintext.
A new random number of the same size is generated, signed and verified
to test the correctness of the signing operation. As a second signing
test, the signature is modified by incrementing its value and then
verified with the expected result that the verification fails.
(@code{cipher/@/rsa.c:@/test_keys})
@item DSA
The test uses a random number of the size of the Q parameter to create
a signature and then checks that the signature verifies. As a second
signing test, the data is modified by incrementing its value and then
verified against the signature with the expected result that the
verification fails. (@code{cipher/@/dsa.c:@/test_keys})
@end table
@subsection Software Load Tests
Loading of extra modules into libgcrypt is disabled in FIPS mode and
thus no tests are
implemented. (@code{cipher/@/cipher.c:@/gcry_cipher_register},
@code{cipher/@/md.c:@/gcry_md_register},
@code{cipher/@/md.c:@/gcry_pk_register})
@subsection Manual Key Entry Tests
A manual key entry feature is not implemented in Libgcrypt.
@subsection Continuous RNG Tests
The continuous random number test is only used in FIPS mode. The RNG
generates blocks of 128 bit size; the first block generated per
context is saved in the context and another block is generated to be
returned to the caller. Each block is compared against the saved
block and then stored in the context. If a duplicated block is
detected an error is signaled and the libray is put into the
``Fatal-Error'' state.
(@code{random/@/random-fips.c:@/x931_aes_driver})
@c --------------------------------
@section Application Requested Tests
The application may requests tests at any time by means of the
@code{GCRYCTL_SELFTEST} control command. Note that using these tests
is not FIPS conform: Although Libgcrypt rejects all application
requests for services while running self-tests, it does not ensure
that no other operations of Libgcrypt are still being executed. Thus,
in FIPS mode an application requesting self-tests needs to power-cycle
Libgcrypt instead.
When self-tests are requested, Libgcrypt runs all the tests it does
during power-up as well as a few extra checks as described below.
@subsection Symmetric Cipher Algorithm Tests
The following symmetric encryption algorithm tests are run in addition
to the power-up tests:
@table @asis
@item AES-128
A known answer tests with test vectors taken from NIST SP800-38a and
using the high level functions is run for block modes CFB and OFB.
@end table
@subsection Hash Algorithm Tests
The following hash algorithm tests are run in addition to the
power-up tests:
@table @asis
@item SHA-1
@itemx SHA-224
@itemx SHA-256
@enumerate
@item
A known answer test using a 56 byte string is run.
@item
A known answer test using a string of one million letters "a" is run.
@end enumerate
(@code{cipher/@/sha1.c:@/selftests_sha1},
@code{cipher/@/sha256.c:@/selftests_sha224},
@code{cipher/@/sha256.c:@/selftests_sha256})
@item SHA-384
@item SHA-512
@enumerate
@item
A known answer test using a 112 byte string is run.
@item
A known answer test using a string of one million letters "a" is run.
@end enumerate
(@code{cipher/@/sha512.c:@/selftests_sha384},
@code{cipher/@/sha512.c:@/selftests_sha512})
@end table
@subsection MAC Algorithm Tests
The following MAC algorithm tests are run in addition to the power-up
tests:
@table @asis
@item HMAC SHA-1
@enumerate
@item
A known answer test using 9 byte of data and a 20 byte key is run.
@item
A known answer test using 9 byte of data and a 100 byte key is run.
@item
A known answer test using 9 byte of data and a 49 byte key is run.
@end enumerate
(@code{cipher/hmac-tests.c:selftests_sha1})
@item HMAC SHA-224
@itemx HMAC SHA-256
@itemx HMAC SHA-384
@itemx HMAC SHA-512
@enumerate
@item
A known answer test using 9 byte of data and a 20 byte key is run.
@item
A known answer test using 50 byte of data and a 20 byte key is run.
@item
A known answer test using 50 byte of data and a 26 byte key is run.
@item
A known answer test using 54 byte of data and a 131 byte key is run.
@item
A known answer test using 152 byte of data and a 131 byte key is run.
@end enumerate
(@code{cipher/@/hmac-tests.c:@/selftests_sha224},
@code{cipher/@/hmac-tests.c:@/selftests_sha256},
@code{cipher/@/hmac-tests.c:@/selftests_sha384},
@code{cipher/@/hmac-tests.c:@/selftests_sha512})
@end table
@c ********************************************
@node FIPS Mode
@appendix Description of the FIPS Mode
This appendix gives detailed information pertaining to the FIPS mode.
In particular, the changes to the standard mode and the finite state
machine are described. The self-tests required in this mode are
described in the appendix on self-tests.
@c -------------------------------
@section Restrictions in FIPS Mode
@noindent
If Libgcrypt is used in FIPS mode these restrictions are effective:
@itemize
@item
The cryptographic algorithms are restricted to this list:
@table @asis
@item GCRY_CIPHER_3DES
3 key EDE Triple-DES symmetric encryption.
@item GCRY_CIPHER_AES128
AES 128 bit symmetric encryption.
@item GCRY_CIPHER_AES192
AES 192 bit symmetric encryption.
@item GCRY_CIPHER_AES256
AES 256 bit symmetric encryption.
@item GCRY_MD_SHA1
SHA-1 message digest.
@item GCRY_MD_SHA224
SHA-224 message digest.
@item GCRY_MD_SHA256
SHA-256 message digest.
@item GCRY_MD_SHA384
SHA-384 message digest.
@item GCRY_MD_SHA512
SHA-512 message digest.
@item GCRY_MD_SHA1,GCRY_MD_FLAG_HMAC
HMAC using a SHA-1 message digest.
@item GCRY_MD_SHA224,GCRY_MD_FLAG_HMAC
HMAC using a SHA-224 message digest.
@item GCRY_MD_SHA256,GCRY_MD_FLAG_HMAC
HMAC using a SHA-256 message digest.
@item GCRY_MD_SHA384,GCRY_MD_FLAG_HMAC
HMAC using a SHA-384 message digest.
@item GCRY_MD_SHA512,GCRY_MD_FLAG_HMAC
HMAC using a SHA-512 message digest.
@item GCRY_PK_RSA
RSA encryption and signing.
@item GCRY_PK_DSA
DSA signing.
@end table
Note that the CRC algorithms are not considered cryptographic algorithms
and thus are in addition available.
@item
RSA and DSA key generation refuses to create a key with a keysize of
less than 1024 bits.
@item
The @code{transient-key} flag for RSA key generation is ignored.
@item
Support for the VIA Padlock engine is disabled.
@item
FIPS mode may only be used on systems with a /dev/random device.
Switching into FIPS mode on other systems will fail at runtime.
@item
Saving and loading a random seed file is ignored.
@item
An X9.31 style random number generator is used in place of the
large-pool-CSPRNG generator.
@item
The command @code{GCRYCTL_ENABLE_QUICK_RANDOM} is ignored.
@item
The Alternative Public Key Interface (@code{gcry_ac_xxx}) is not
supported and all API calls return an error.
@item
Registration of external modules is not supported.
@item
Message digest debugging is disabled.
@item
All debug output related to cryptographic data is suppressed.
@item
On-the-fly self-tests are not performed, instead self-tests are run
before entering operational state.
@item
The function @code{gcry_set_allocation_handler} may not be used. If
it is used Libgcrypt disables FIPS mode unless Enforced FIPS mode is
enabled, in which case Libgcrypt will enter the error state.
@item
In Enforced FIPS mode the command @code{GCRYCTL_DISABLE_SECMEM} is
ignored. In standard FIPS mode it disables FIPS mode.
@item
A handler set by @code{gcry_set_outofcore_handler} is ignored.
@item
A handler set by @code{gcry_set_fatalerror_handler} is ignored.
@end itemize
Note that when we speak about disabling FIPS mode, it merely means
that the fucntion @code{gcry_fips_mode_active} returns false; it does
not mean that any non FIPS algorithms are allowed.
@c ********************************************
@section FIPS Finite State Machine
The FIPS mode of libgcrypt implements a finite state machine (FSM) using
8 states (@pxref{tbl:fips-states}) and checks at runtime that only valid
transitions (@pxref{tbl:fips-state-transitions}) may happen.
@float Figure,fig:fips-fsm
@caption{FIPS mode state diagram}
@center @image{fips-fsm,150mm,,FIPS FSM Diagram}
@end float
@float Table,tbl:fips-states
@caption{FIPS mode states}
@noindent
States used by the FIPS FSM:
@table @asis
@item Power-Off
Libgcrypt is not runtime linked to another application. This usually
means that the library is not loaded into main memory. This state is
documentation only.
@item Power-On
Libgcrypt is loaded into memory and API calls may be made. Compiler
introducted constructor functions may be run. Note that Libgcrypt does
not implement any arbitrary constructor functions to be called by the
operating system
@item Init
The Libgcrypt initialization functions are performed and the library has
not yet run any self-test.
@item Self-Test
Libgcrypt is performing self-tests.
@item Operational
Libgcrypt is in the operational state and all interfaces may be used.
@item Error
Libgrypt is in the error state. When calling any FIPS relevant
interfaces they either return an error (@code{GPG_ERR_NOT_OPERATIONAL})
or put Libgcrypt into the Fatal-Error state and won't return.
@item Fatal-Error
Libgcrypt is in a non-recoverable error state and
will automatically transit into the Shutdown state.
@item Shutdown
Libgcrypt is about to be terminated and removed from the memory. The
application may at this point still runing cleanup handlers.
@end table
@end float
@float Table,tbl:fips-state-transitions
@caption{FIPS mode state transitions}
@noindent
The valid state transitions (@pxref{fig:fips-fsm}) are:
@table @code
@item 1
Power-Off to Power-On is implicitly done by the OS loading Libgcrypt as
a shared library and having it linked to an application.
@item 2
Power-On to Init is triggered by the application calling the
Libgcrypt intialization function @code{gcry_check_version}.
@item 3
Init to Self-Test is either triggred by a dedicated API call or implicit
by invoking a libgrypt service conrolled by the FSM.
@item 4
Self-Test to Operational is triggered after all self-tests passed
successfully.
@item 5
Operational to Shutdown is an artifical state without any direct action
in Libgcrypt. When reaching the Shutdown state the library is
deinitialized and can't return to any other state again.
@item 6
Shutdown to Power-off is the process of removing Libgcrypt from the
computer's memory. For obvious reasons the Power-Off state can't be
represented within Libgcrypt and thus this transition is for
documentation only.
@item 7
Operational to Error is triggered if Libgcrypt detected an application
error which can't be returned to the caller but still allows Libgcrypt
to properly run. In the Error state all FIPS relevant interfaces return
an error code.
@item 8
Error to Shutdown is similar to the Operational to Shutdown transition
(5).
@item 9
Error to Fatal-Error is triggred if Libgrypt detects an fatal error
while already being in Error state.
@item 10
Fatal-Error to Shutdown is automatically entered by Libgcrypt
after having reported the error.
@item 11
Power-On to Shutdown is an artifical state to document that Libgcrypt
has not ye been initializaed but the process is about to terminate.
@item 12
Power-On to Fatal-Error will be triggerd if certain Libgcrypt functions
are used without having reached the Init state.
@item 13
Self-Test to Fatal-Error is triggred by severe errors in Libgcrypt while
running self-tests.
@item 14
Self-Test to Error is triggred by a failed self-test.
@item 15
Operational to Fatal-Error is triggered if Libcrypt encountered a
non-recoverable error.
@item 16
Operational to Self-Test is triggred if the application requested to run
the self-tests again.
@item 17
Error to Self-Test is triggered if the application has requested to run
self-tests to get to get back into operational state after an error.
@item 18
Init to Error is triggered by errors in the initialization code.
@item 19
Init to Fatal-Error is triggered by non-recoverable errors in the
initialization code.
+@item 20
+Error to Error is triggered by errors while already in the Error
+state.
+
+
@end table
@end float
@c **********************************************************
@c ************* Appendices (license etc.) ****************
@c **********************************************************
@include lgpl.texi
@include gpl.texi
@node Figures and Tables
@unnumbered List of Figures and Tables
@listoffloats Figure
@listoffloats Table
@node Concept Index
@unnumbered Concept Index
@printindex cp
@node Function and Data Index
@unnumbered Function and Data Index
@printindex fn
@bye
GCRYCTL_SET_RANDOM_DAEMON_SOCKET
GCRYCTL_USE_RANDOM_DAEMON
The random damon is still a bit experimental, thus we do not document
them. Note that they should be used during initialization and that
these functions are not really thread safe.
@c LocalWords: int HD
diff --git a/src/ChangeLog b/src/ChangeLog
index 3371ca34..7759dbb8 100644
--- a/src/ChangeLog
+++ b/src/ChangeLog
@@ -1,2048 +1,2065 @@
+2008-09-29 Werner Koch <wk@g10code.com>
+
+ * gcrypt-module.h (GCRY_MODULE_ID_USER, GCRY_MODULE_ID_USER_LAST):
+ New.
+ * module.c (MODULE_ID_USER, MODULE_ID_USER_LAST): Define using new
+ macros.
+
+2008-09-20 Werner Koch <wk@g10code.com>
+
+ * hmac256.c (finalize) [WORDS_BIGENDIAN]: Fix sigbus problem.
+
+2008-09-18 Werner Koch <wk@g10code.com>
+
+ * cipher-proto.h (pk_ext_generate_t): Add args QBITS, NAME, DOMAIN.
+
+ * fips.c (fips_new_state): Allow Error => Error transition.
+
2008-09-18 Werner Koch <wk@g10code.com>
* gcrypt.h.in (gcry_fips_mode_active): New.
* secmem.c (_gcry_secmem_init): Factor most code out to ..
(secmem_init): .. new.
(DEFAULT_POOL_SIZE): Rename to MINIMUM_POOL_SIZE.
(STANDARD_POOL_SIZE): New.
(_gcry_secmem_malloc_internal): Don't abort if the pool is not
initialized but try to out intialize it first and only then print
an error message and return NULL. If the pool is not locked while
in FIPS mode, return NULL.
* fips.c (FIPS_FORCE_FILE): New constant. Change the file name to
"/etc/gcrypt/fips_enabled".
(enforced_fips_mode): New.
(_gcry_initialize_fips_mode): Set that flag.
(_gcry_enforced_fips_mode): New.
* global.c (inactive_fips_mode): New.
(_gcry_vcontrol): Take that flag in account for GCRYCTL_FIPS_MODE_P.
(gcry_set_allocation_handler): Take care of the enforced fips mdoe
flag.
(get_no_secure_memory): New.
(do_malloc, gcry_is_secure): Use it.
2008-09-16 Werner Koch <wk@g10code.com>
* global.c (print_config): Use y/n for fips mode.
* fips.c (fips_new_state): Allow transition to Error and
Fatal-error from Init.
2008-09-15 Werner Koch <wk@g10code.com>
* fips.c [HAVE_SYSLOG]: Include syslog.h.
(_gcry_initialize_fips_mode, lock_fsm, unlock_fsm)
(_gcry_fips_signal_error, fips_new_state)
(_gcry_fips_noreturn) [HAVE_SYSLOG]: Also log via syslog.
(check_binary_integrity) [HAVE_SYSLOG]: Log failure.
* global.h [HAVE_SYSLOG]: Include syslog.h.
(_gcry_global_is_operational) [HAVE_SYSLOG]: Print warning.
* global.c (_gcry_vcontrol): Use GCRYCTL_INITIALIZATION_FINISHED
to run power-up tests. Add unpublished control commands 58-60.
* global.c (_gcry_global_is_operational): New.
* g10lib.h (fips_is_operational): Change to call this function.
2008-09-12 Werner Koch <wk@g10code.com>
* fips.c (_gcry_fips_run_selftests): Add arg EXTENDED.
(run_cipher_selftests, run_digest_selftests, run_hmac_selftests)
(run_pubkey_selftests): Ditto.
* cipher-proto.h (selftest_func_t): Add arg EXTENDED
2008-09-11 Werner Koch <wk@g10code.com>
* fips.c: Include string.h.
(loxtoi_1, loxtoi_2, loxdigit_p): New.
(check_binary_integrity): Change the format of the expected file.
* fips.c (_gcry_fips_run_selftests): Run random tests before the
pubkey tests.
2008-09-05 Werner Koch <wk@g10code.com>
* gcrypt.h.in (GCYRCTL_SELFTEST): New.
* global.c (_gcry_vcontrol): Implement.
* fips.c (_gcry_fips_run_selftests): Do state transitions only if
in fips mode. Return an error code.
2008-09-01 Werner Koch <wk@g10code.com>
* stdmem.c: Re-indented.
2008-08-29 Werner Koch <wk@g10code.com>
* fips.c (_gcry_initialize_fips_mode): Changed /proc file to test
for FIPS mode.
* cipher-proto.h (pk_compute_keygrip_t): New.
(pk_extra_spec): Add field comp_keygrip.
2008-08-28 Werner Koch <wk@g10code.com>
* hwfeatures.c (_gcry_detect_hw_features): Disable hardware
detection in FIPS mode.
2008-08-27 Werner Koch <wk@g10code.com>
* global.c (_gcry_vcontrol): Allow running selftests from error
state.
(gcry_set_outofcore_handler): Only print a warning if used in FIPS
mode.
(gcry_xmalloc, gcry_xrealloc, gcry_xmalloc_secure, gcry_xstrdup):
Ignore an outofcore handler in FIPS mode.
* fips.c (_gcry_fips_test_error_or_operational): New.
(fips_new_state): Allow transition from error into selftest.
Disallow error to init.
2008-08-26 Werner Koch <wk@g10code.com>
* fips.c (fips_new_state): Print state transitions only at
verbosity level of 2.
(reporter): Likewise.
* cipher-proto.h (pk_ext_generate_t): New.
(pk_extra_spec): Add member ext_generate.
* cipher.h (PUBKEY_FLAG_TRANSIENT_KEY): New.
2008-08-22 Werner Koch <wk@g10code.com>
* hmac256.c (_gcry_hmac256_file): New.
(main): New option --binary.
* fips.c (check_binary_integrity): New.
(_gcry_fips_run_selftests): Run it.
* global.c (_gcry_vcontrol) <GCRYCTL_UPDATE_RANDOM_SEED_FILE>:
Check for fips operational state.
(_gcry_vcontrol) <GCRYCTL_FAST_POLL>: Ditt.
2008-08-21 Werner Koch <wk@g10code.com>
* misc.c (_gcry_log_printhex): New.
2008-08-20 Werner Koch <wk@g10code.com>
* g10lib.h (gcry_assert): New. use this at almost all places
where we used a plain assert.
* misc.c (_gcry_assert_failed): New.
(_gcry_bug): Also use func variant for ISO-C99.
2008-08-19 Werner Koch <wk@g10code.com>
* visibility.c, visibility.h (gcry_mpi_lshift): New.
* libgcrypt.vers, libgcrypt.def, gcrypt.h.in: Ditto.
2008-08-15 Werner Koch <wk@g10code.com>
* gcrypt.h.in (gcry_cipher_setkey): Replace macro by function.
(gcry_cipher_setiv): Ditto.
(gcry_cipher_setctr): Ditto.
* visibility.c (gcry_cipher_setkey, gcry_cipher_setiv)
(gcry_cipher_setctr): New.
* visibility.h (gcry_cipher_setkey, gcry_cipher_setiv)
(gcry_cipher_setctr): New.
* libgcrypt.vers (gcry_cipher_setkey, gcry_cipher_setiv)
(gcry_cipher_setctr): New.
* libgcrypt.def (gcry_cipher_setkey, gcry_cipher_setiv)
(gcry_cipher_setctr): New.
* hmac256.h, hmac256.c: New.
* Makefile.am (hmac256_SOURCES): New.
* Makefile.am (bin_PROGRAMS): Add hmac256.
* gcrypt.h.in (struct gcry_thread_cbs): Change type of OPTION to
unsigned int. Although this is a type change it does not make a
difference.
* ath.c (ath_install): Take the version of the option field in
account.
* visibility.c (gcry_pk_encrypt, gcry_pk_decrypt, gcry_pk_sign)
(gcry_pk_verify, gcry_pk_testkey, gcry_pk_genkey)
(gcry_pk_get_nbits, gcry_pk_get_keygrip)
(gcry_md_open, gcry_md_copy, gcry_md_enable)
(gcry_md_write, md_final, gcry_md_ctl, gcry_md_setkey)
(gcry_md_hash_buffer, gcry_md_get_algo, gcry_md_info)
(gcry_md_is_enabled)
(gcry_cipher_open, gcry_cipher_encrypt)
(gcry_cipher_decrypt, gcry_cipher_ctl)
(gcry_cipher_algo_info): Check whether the library is operational.
* cipher-proto.h: New.
* cipher.h: Include cipher-proto.h.
* visibility.h: Remove duplicate macro definitions. Remove
gcry_cipher_register, gcry_md_register, gcry_pk_register macros.
* visibility.c: Include cipher-proto.h.
(gcry_cipher_register): Pass dummy extra args to the internal
register function.
(gcry_md_register, gcry_pk_register): Ditto.
* g10lib.h (struct gcry_module): Add field EXTRASPEC.
* module.c (_gcry_module_add): Add arg EXTRASPEC. Changed all
callers to pass NULL.
* fips.c: New.
* gcrypt.h.in (GCRYCTL_FIPS_MODE_P): New.
* global.c (global_init): Call fips initialization.
(_gcry_vcontrol): Add GCRYCTL_FIPS_MODE_P code.
(print_config): Add config item fips-mode.
(gcry_set_allocation_handler): Do not allow the use of custom
allocation handlers.
(gcry_set_outofcore_handler): Ditto.
(_gcry_get_debug_flag): Do not return any debug flags in fips mode.
* misc.c (_gcry_logv): Signal fips error on BUG or FATAL.
(_gcry_fatal_error): Ditto.
2008-07-05 Werner Koch <wk@g10code.com>
* Makefile.am: Include librandom.la.
2008-04-18 Werner Koch <wk@g10code.com>
* missing-string.c (vasprintf): Remove. It is not used. Reported
by Simon Josefsson.
2008-03-11 Werner Koch <wk@g10code.com>
* gcrypt.h.in (gcry_ac_em_t, gcry_ac_scheme_t): Remove trailing
comma for full C-89 compatibility.
2008-01-21 Marcus Brinkmann <marcus@g10code.de>
* hwfeatures.c (detect_ia32_gnuc): Fix inline asm.
2007-12-11 Werner Koch <wk@g10code.com>
* visibility.c (gcry_md_hash_buffer): Don't use return vor a void
function. Hey, why does gcc not complain about this?
(gcry_ac_io_init_va): Ditto.
2007-12-05 Werner Koch <wk@g10code.com>
* hwfeatures.c (detect_ia32_gnuc): Depend on ENABLE_PADLOCK_SUPPORT.
2007-12-03 Werner Koch <wk@g10code.com>
* misc.c (_gcry_logv): Use abort for error levels fatal and bug as
this is more approriate for a library. Terminate the secmem
before doing so.
(_gcry_fatal_error): Terminate secmem before abort.
* secmem.c (_gcry_secmem_malloc_internal): Use log_bug instead of
exit.
2007-11-29 Werner Koch <wk@g10code.com>
* hwfeatures.c (detect_ia32_gnuc): Detect Padlock engine.
2007-11-13 Werner Koch <wk@g10code.com>
* gcrypt.h.in (_GCRY_GCC_ATTR_MALLOC): Fixed gcc version check.
Reported by Gabriele Monti.
2007-10-31 Werner Koch <wk@g10code.com>
* global.c (gcry_control): Factor most code out to ..
(_gcry_vcontrol): .. new.
* sexp.c (_gcry_sexp_vbuild): New.
* mpi.h (_gcry_mpi_set, _gcry_mpi_set_ui, _gcry_mpi_invm): Remove
prototypes as they are already in gcrypt.h.
2007-10-30 Werner Koch <wk@g10code.com>
* sexp.c (gcry_sexp_nth_string): Replace by _gcry_sexp_nth_string.
* visibility.h, visibility.c: New.
* g10lib.h: Include visibility.h instead of gcrypt.h.
* globals.c (_gcry_malloc): Rename to ..
(do_malloc): .. this.
* hwfeatures.c: New.
* global.c (global_init): Detect features.
(print_config): Print them.
2007-08-22 Werner Koch <wk@g10code.com>
* dumpsexp.c: New.
* Makefile.am (bin_PROGRAMS): Install it.
* getrandom.c (print_version): Use new standard license line.
* gcryptrnd.c (print_version): Ditto.
2007-06-06 Werner Koch <wk@g10code.com>
* gcrypt.h.in (GCRY_THREAD_OPTION_PTH_IMPL): Factror network
related code out so that the prototypes can be adjusted for W32.
(_GCRY_THREAD_OPTION_PTH_IMPL_NET): New.
2007-05-09 Werner Koch <wk@g10code.com>
* libgcrypt.m4: Print found version on success.
2007-05-09 Marcus Brinkmann <marcus@g10code.de>
* gcrypt.h.in (gcry_ac_io_t): Add name for anonymous union, and mark
all members as internal (actually: deprecated).
2007-05-04 Werner Koch <wk@g10code.com>
* Makefile.am (.rc.lo): New to replace gmake specific suffix rule.
2007-05-03 Werner Koch <wk@g10code.com>
* libgcrypt.def (gcry_sexp_nth_string): New.
* Makefile.am (EXTRA_DIST): Add libgcrypt.def.
2007-05-02 Werner Koch <wk@g10code.com>
* global.c (print_config): Print ciphers, digests and pubkeys.
2007-05-02 David Shaw <dshaw@jabberwocky.com>
* cipher.h, gcrypt.h.in: Add Camellia.
2007-04-30 Werner Koch <wk@g10code.com>
* gcrypt.h.in (GCRYCTL_PRINT_CONFIG): New.
(GCRYCTL_SET_RNDEGD_SOCKET): New.
* global.c (gcry_control): Add GCRYCTL_PRINT_CONFIG and
GCRYCTL_SET_RNDEGD_SOCKET.
(print_config): New.
* misc.c (_gcry_log_info_with_dummy_fp): New.
2007-04-18 Werner Koch <wk@g10code.com>
* gcrypt.h.in (gcry_sexp_nth_string): New.
* sexp.c (gcry_sexp_nth_data): Factored code out to ...
(sexp_nth_data): ... new.
(gcry_sexp_nth_string): New.
(gcry_sexp_nth_mpi): Reimplemented in terms of sexp_ntd_data.
2007-04-16 Werner Koch <wk@g10code.com>
* secmem.c (init_pool): Use sysconf() if available to determine
page size.
2007-03-22 Werner Koch <wk@g10code.com>
* mpi.h (mpi_mod): New.
(mpi_new, mpi_snew): New.
* gcrypt.h.in: Add GCRY_PK_ECDSA.
2007-03-16 Werner Koch <wk@g10code.com>
* gcrypt.h.in (GCRY_THREAD_OPTION_PTHREAD_IMPL): Fixed typo
introduced by me on 2006-10-23.
2007-02-22 Werner Koch <wk@g10code.com>
* gcrypt.h.in (gcry_ac_id_to_name, gcry_ac_name_to_id): Mark as
deprecated.
* libgcrypt.def (gcry_fast_random_poll): Removed - it is a macro.
(gcry_cipher_register, gcry_cipher_unregister): New.
(gcry_md_register, gcry_md_unregister): New.
(gcry_pk_register, gcry_pk_unregister): New.
(gcry_ac_data_from_sexp, gcry_ac_data_to_sexp): New.
(gcry_ac_io_init, gcry_ac_io_init_va): New.
(gcry_ac_data_encrypt_scheme, gcry_ac_data_decrypt_scheme): New.
(gcry_ac_data_sign_scheme, gcry_ac_data_verify_scheme): New.
* missing-string.c: Include stdio.h for the vsprintf prototype.
* ath.h (struct ath_ops) [_WIN32]: Use int instead of socklen_t.
2007-02-21 Werner Koch <wk@g10code.com>
* libgcrypt.def (gcry_create_nonce, gcry_fast_random_poll)
(gcry_md_debug): New.
* libgcrypt-config.in: Remove duplicates from --cflags and --libs.
Print a error for option --thread.
* gcrypt.h.in (gcry_sexp_sprint): Change BUFFER from char* to void*.
(gcry_md_ctl): Change BUFFER from unsigned char* to void*.
(gcry_md_debug): New.
(gcry_cipher_encrypt, gcry_cipher_decrypt): Change buffer args to
void*.
(gcry_randomize): Change BUFFER to void.
(gcry_create_nonce): Ditto.
* libgcrypt.vers (gcry_md_debug): New.
* sexp.c (gcry_sexp_sprint): Ditto.
(normalize): Make P unsigned.
(gcry_sexp_nth_data): Cast return value to char*.
(sexp_sscan): Fix sign/unsigned conflicts.
(whitespacep): Change P to char*.
(unquote_string): Change STRING to char*.
(convert_to_hex): Change DEST to char*.
(convert_to_string): Change DEST and P to char*.
(convert_to_token): Chnage DEST to char*.
(gcry_sexp_canon_len): Change DISPHINT to unsigned char*.
* gcrypt-module.h (gcry_pk_spec): Made ALIASES a const.
(gcry_md_write_t): Changed BUF to a const void*.
2007-02-12 Werner Koch <wk@g10code.com>
* gcrypt.h.in: Include stdlib.h for the sake fo the trheading
macros. Suggested by Andreas Metzler.
* secmem.c (ptr_into_pool_p): New.
(_gcry_private_is_secure): Implement in terms of new function.
(BLOCK_VALID): Removed. Replaced all users by new function.
2007-01-31 Werner Koch <wk@g10code.com>
* secmem.c (_gcry_private_is_secure): Fixed severe implementation
flaw. Might be the reason for some of the more obscure bugs.
(MB_WIPE_OUT): Use wipememory2.
2006-10-23 Werner Koch <wk@g10code.com>
* gcrypt.h.in (GCRY_THREAD_OPTION_PTHREAD_IMPL): Add some cast for
use by C-doubleplus. In general I don't like this but due to
public demand I give up ;-)
2006-10-19 Werner Koch <wk@g10code.com>
* global.c (gcry_control) <GCRYCTL_INIT_SECMEM>: Return an error
if the memory could not be locked.
* secmem.c (not_locked): New.
(_gcry_secmem_get_flags): Return that flag.
* secmem.h (GCRY_SECMEM_FLAG_NOT_LOCKED): New.
2006-10-05 Werner Koch <wk@g10code.com>
* module.c (_gcry_module_id_new): Don't assign modules in the range
the range of 1024..4096.
* gcrypt.h (GCRY_MD_USER, GCRY_MD_USER_LAST): New
(GCRY_PK_USER, GCRY_PK_USER_LAST): New.
(GCRY_CIPHER_USER, GCRY_CIPHER_USER_LAST): New.
2006-10-12 Marcus Brinkmann <marcus@g10code.de>
* gcrypt.h.in: Replace socklen_t with gcry_socklen_t.
2006-10-11 Marcus Brinkmann <marcus@g10code.de>
* gcrypt.h.in: Replace version by @VERSION@.
2006-10-10 Marcus Brinkmann <marcus@g10code.de>
* gcrypt.h: Add fallback type for socklen_t. Move to ...
* gcrypt.h.in: ... this file.
* Makefile.am (EXTRA_DIST): Add gcrypt.h.in.
2006-09-04 Werner Koch <wk@g10code.com>
* gcrypt.h: Removed some trailing comma in enums.
2006-08-29 Werner Koch <wk@g10code.com>
* global.c (gcry_xrealloc): Pass secure flag to outofcore handler.
* gcrypt.h (GCRY_CIPHER_SEED): New.
2006-08-21 Werner Koch <wk@g10code.com>
* gcrypt.h (GCRYCTL_FAKED_RANDOM_P): New.
2006-07-29 Marcus Brinkmann <marcus@g10code.de>
* secmem.c (init_pool): Close FD after establishing the mapping.
2006-07-12 Marcus Brinkmann <marcus@g10code.de>
* ath.c (ath_mutex_destroy): Microoptimize destruction of unused
statitically initialized mutexes. Suggested by Victor Stinner
<victor.stinner@inl.fr>.
* gcrypt.h (GCRY_THREAD_OPTION_PTHREAD_IMPL,
(GCRY_THREAD_OPTION_PTH_IMPL): Add missing initializers to
suppress gcc warning.
Submitted by Victor Stinner <victor.stinner@inl.fr>.
2006-07-04 Marcus Brinkmann <marcus@g10code.de>
* ath.c: Avoid warning about double defined type byte and other
hacks to let it build for W32 (backported from LIBGCRYPT-1-2-BRANCH).
* ath.h, gcrypt.h, tests/benchmark.c, src/types.h: Likewise.
* gcrypt.h: Revert last change, and instead:
[_WIN32 || __WIN32__]: Do not include <sys/socket.h>, but
<winsock2.h> and <ws2tcpip.h>.
Suggested by Simon Josefsson <jas@extundo.com>.
* Makefile.am (install-data-local, uninstall-local, %.lo,
(install-def-file, uninstall-def-file): New targets.
(LTRCCOMPILE, gcrypt_res, gcrypt_res_ldflag, no_undefined,
(export_symbols, gcrypt_deps): New variables.
* versioninfo.rc.in: New file.
* libgcrypt.def: New file from ../w32-dll/libgcrypt.def.
* gcrypt.h [!HAVE_SYS_SOCKET_H]: Do not include sys/socket.h, but
the appropriate windows socket header.
2006-06-21 Werner Koch <wk@g10code.com>
* global.c (gcry_xcalloc, gcry_xcalloc_secure): Made safe against
integer overflow.
* sexp.c (make_space): Return an error on out of core.
(sexp_sscan): Remove all xmalloc style calls and return proper
error codes on allocation failures.
(gcry_sexp_find_token): Ditto.
(gcry_sexp_nth):
* sexp.c (gcry_sexp_find_token): Re-indented and removed a cruft
"while(level);" which fortunately had no effect.
2006-04-28 Werner Koch <wk@g10code.com>
* gcrypt.h (GCRY_MD_SHA224): Change value from 306 to 11 to match
the use in OpenPGP. There has been no release yet, so we can
safely do it.
2006-04-22 Moritz Schulte <moritz@g10code.com>
* gcrypt.h (gcry_ctl_cmds): New commands:
GCRYCTL_SET_RANDOM_DAEMON_SOCKET, GCRYCTL_USE_RANDOM_DAEMON.
* global.c (gcry_control): Handle new commands, calling
_gcry_set_random_daemon_socket() and _gcry_use_random_daemon().
2006-04-18 Werner Koch <wk@g10code.com>
* gcrypt.h (GCRY_PK_USAGE_CERT, GCRY_PK_USAGE_AUTH)
(GCRY_PK_USAGE_UNKN): New.
2006-04-01 Moritz Schulte <moritz@g10code.com>
* gcrypt.h (gcry_ac_eme_pkcs_v1_5): Removed members: key, handle;
added member: key_size.
* secmem.c (MB_FLAG_ACTIVE): Write braces around MB_FLAG_ACTIVE
definition.
2006-03-15 Werner Koch <wk@g10code.com>
* getrandom.c: New.
2006-03-14 Werner Koch <wk@g10code.com>
* gcryptrnd.c: New.
2006-03-10 Werner Koch <wk@g10code.com>
* gcrypt.h: Add GCRY_MD_SHA224.
2005-11-02 Moritz Schulte <moritz@g10code.com>
* gcrypt.h: Update comments for functions: gcry_cipher_algo_name,
gcry_pk_algo_name.
2005-10-31 Moritz Schulte <moritz@g10code.com>
* global.c: Added documentation.
2005-10-16 Moritz Schulte <moritz@g10code.com>
* global.c (global_init): Use gcry_error_t instead of
gcry_err_code_t; use goto instead of if constructs.
* stdmem.c: Inserted description of the layered memory management
in Libgcrypt.
* g10lib.h: Removed G10_I18N_H related check; it seems to be a
GnuPG relict (Libgcrypt does not define this symbol anywhere).
(FLAG_MODULE_DISABLED): Don't forget parantheses around shifted
value.
Removed GCC_ATTR_PURE macro definitions, since gcrypt.h does
already contain such a macro named _GCRY_GCC_ATTR_PURE, which we
can use here as well.
Likewise for GCC_ATTR_MALLOC and _GCRY_GCC_ATTR_MALLOC.
* stdmem.h: Use _GCRY_GCC_ATTR_MALLOC instead of GCC_ATTR_MALLOC.
* secmem.h: Likewise.
2005-10-09 Moritz Schulte <moritz@g10code.com>
* global.c (gcry_control): Call global_init() after passing thread
cbs to ath. global_init() MUST to be called AFTER passing the cbs
to ath and BEFORE calling library functions, which make use of
ath. This change combines cbs installing with ath initialization
and thus removes the need to call other library initialization
functions inbetween like e.g. gcry_check_version().
2005-10-01 Moritz Schulte <moritz@g10code.com>
* ath.c: Assign copyright to FSF.
* ath.h: Likewise.
2005-06-25 Moritz Schulte <moritz@g10code.com>
* Makefile.am (pkgconfigdir, pkgconfig_DATA): Removed variables.
* libgcrypt.pc.in: Removed file - we do not want to support a
second, foreign configuration system.
2005-06-17 Moritz Schulte <moritz@g10code.com>
* global.c (gcry_xstrdup): Removed superfluous strcpy call.
2005-04-22 Moritz Schulte <moritz@g10code.com>
* Makefile.am (pkgconfigdir, pkgconfig_DATA): New; support for
pkgconfig provided by Albert Chin.
* libgcrypt.pc.in (Cflags): New file.
2005-04-16 Moritz Schulte <moritz@g10code.com>
* g10lib.h (_gcry_ac_init): Declare.
* global.c (global_init): Call _gcry_ac_init; don't forget to set
err.
2005-04-14 Werner Koch <wk@g10code.com>
* sexp.c (whitespacep): New.
(sexp_sscan): Replaced isdigit and isspace by whitespacep and
digitp.
2005-04-11 Moritz Schulte <moritz@g10code.com>
* gcrypt.h (gcry_md_algos): Added: GCRY_MD_WHIRLPOOL.
* cipher.h (_gcry_digest_spec_whirlpool): Declare.
2005-03-30 Moritz Schulte <moritz@g10code.com>
* libgcrypt.vers: Added: gcry_ac_io_init, gry_ac_io_init_va.
* gcrypt.h (gcry_ac_data_read_cb_t, gcry_ac_data_write_cb_t,
gcry_ac_io_mode_t, gcry_ac_io_type_t, gcry_ac_io_t): New types.
(gcry_ac_io_init_va): Declare function.
(gcry_ac_data_encode, gcry_ac_data_decode,
gcry_ac_data_encrypt_scheme, gcry_ac_data_decrypt_scheme,
gcry_ac_data_sign_scheme, gcry_ac_data_verify_scheme): Use
gcry_ac_io_type_t objects instead of memory strings directly.
2005-03-03 Moritz Schulte <moritz@g10code.com>
* libgcrypt.vers: Added: gcry_ac_data_to_sexp() and
gcry_ac_data_from_sexp().
2005-02-22 Werner Koch <wk@g10code.com>
* global.c (_gcry_malloc): Make sure ERRNO is set if we return
NULL. Remove unneeded initialization of M to allow the compiler
to catch errors.
(gcry_realloc): Make sure ERRNO is set if we return NULL>
2005-02-13 Moritz Schulte <moritz@g10code.com>
* gcrypt.h: Declare new functions: gcry_ac_data_encrypt_scheme,
gcry_ac_data_decrypt_scheme, gcry_ac_data_sign_scheme,
gcry_ac_data_verify_scheme, gcry_ac_data_encode,
gcry_ac_data_decode, gcry_ac_data_to_sexp, gcry_ac_data_from_sexp.
New types: gcry_ac_emsa_pkcs_v1_5_t, gcry_ac_ssa_pkcs_v1_5_t,
gcry_md_algo_t.
New enumeration lists: gcry_ac_scheme_t, gcry_ac_em_t.
* libgcrypt.vers: Added new ac functions.
* g10lib.h: Declare function: _gcry_pk_get_elements.
* mpi.h (mpi_get_ui): New macro.
Declare function: _gcry_mpi_get_ui.
2004-11-09 Werner Koch <wk@g10code.com>
* gcrypt.h: Removed 3 trailing commas from enums. Noted by Heiko
Stamer.
2004-09-21 Werner Koch <wk@g10code.de>
* sexp.c (sexp_sscan): Removed C++ style comments. Noted by Yoann
Vandoorselaere.
2004-08-23 Moritz Schulte <moritz@g10code.com>
* global.c: Do not include <assert.h>.
* sexp.c: Likewise.
* module.c: Likewise.
* misc.c: Likewise.
2004-08-18 Moritz Schulte <moritz@g10code.com>
* secmem.c (_gcry_secmem_init): Try to lock pool into core not
only when running with root privileges.
2004-08-16 Werner Koch <wk@g10code.de>
* secmem.h (_gcry_secmem_set_flags,_gcry_secmem_get_flags):
Removed __pure__.
(GCRY_SECMEM_FLAG_NO_WARNING): Put macro value into parens.
* secmem.c (_gcry_secmem_init): Defer printing of the warning.
2004-08-10 Moritz Schulte <moritz@g10code.com>
* gcrypt.h: Include <sys/time.h>, thanks to Simon Josefsson.
2004-05-07 Werner Koch <wk@gnupg.org>
* gcrypt.h: Added GCRYCTL_FAST_POLL.
(gcry_fast_random_poll): New.
* global.c (gcry_control) <INITIALIZATION_FINISHED>: Do only basic
random subsystem init.
(gcry_control) <FAST_POLL>: New.
2004-04-22 Marcus Brinkmann <marcus@g10code.de>
* libgcrypt.m4: Quote first argument to AC_DEFUN.
2004-04-15 Werner Koch <wk@gnupg.org>
* secmem.c (_gcry_secmem_malloc_internal): Removed old extra info
error output.
(_gcry_secmem_term): Use wipememory2 here.
* misc.c (_gcry_burn_stack): Use wipememory to avoid optimizations.
* string.c: Removed. Was never used.
* global.c (gcry_strdup): Replaced by the version from string.c
(gcry_xstrdup): Rewritten.
* gcrypt.h: Removed duplicate prototype for gcry_strdup.
2004-03-29 Werner Koch <wk@gnupg.org>
* secmem.c (_gcry_secmem_realloc): Fixed double unlock; bug
manifested itself due to the more rigorous checking in the changed
ath.h
* libgcrypt-config.in (Options): Ignore the obsolete --threads
option for now.
2004-03-17 Marcus Brinkmann <marcus@g10code.de>
* libgcrypt-config.in (includedir, libdir): Quote'em. Use
$gpg_error_cflags and $gpg_error_libs. Fix construction of
$includes.
2004-03-14 Marcus Brinkmann <marcus@g10code.de>
* libgcrypt-config.in (includedir, libdir): New variables. For
--cflags, don't test $cflags. Also check against /include for the
GNU/Hurd. Don't overwrite but extend $cflags_final. Likewise for
--libs.
2004-03-10 Marcus Brinkmann <marcus@g10code.de>
* Makefile.am (ltlib_libgcrypt_pthread, ltlib_libgcrypt_pth): Removed.
(lib_LTLIBRARIES): Remove those variables from here.
(libgcrypt_pthread_la_SOURCES, libgcrypt_pthread_la_LDFLAGS,
(libgcrypt_pthread_la_DEPENDENCIES, libgcrypt_pthread_la_LIBADD,
(libgcrypt_pth_la_SOURCES, libgcrypt_pth_la_LDFLAGS,
(libgcrypt_pth_la_DEPENDENCIES, libgcrypt_pth_la_LIBADD,
(noinst_LTLIBRARIES): Removed.
(libgcrypt_real_la_SOURCES): Merge with ...
(libgcrypt_la_SOURCES): ... likewise.
(libgcrypt_real_la_DEPENDENCIES): Merge with ...
(libgcrypt_la_DEPENDENCIES): ... this.
(libgcrypt_real_la_LIBADD): Merge with ...
(libgcrypt_la_LIBADD): ... this.
* libgcrypt-config.in (libs_pthread, libs_pth, cflags_pth)
(cflags_pthread, thread_module, thread_modules): Removed.
(Options): Remove --thread option from help output. If the option
is specified, output an error and exit.
For --cflags and --libs option, remove pth and pthread from output.
* gcrypt.h: Include <sys/types.h> and <sys/socket.h>.
(enum gcry_ctl_cmds): Add GCRYCTL_SET_THREAD_CBS.
(gcry_thread_cbs): New struct.
* global.c (gcry_control): Implement GCRYCTL_SET_THREAD_CBS.
(global_init): Don't call ath_init here.
* ath.h: Rewritten.
* ath.c: Rewritten.
2004-03-06 Werner Koch <wk@gnupg.org>
* libgcrypt-config.in: s/--soname-number/--api-version/
* libgcrypt.m4: Changed test for API version.
2004-03-05 Werner Koch <wk@gnupg.org>
* libgcrypt.m4: Optionally check the SONAME number.
* libgcrypt-config.in: Add option --soname-number
2004-03-01 Marcus Brinkmann <marcus@g10code.de>
* Makefile.am (libgcrypt_la_SOURCES): Add ath.c.
* ath.c (ath_init): Add missing function.
* Makefile.am (ath_pth_src): Removed.
(ath_pthread_src): Removed.
(libgcrypt_la_SOURCES): Remove ath-compat, $(ath_pth_src) and
$(ath_pthread_src).
* ath-compat.c, ath-pth-compat.c, ath-pthread-compat.c: Files
removed.
2004-02-20 Werner Koch <wk@gnupg.org>
* gcrypt.h (GCRY_PRIME_CHECK_AT_GOT_PRIME)
(GCRY_PRIME_CHECK_AT_FINISH),
(GCRY_PRIME_CHECK_AT_MAYBE_PRIME): New.
2004-02-18 Werner Koch <wk@gnupg.org>
* libgcrypt-config.in: Ignore setting of --prefix.
2004-02-13 Werner Koch <wk@gnupg.org>
* gcrypt.h: Added GCRY_CIPHER_RFC2268_128, alsthough not yet
supported.
2004-02-06 Werner Koch <wk@gnupg.org>
* gcrypt.h: Added GCRY_CIPHER_RFC2268_40.
2004-02-03 Werner Koch <wk@gnupg.org>
* secmem.c (_gcry_secmem_init): Do not print the "not locked into
core warning" if the NO_WARNING flag has been set.
* sexp.c (sexp_sscan): Allocate result in secure memory if BUFFER
is in secure memory. Switch to secure memory for the a secure %b
format item. Extra paranoid wipe on error.
(gcry_sexp_release): Added paranoid wiping for securely allocated
S-expressions.
2004-01-25 Moritz Schulte <mo@g10code.com>
* ath.h: Include <config.h>.
2004-01-12 Moritz Schulte <mo@g10code.com>
* gcrypt.h: Adjusted declarations of: gcry_ac_data_set,
gcry_ac_data_get_name, gcry_ac_data_get_index,
gcry_ac_key_pair_generate, gcry_ac_key_test,
gcry_ac_key_get_nbits, gcry_ac_key_get_grip.
* gcrypt.h (GCRY_AC_FLAG_DATA_NO_BLINDING): Removed symbol.
(GCRY_AC_FLAG_DEALLOC, GCRY_AC_FLAG_COPY)
(GCRY_AC_FLAG_NO_BLINDING): New symbols.
* global.c (gcry_strdup): Removed function.
* string.c: New file.
* Makefile.am (libgcrypt_real_la_SOURCES): Added: string.c.
* string.c (gcry_strdup): New function.
* gcrypt.h (gcry_strdup): Declare.
2003-12-19 Werner Koch <wk@gnupg.org>
* g10lib.h (wipememory, wipememory2): New; taken from gnupg.
2003-11-14 Werner Koch <wk@gnupg.org>
* global.c (gcry_strdup): Don't copy the string after a malloc
error.
2003-11-11 Werner Koch <wk@gnupg.org>
* sexp.c (sexp_sscan): Implemented "%b" format specifier.
2003-11-11 Moritz Schulte <mo@g10code.com>
* libgcrypt.m4: Do not set prefix when calling libgcrypt-config.
Thanks to Nikos Mavroyanopoulos.
2003-11-08 Moritz Schulte <mo@g10code.com>
* cipher.h (small_prime_numbers): Removed declaration.
(PUBKEY_FLAG_NO_BLINDING): Put braces around shift.
2003-11-04 Werner Koch <wk@gnupg.org>
* cipher.h (_gcry_sha1_has_buffer): New.
* gcrypt.h (gcry_create_nonce): New.
2003-10-31 Werner Koch <wk@gnupg.org>
* libgcrypt.vers (_gcry_generate_elg_prime): Removed this symbol;
gnutls does not need it anymore.
* secmem.c (mb_get_new): s/pool/block/ due to global pool.
* misc.c (gcry_set_log_handler): s/logf/f/ to avoid shadowing
warning against a builtin.
* ath-pth-compat.c: cast pth_connect to get rid of the const
prototype.
2003-10-27 Werner Koch <wk@gnupg.org>
* ath.h (ATH_MUTEX_INITIALIZER): Removed spurious semicolon.
2003-10-27 Moritz Schulte <mo@g10code.com>
* libgcrypt-config.in: Include libs/cflags of libgpg-error.
* sexp.c (sexp_sscan): Cleaned up, deallocate scanned sexp on
error.
* module.c (MODULE_ID_MIN): New symbol, use it.
2003-10-27 Werner Koch <wk@gnupg.org>
* gcrypt.h (gcry_pk_testkey): Doc fix.
2003-09-29 Moritz Schulte <mo@g10code.com>
* libgcrypt-config.in: Fix --algorithms option.
2003-10-23 Werner Koch <wk@gnupg.org>
* gcrypt.h (gcry_err_code): Use GPG_ERR_INLINE instead of
__inline__.
* secmem.c (lock_pool): Don't print the warning for certain
systems, handle ENOMEM.
2003-10-21 Werner Koch <wk@gnupg.org>
* secmem.c (_gcry_secmem_dump_stats): Fixed format sepcifier for a
size_t. Reported by Stephane Corthesy.
2003-10-10 Werner Koch <wk@gnupg.org>
* global.c (_gcry_malloc): Handle the no_secure_memory option.
* gcrypt.h (gcry_prime_group_generator): New.
(gcry_prime_release_factors): New.
2003-10-07 Werner Koch <wk@gnupg.org>
* sexp.c (sexp_sscan): Check that parenthesis are matching.
2003-09-28 Moritz Schulte <mo@g10code.com>
* g10lib.h: Declare: _gcry_malloc.
(GCRY_ALLOC_FLAG_SECURE): New symbol.
* global.c (_gcry_malloc): New function...
(gcry_malloc): ... use it.
(gcry_malloc_secure): Likewise.
* ath.c: Change License to LGPL.
* ath-pthread-compat.c: Likewise.
* ath-pthread.c: Likewise.
* ath-pth-compat.c: Likewise.
* ath-pth.c: Likewise.
* ath.h: Likewise.
* ath-compat.c: Likewise.
* secmem.c (_gcry_secmem_realloc): Do not forget to release secmem
lock. Thanks to low halo for triggering this bug.
2003-09-04 Werner Koch <wk@gnupg.org>
* gcrypt.h (_GCRY_ERR_SOURCE_DEFAULT): Removed cruft.
(gcry_prime_check_func_t): Renamed arg for clarity.
2003-09-02 Moritz Schulte <mo@g10code.com>
* gcrypt.h (GCRY_PRIME_FLAG_SPECIAL_FACTOR): New symbol.
2003-09-01 Moritz Schulte <mo@g10code.com>
* gcrypt.h (gcry_random_level_t): New type.
(gcry_prime_check_func_t): Likewise.
(GCRY_PRIME_FLAG_SECRET): New symbol.
(gcry_prime_generate, gcry_prime_check): Declare functions.
2003-08-28 Werner Koch <wk@gnupg.org>
* Makefile.am (libgcrypt_pth_la_LDFLAGS): Removed PTH_CFLAGS cruft.
2003-08-27 Moritz Schulte <mo@g10code.com>
* global.c (gcry_control): Remove call to ath_deinit.
* Makefile.am (libgcrypt_real_la_DEPENDENCIES): Fixed.
(libgcrypt_real_la_LIBADD): Fixed.
Removed unecessary variables.
* libgcrypt-config.in: Adjusted script for new thread handling.
* Makefile.am: New version, based on GPGMEs Makefile.am.
* ath.c, ath-compat.c, ath.h, ath-pth.c, ath-pth-compat.c,
ath-pthread.c, ath-pthread-compat.c: New files, merged from GPGME.
* ath.c, ath.h, ath-pthread.c, ath-pth.c: Removed files.
2003-08-08 Moritz Schulte <moritz@g10code.com>
* global.c (gcry_realloc): Remove FIXME about `clearing out
realloced memory', since _gcry_secmem_realloc takes care of
overwriting old memory.
2003-08-07 Werner Koch <wk@gnupg.org>
* module.c (_gcry_module_release): Don't act if module is NULL.
2003-07-30 Moritz Schulte <moritz@g10code.com>
* gcrypt.h (enum gcry_ac_id): Added: GCRY_AC_ELG_E.
Reverted change: use gcry_md_flags enumeration list instead of
defines.
2003-07-29 Werner Koch <wk@gnupg.org>
* global.c (gcry_control): Add GCRYCTL_SET_RANDOM_SEED_FILE and
GCRYCTL_UPDATE_RANDOM_SEED_FILE.
* gcrypt.h: Ditto. Renamed index to idx, so avoid warning
related to the old index function.
2003-07-28 Moritz Schulte <moritz@g10code.com>
* global.c (gcry_err_code_from_errno, gcry_err_code_to_errno)
(gcry_err_make_from_errno, gcry_error_from_errno): New functions.
* gcrypt.h: Declared: gcry_err_code_from_errno,
gcry_err_code_to_errno, gcry_err_make_from_errno,
gcry_error_from_errno.
* Makefile.am (include_HEADERS): Added: gcrypt-module.h.
* gcrypt.h: Include <gcrypt-module.h>.
* gcrypt-module.h: New file.
2003-07-27 Werner Koch <wk@gnupg.org>
* gcrypt.h (gcry_mpi_scan, gcry_mpi_print): API change.
(gcry_mpi_dump): New.
2003-07-21 Moritz Schulte <moritz@g10code.com>
* gcrypt.h: Declared: gcry_ac_key_data_get.
(gcry_pk_spec): Renamed member `sexp_names' into `aliases'.
2003-07-20 Moritz Schulte <moritz@g10code.com>
* gcrypt.h (gcry_md_oid_spec_t): New type.
(gcry_md_spec): New member: oids.
2003-07-19 Moritz Schulte <moritz@g10code.com>
* gcrypt.h (gcry_cipher_oid_spec_t): New type.
(gcry_cipher_spec): New member: oids;
2003-07-18 Werner Koch <wk@gnupg.org>
* gcrypt.h (gcry_mpi_set_opaque): Add a warning comment.
2003-07-15 Moritz Schulte <moritz@g10code.com>
* secmem.c (compress_pool): Remove function, since unused blocks
are automatically concatenad.
* gcrypt.h: Bumped version number up to 1.1.42-cvs.
2003-07-14 Moritz Schulte <moritz@g10code.com>
* gcrypt.h (gcry_cipher_spec): New member: aliases.
* Makefile.am (noinst_PROGRAMS, testapi_SOURCES, testapai_LDADD,
benchmark_SOURCES, benchmark_LDADD): Removed.
* benchmark.c, testapi.c: Removed files.
* mpi.h: Removed disabled typedef.
* g10lib.h: Likewise.
* benchmark.c, g10lib.h, gcrypt.h, global.c, module.c, sexp.c:
Used gcry_err* wrappers for libgpg-error symbols.
2003-07-12 Moritz Schulte <moritz@g10code.com>
* global.c: Likewise.
* gcrypt.h: New type: gcry_error_t, gcry_err_code_t and
gcry_err_source_t.
(gcry_err_make, gcry_error, gcry_err_code, gcry_err_source): New
functions.
* global.c (gcry_strerror): New function.
(gcry_strsource): New function.
* gcrypt.h: New symbol: GCRY_CIPHER_TWOFISH128.
2003-07-09 Moritz Schulte <moritz@g10code.com>
* gcrypt.h (enum gcry_md_flags): Removed, used define instead,
since that is more common than an enumeration list when it comes
to flags that can be bitwise ORed.
2003-07-08 Moritz Schulte <moritz@g10code.com>
* global.c: Use new types for handlers.
* gcrypt.h: Declare: gcry_ac_data_copy.
2003-07-07 Moritz Schulte <moritz@g10code.com>
* sexp.c (gcry_sexp_build_array): Use dummy argument pointer.
Thanks to Simon Josefsson <jas@extunde.com>.
* gcrypt.h: Declare: gcry_cipher_list, gcry_pk_list, gcry_md_list.
2003-07-05 Moritz Schulte <moritz@g10code.com>
* gcrypt.h: Declare: gcry_cipher_register, gcry_cipher_unregister,
gcry_md_register, gcry_md_unregister, gcry_pk_register,
gcry_pk_unregister.
(gcry_cipher_spec): Removed member: algorithm.
(gcry_pk_spec): Likewise.
(gcry_md_spec): Likewise.
Adjusted declarations: gcry_cipher_register, gcry_pk_register,
gcry_md_register.
* module.c: Replaced all occurences of `id' with `mod_id', since
`id' is a keyword in obj-c.
* gcrypt.h (gcry_cipher_spec): Renamed member `id' to `algorithm'.
(gcry_pk_spec): Likewise.
(gcry_md_spec): Likewise.
* cipher.h: Removed types: gcry_pubkey_generate_t,
gcry_pubkey_check_secret_key_t, gcry_pubkey_encrypt_t,
gcry_pubkey_decrypt_t, gcry_pubkey_sign_t, gcry_pubkey_verify_t,
gcry_pubkey_get_nbits_t, gcry_pk_spec_t, gcry_digest_init_t,
gcry_digest_write_t, gcry_digest_final_t, gcry_digest_read_t,
gcry_digest_spec_t, gcry_cipher_setkey_t, gcry_cipher_encrypt_t,
gcry_cipher_decrypt_t, gcry_cipher_stencrypt_t,
gcry_cipher_stdecrypt_t, gcry_cipher_spec_t.
* gcrypt.h: New types: gcry_pk_generate_t,
gcry_pk_check_secret_key_t, gcry_pk_encrypt_t, gcry_pk_decrypt_t,
gcry_pk_sign_t, gcry_pk_verify_t, gcry_pk_get_nbits_t,
gcry_pk_spec_t, gcry_md_init_t, gcry_md_write_t, gcry_md_final_t,
gcry_md_read_t, gcry_md_spec_t, gcry_cipher_setkey_t,
gcry_cipher_encrypt_t, gcry_cipher_decrypt_t,
gcry_cipher_stencrypt_t, gcry_cipher_stdecrypt_t,
gcry_cipher_spec_t, gcry_module_t.
2003-07-04 Moritz Schulte <moritz@g10code.com>
* module.c (_gcry_module_list): New function.
2003-07-02 Moritz Schulte <moritz@g10code.com>
* module.c (_gcry_module_lookup): Fixed typo.
* gcrypt.h: Added all definitions and declarations necessary for
the new ac interface.
2003-06-30 Moritz Schulte <moritz@g10code.com>
* g10lib.h: Added declarations: _gcry_pk_module_lookup,
_gcry_pk_module_release.
2003-06-18 Werner Koch <wk@gnupg.org>
* benchmark.c (cipher_bench): Adjusted for new API of get_blklen
and get_keylen.
* gcrypt.h (gcry_cipher_get_algo_blklen)
(gcry_cipher_get_algo_keylen): Replaced macro by funcion.
2003-06-18 Moritz Schulte <moritz@g10code.com>
* cipher.h: Renamed types GcryDigestSpec, GcryCipherSpec and
GcryPubkeySpec into: gcry_digest_spec_t, gcry_cipher_spec_t and
gcry_pubkey_spec_t.
(gcry_pubkey_spec): Defined member `id' as unsigned.
(gcry_digest_spec): Likewise.
(gcry_cipher_spec): Likewise.
* module.c (_gcry_module_id_new): New function.
(_gcry_module_add): Generate a new ID via _gcry_module_id_new in
case `id' is zero.
* g10lib.h, module.c: Replace old type GcryModule with newer one:
gcry_module_t.
* module.c (_gcry_module_add): Added argument `id', use it.
* g10lib.h: Added declaration: _gcry_module_lookup_id.
(_gcry_module_add): Added argument `id'.
* module.c (_gcry_module_lookup_id): New function.
* g10lib.h (struct gcry_module): New member: id.
* gcrypt.h: New type: gcry_handler_progress_t,
gcry_handler_alloc_t, gcry_haandler_secure_check_t,
gcry_handler_realloc_t, gcry_handler_free_t,
gcry_handler_no_mem_t, gcry_handler_error_t, gcry_handler_log_t.
Use new types.
* cipher.h: Include <gcrypt.h>.
New types: gcry_pk_generate_t, gcry_pk_check_secret_key_t,
gcry_pk_encrypt_t, gcry_pk_decrypt_t, gcry_pk_sign_t,
gcry_pk_verify_t, gcry_pk_get_nbits_t, gcry_md_init_t,
gcry_md_write_t, gcry_md_final_t, gcry_md_read_t,
gcry_cipher_setkey_t, gcry_cipher_encrypt_t,
gcry_cipher_decrypt_t, gcry_cipher_stencrypt_t,
gcry_cipher_stdecrypt_t.
Use new types.
2003-06-17 Moritz Schulte <moritz@g10code.com>
* Makefile.am (AM_CFLAGS): Added: @GPG_ERROR_CFLAGS@.
2003-06-16 Moritz Schulte <moritz@g10code.com>
* g10lib.h: Replace last occurences of old type names with newer
names (i.e. replace MPI with gcry_mpi_t).
* mpi.h: Likewise.
* sexp.c: Likewise.
2003-06-15 Moritz Schulte <moritz@g10code.com>
* testapi.c (test_genkey): Use gpg_strerror instead of
gcry_strerror.
* global.c (gcry_control): Fixed typo.
* misc.c (_gcry_fatal_error): Use gpg_strerror instead of
gcry_strerror.
* types.h (STRLIST): Removed type since it is not used.
2003-06-11 Moritz Schulte <moritz@g10code.com>
* global.c (global_init): Call: _gcry_cipher_init, _gcry_md_init,
_gcry_pk_init.
* g10lib.h: Declare: _gcry_cipher_init, _gcry_md_init,
_gcry_pk_init.
* global.c (gcry_strerror): Remove compatibility code.
* Makefile.am: Remove support libgpg-error special handling.
(AM_CPPFLAGS): Add @GPG_ERROR_CFLAGS@
* gcrypt.h: Likewise.
2003-06-13 Werner Koch <wk@gnupg.org>
* gcrypt.h (gcry_md_get_algo): Reverted to old API. This is a
convenience function anyway and error checking is not approriate.
(gcry_md_is_enabled): New.
(gcry_md_is_secure): Replaced macro by function and reverted to old
API.
2003-06-11 Werner Koch <wk@gnupg.org>
* gcrypt.h (GCRYERR): Define _GCRY_ERR_SOURCE_DEFAULT instead of
GPG_ERR_SOURCE_DEFAULT, so that libgpg-error still works despite
the use of the old gcrypt error codes.
(gcry_md_copy): Swapped arguments.
2003-06-09 Moritz Schulte <moritz@g10code.com>
* Makefile.am: Support for libgpg-error.
2003-06-08 Moritz Schulte <moritz@g10code.com>
* sexp.c (gcry_sexp_create): Expect sane error values from
gcry_sexp_canon_len instead of the `historical' values.
2003-06-07 Moritz Schulte <moritz@g10code.com>
* ath.c, ath.c, ath-pth.c, ath-pthread.c, benchmark.c, cipher.h,
g10lib.h, gcrypt.h, global.c, misc.c, missing-string.c, module.c,
mpi.h, secmem.c, secmem.h, sexp.c, stdmem.c, stdmem.h, testapi.c,
types.h: Edited all preprocessor instructions to remove whitespace
before the '#'. This is not required by C89, but there are some
compilers out there that don't like it. Replaced any occurence of
the now deprecated type names with the new ones.
* gcrypt.h: Re-organized checking for gcc features; New macro:
_GCRY_GCC_ATTR_DEPRECATED.
Include copy of libgpg-error's gpg-error.h in order to make it
easy to build libgcrypt without needing libgpg-error.h.
(GCRY_MPI, GcryMPI, GCRY_SEXP, GcrySexp, GCRY_CIPHER_HD,
GcryCipherHd, GCRY_MD_HD, GcryMDHd): Declared deprecated.
(gcry_mpi_t, gcry_sexp_t, gcry_cipher_hd_t, gcry_md_hd_t): New
types.
2003-06-04 Moritz Schulte <moritz@g10code.com>
* sexp.c (sexp_sscan): New argument: arg_list, adjusted all
callers.
(ARG_NEXT): New macro.
(sexp_sscan): Use ARG_NEXT for receiving format string arguments.
(gcry_sexp_build_array): New function.
2003-06-02 Moritz Schulte <moritz@g10code.com>
* gcrypt.h: Added some comments describing the gcry_sexp_*
functions.
Include <gpg-error.h> instead of <gpg/error.h>.
2003-06-01 Moritz Schulte <moritz@g10code.com>
* sexp.c (OLDPARSECODE): Removed macro...
(gcry_sexp_canon_len): ... and do not use it.
* gcrypt.h (gcry_errno): Removed declaration.
* g10lib.h (string_to_pubkey_algo, pubkey_algo_to_string,
pubkey_nbits): Removed declarations for non-existing functions.
2003-05-31 Moritz Schulte <moritz@g10code.com>
* cipher.h (is_RSA, is_ELGAMAL): Removed macros.
* g10lib.h (set_lasterr): Removed macro.
(_gcry_set_lasterr): Removed declaration.
* gcrypt.h: Changed declarations for: gcry_pk_algo_info,
gcry_md_open, gcry_md_copy, gcry_md_algo_info, gcry_md_info,
gcry_md_get_algo, gcry_random_add_bytes.
(gcry_md_is_secure): Adjust macro for new API.
2003-05-29 Moritz Schulte <moritz@g10code.com>
* gcrypt.h: Changed declarations for: gcry_cipher_open,
gcry_cipher_info, gcry_cipher_algo_info.
(gcry_cipher_get_algo_keylen): Adjuster for new
gcry_cipher_algo_info interface.
(gcry_cipher_get_algo_blklen): Likewise.
* global.c (gcry_errno): Removed function.
(gcry_strerror): Do not use gcry_errno.
(_gcry_set_lasterr): Removed function.
(last_ec): Removed variable.
2003-05-27 Moritz Schulte <moritz@g10code.com>
* gcrypt.h (enum gcry_cipher_algos): Make Serpent IDs do not
conflict with OpenPGP. Reported by Timo Schulz.
* global.c (gcry_control): Fixed name of enum list.
2003-05-25 Moritz Schulte <moritz@g10code.com>
* cipher.h (gcry_cipher_spec): Adjust return type of `setkey' for
libgpg-error.
(gcry_pubkey_spec): Adjust return type of `generate',
`check_secret_key', `encrypt', `decrypt', `sign' and `verify' for
libgpg-error.
* sexp.c (gcry_sexp_canon_len): Adjusted for libgpg-error.
(gcry_sexp_create): Likewise.
(gcry_sexp_new): Likewise.
(sexp_sscan): Likewise.
(gcry_sexp_build): Likewise.
(gcry_sexp_sscan): Likewise.
* module.c (_gcry_module_add): Likewise.
* global.c (last_ec): Change type to gpg_error_t.
(gcry_control): Adjust for libgpg-error.
(gcry_errno): Likewise.
(gcry_strerror): Likewise.
(_gcry_set_lasterr): Likewise.
(gcry_xmalloc): Likewise.
(gcry_xrealloc): Likewise.
2003-05-22 Moritz Schulte <moritz@g10code.com>
* types.h: Merged code from GnuPG regarding U64_C.
* missing-string.c (strsep): Removed function.
* g10lib.h: Removed declarations: strsep, strlwr.
* secmem.c (secmem_lock): New variable.
(SECMEM_LOCK, SECMEM_UNLOCK): New macros.
(_gcry_secmem_set_flags): Use SECMEM_LOCK and SECMEM_UNLOCK.
(_gcry_secmem_get_flags): Likewise.
(_gcry_secmem_init): Likewie.
(_gcry_secmem_malloc): Likewise.
(_gcry_secmem_free): Likewise.
(_gcry_secmem_malloc): Renamed to ...
(_gcry_secmem_malloc_internal): ... this.
(_gcry_secmem_malloc): New function, use SECMEM_LOCK,
SECMEM_UNLOCK, call _gcry_secmem_malloc_internal.
(_gcry_secmem_free): Renamed to ...
(_gcry_secmem_free_internal): ... this.
(_gcry_secmem_free): New function, use SECMEM_LOCK, SECMEM_UNLOCK,
call _gcry_secmem_free_internal.
(_gcry_secmem_realloc): Use SECMEM_LOCK, SECMEM_UNLOCK, call
_gcry_secmem_malloc_internal and _gcry_secmem_free_internal.
(_gcry_private_is_secure): Use SECMEM_LOCK, SECMEM_UNLOCK.
(_gcry_secmem_dump_stats): Likewise.
(_gcry_secmem_malloc_internal): Removed unused variable:
compressed.
Include "ath.h".
2003-05-21 Moritz Schulte <moritz@g10code.com>
* gcrypt.h (GCRY_CIPHER_SERPENT128, GCRY_CIPHER_SERPENT192,
GCRY_CIPHER_SERPENT256): New symbols.
2003-05-19 Moritz Schulte <moritz@g10code.com>
* gcrypt.h: Reversed changes from 2003-03-03 since they would have
been an unnecessary ABI break.
2003-05-13 Moritz Schulte <moritz@g10code.com>
* secmem.c (stats_update): New function.
(BLOCK_HEAD_SIZE): New symbol.
(MB_FLAG_ACTIVE): New symbol.
(ADDR_TO_BLOCK, BLOCK_VALID): New macros.
(mb_get_next): New function.
(mb_get_prev): New function.
(mb_merge): New function.
(mb_get_new): New function.
(unused_blocks): Removed variable.
(init_pool): Initialize new memory pool.
(_gcry_secmem_malloc): Use new heap management code.
(_gcry_secmem_free): Likewise.
(_gcry_secmem_realloc): Likewise.
Renamed type MEMBLOCK to memblock_t.
2003-04-27 Moritz Schulte <moritz@g10code.com>
* cipher.h (gcry_pubkey_spec): New member: sexp_names.
2003-04-23 Moritz Schulte <moritz@g10code.com>
* cipher.h (gcry_pubkey_spec): Removed members: npkey, nskey,
nenc, nsig.
(gcry_pubkey_spec): Added members: elements_pkey, elements_skey,
elements_enc, elements_sig, elements_grip.
2003-04-17 Moritz Schulte <moritz@g10code.com>
* g10lib.h (GcryModule): New typedef.
* gcrypt.h (gcry_cipher_register, gcry_cipher_unregister,
gcry_digest_register, gcry_digest_unregister,
gcry_pubkey_register, gcry_pubkey_unregister): Function
declarations removed - for now.
* gcrypt.h (GcryModule): Declaration removed.
* gcrypt.h (GcryPubkeySpec, GcryDigestSpec, GcryCipherSpec):
Types Moved...
* cipher.h: ... here.
2003-04-17 Moritz Schulte <moritz@g10code.com>
* cipher.h: Declare digest_spec_sha512 and digest_spec_384.
2003-04-16 Moritz Schulte <moritz@g10code.com>
* module.c (_gcry_module_use): New function.
* g10lib.h (_gcry_module_use): Declare function.
* libgcrypt-config.in: Support for --algorithms switch, which
prints the algorithms included in the built libgcrypt.
* global.c (gcry_set_progress_handler): Register progress
functions depending on the enabled algorithms.
2003-04-07 Moritz Schulte <moritz@g10code.com>
* Makefile.am (libgcrypt_la_SOURCES): Added module.c
* module.c: New file.
(_gcry_module_add): New function.
(_gcry_module_drop): New function.
(_gcry_module_lookup): New function.
(_gcry_module_release): New function.
* g10lib.h (GcryModule): New types.
(FLAG_MODULE_DISABLED): New symbol.
Added declarations for _gcry_module_add, _gcry_module_release and
_gcry_module_lookup.
* gcrypt.h: New types: GcryPubkeySpec, GcryDigestSpec,
GcryCipherSpec.
Added declarations for: gcry_cipher_register,
gcry_cipher_unregister, gcry_digest_register,
gcry_digest_unregister, gcry_pubkey_register and
gcry_pubkey_unregister.
* cipher.h: Removed symbols: CIPHER_ALGO_NONE, CIPHER_ALGO_IDEA,
CIPHER_ALGO_3DES, CIPHER_ALGO_CAST5, CIPHER_ALGO_BLOWFISH,
CIPHER_ALGO_SAFER_SK128, CIPHER_ALGO_DES_SK, CIPHER_ALGO_TWOFISH,
CIPHER_ALGO_TWOFISH_OLD, CIPHER_ALGO_DUMMY, PUBKEY_USAGE_SIG,
PUBKEY_USAGE_ENC, DIGEST_ALGO_MD5, DIGEST_ALGO_SHA1,
DIGEST_ALGO_RMD160, DIGEST_ALGO_TIGER, PUBKEY_ALGO_RSA,
PUBKEY_ALGO_RSA_E, PUBKEY_ALGO_RSA_S, PUBKEY_ALGO_DSA,
PUBKEY_ALGO_ELGAMAL, PUBKEY_ALGO_ELGAMAL_E.
2003-04-02 Moritz Schulte <moritz@g10code.com>
* benchmark.c (md_bench): Fix error message.
2003-03-31 Moritz Schulte <moritz@g10code.com>
* benchmark.c (cipher_bench): Added CTR mode.
2003-03-30 Simon Josefsson <jas@extundo.com>
* gcrypt.h (enum gcry_control_cmds): Add GCRY_SET_CTR.
(enum gcry_cipher_modes): Add GCRY_CIPHER_MODE_CTR.
(gcry_cipher_setctr): New macro to set counter.
2003-03-19 Moritz Schulte <moritz@g10code.com>
* cipher.h (PUBKEY_FLAG_NO_BLINDING): New symbol.
2003-03-22 Simon Josefsson <jas@extundo.com>
* gcrypt.h: Add GCRYCTL_SET_CBC_MAC and GCRY_CIPHER_CBC_MAC.
2003-03-19 Werner Koch <wk@gnupg.org>
* g10lib.h: Adjusted primegen.c prototypes.
2003-03-12 Werner Koch <wk@gnupg.org>
* sexp.c (sexp_sscan): Initialize NM. Thanks to Ian Peters for
valgrinding this.
2003-03-06 Moritz Schulte <mo@g10code.com>
* secmem.h (GCRY_SECMEM_FLAG_NO_WARNING,
GCRY_SECMEM_FLAG_SUSPEND_WARNING): New symbols.
* global.c (gcry_control): Use
GCRY_SECMEM_FLAG_{NO,SUSPEND}_WARNING, instead of hard-coded
values.
* secmem.c (_gcry_secmem_set_flags): Likewise.
* secmem.c (_gcry_secmem_get_flags): Likewise.
2003-03-03 Moritz Schulte <moritz@g10code.com>
* misc.c: Removed old FIXME, since there is already a function to
set the value of `verbosity_level'.
* gcrypt.h: Removed enumeration list: gcry_ctl_cmds.
New enumeration lists: gcry_global_control_cmds,
gcry_control_cmds, gcry_info_cmds, gcry_algo_info_cmds.
2003-03-02 Moritz Schulte <moritz@g10code.com>
* gcrypt.h (gcry_cipher_reset): New macro for resetting a handle.
2003-02-28 Moritz Schulte <moritz@g10code.com>
* secmem.c (DEFAULT_PAGESIZE): New symbol.
(init_pool): Use DEFAULT_PAGESIZE.
2003-02-23 Moritz Schulte <moritz@g10code.com>
* secmem.h: Fix typo in declaration of _gcry_secmem_term.
* sexp.c: Move macro definitions of `digitp', `octdigit', `alphap'
and `hexdigit' ...
* g10lib.h: ... here.
* misc.c (_gcry_burn_stack): New function (former name:
burn_stack).
* g10lib.h (burn_stack): Declare _gcry_burn_stack().
2003-01-24 Werner Koch <wk@gnupg.org>
* global.c (gcry_set_progress_handler): Register a random progress
handler.
2003-01-23 Werner Koch <wk@gnupg.org>
* gcrypt.h (GCRY_ENABLE_QUICK_RANDOM): New.
* global.c (gcry_control): Make use of it.
2003-01-21 Werner Koch <wk@gnupg.org>
* gcrypt.h (gcry_random_add_bytes): Add QUALITY argument.
2003-01-21 Timo Schulz <twoaday@freakmail.de>
* gcrypt.h (gcry_random_add_bytes): New.
2003-01-20 Simon Josefsson <jas@extundo.com>
* gcrypt.h (gcry_md_algos): Add GCRY_MD_CRC32,
GCRY_MD_CRC32_RFC1510, GCRY_MD_CRC24_RFC2440.
2003-01-16 Werner Koch <wk@gnupg.org>
* gcrypt.h (gcry_md_write): Changed type of 2nd argument to void*.
(gcry_md_hash_buffer): Changed type of both buffers to void*.
(gcry_md_setkey): Changed type of 2nd argument to void*.
(gcry_md_get_asnoid): New.
2003-01-15 Werner Koch <wk@gnupg.org>
* sexp.c (gcry_sexp_length): Fixed. This was seriously broken.
2003-01-14 Werner Koch <wk@gnupg.org>
* gcrypt.h (GCRYERR_INV_FLAG), global.c (gcry_strerror): New.
2003-01-02 Werner Koch <wk@gnupg.org>
* libgcrypt.vers: Temporary export _gcry_generate_elg_prime for
use by GNUTLS.
2002-12-21 Werner Koch <wk@gnupg.org>
* gcrypt.h: Make use of gcc's pure and malloc attributes
(gcry_md_putc): Use a helper variable to avoid multiple
evaluation of H.
* g10lib.h, stdmem.h, secmem.h: Use gcc attributes pure and malloc.
* stdmem.c (use_m_guard): Don't default to yes.
2002-12-19 Werner Koch <wk@gnupg.org>
* global.c (global_init): The meat was never run due to a faulty
check. Thanks to Nikos for pointing this out.
* global.c (gcry_control): Return 1 and not -1 for the
initialization tests.
* libgcrypt.vers: New.
* Makefile.am: Use this instead of the build symbol file.
* global.c (gcry_control) <initialization>: Call the random module
initializer to make sure that the pool lock flag has been
initialized.
2002-12-09 Werner Koch <wk@gnupg.org>
* global.c (gcry_calloc,gcry_calloc_secure): Check for overflow.
Noted by Florian Weimer.
2002-11-10 Simon Josefsson <jas@extundo.com>
* gcrypt.h (gcry_ctl_cmds): New GCRYCTL_SET_CBC_CTS control flag.
(gcry_cipher_flags): New GCRY_CIPHER_CBC_CTS gcry_cipher_open() flag.
(gcry_cipher_cts): New macro for toggling CTS.
2002-11-10 Werner Koch <wk@gnupg.org>
* gcrypt.h (GCRY_MD_MD4): New. We use a non OpenPGP value here.
2002-09-20 Werner Koch <wk@gnupg.org>
* ath.c: Include sys.time.h if sys/select.h does not exist.
(ath_select, ath_waitpid): Shortcut for Windows.
* ath.h: Include some Windows headers. By Timo.
2002-09-18 Werner Koch <wk@gnupg.org>
* ath.h: Prefix ath_deinit.
2002-09-17 Werner Koch <wk@gnupg.org>
* benchmark.c: New.
(mpi_bench, do_powm): Add a a simple test for RSA.
* global.c (global_init): New. Use it instead of the setting
any_init_done. Initialize the ATH system.
(gcry_check_version): Hook global_init in. This is the suggested
way to initialize the library.
(_gcry_no_internal_locking): Removed. We simply call a ath_deinit
and leave it to ATH to disbale the locking.
* ath.c, ath.h, ath-pth.c, ath-pthread.c: New. Taken from GPGME.
* mutex.h: Removed.
* Makefile.am (ath_components): New.
2002-09-16 Werner Koch <wk@gnupg.org>
* secmem.c (_gcry_secmem_dump_stats): Replaced fprintf by log_*.
2002-08-23 Werner Koch <wk@gnupg.org>
* missing-string.c: Removed unneeded strlwr.
* libgcrypt.m4: Made much more simple.
* libgcrypt-config.in: Made --prefix work for --libs.
2002-08-14 Werner Koch <wk@gnupg.org>
* gcrypt.h: Add GCRY_CIPGER_DES. Included string.h for size_t.
Suggested by Simon Josefsson.
2002-07-25 Werner Koch <wk@gnupg.org>
* cipher.h: Added prototypes for progress functions.
* global.c: Include cipher.h for those prototypes.
* stdmem.c (_gcry_private_realloc): Replaced void* by char * for
pointer arithmetic reasons. Noted by Stephan Austermuehle.
2002-06-24 Werner Koch <wk@gnupg.org>
* missing-string.c: Include ctype.h.
* gcrypt.h (gcry_mpi_invm, gcry_mpi_div, gcry_mpi_mod)
(gcry_mpi_swap): New.
2002-06-18 Werner Koch <wk@gnupg.org>
* gcrypt.h: Added a bunch of brief function descriptions.
2002-05-21 Werner Koch <wk@gnupg.org>
* misc.c (_gcry_log_printf): Don't initialize a va_list. Noted by
Jeff Johnson.
* global.c (gcry_set_progress_handler): New.
* gcrypt.h: Replaced the typedef for byte.
2002-05-16 Werner Koch <wk@gnupg.org>
* missing-string.c: New.
* gcrypt.h: Add new error codes GCRYERR_SEXP_ and typedefs
GcryMPI, GcrySexp, GcryCipherHd, GcryMDHd as aliases for the old
ones using an underscore.
* global.c (gcry_strerror): Add strings fro the new error codes.
* sexp.c (gcry_sexp_canon_len): Use a macro to convert from new to
old error codes.
(gcry_sexp_create,gcry_sexp_new): New.
2002-05-15 Werner Koch <wk@gnupg.org>
* mutex.h (DEFINE_LOCAL_MUTEX): Macro to define a mutex and
initialize it so that we can detect an unitialized mutex and don't
read from stdin.
2002-05-14 Werner Koch <wk@gnupg.org>
Changed license of all files to the LGPL.
2002-05-07 Werner Koch <wk@gnupg.org>
* global.c (gcry_control): Add commands
GCRYCTL_ANY_INITIALIZATION_P and GCRYCTL_INITIALIZATION_FINISHED_P
so that other libraries are able to check for required
initializations.
2002-05-02 Werner Koch <wk@gnupg.org>
* gcrypt.h (GCRYCTL_DISABLE_INTERNAL_LOCKING): New.
* global.c (gcry_control): Implement it.
(_gcry_no_internal_locking): New.
* mutex.h: Prefixed all fucntions with _gcry_. Bypass all
functions when desired.
* gcrypt.h (GCRYCTL_DISABLE_SECMEM): New.
* global.c (gcry_control,gcry_malloc_secure,gcry_is_secure):
Implement it here.
* secmem.c (_gcry_private_is_secure): Return false if the pool is
not initialized.
* gcrypt.h (GCRYCTL_INITIALIZATION_FINISHED): New.
* gcrypt.h (gcry_cipher_algos): Replaced RINDAEL by AES and change
the macros to expand from rijdael to aes.
* stdmem.c (_gcry_private_malloc): Return NULL for 0 byte allocation.
(_gcry_private_malloc_secure): Ditto.
* g10lib.h: Copied the JNLIB_GCC macros from ../jnlib/mischelp.h
and removed the inclusion of that file.
2002-04-15 Werner Koch <wk@gnupg.org>
* global.c (gcry_strdup): New.
2002-03-18 Werner Koch <wk@gnupg.org>
* mutex.h: New file with a portable thread mutex implementation
written by Marcus Brinkmann. Taken from GPGME.
2002-02-18 Werner Koch <wk@gnupg.org>
* sexp.c (gcry_sexp_sscan): Don't initialize the dummy
variable. Suggested by Jordi Mallach.
2002-01-31 Werner Koch <wk@gnupg.org>
* sexp.c (suitable_encoding,convert_to_hex,convert_to_string)
(convert_to_token): New.
(gcry_sexp_sprint): Better formatting of advanced encoding, does
now insert LFs and escapes all unprintable characters.
(unquote_string): New.
(sexp_sscan): Implemented the missing conversion of quoted strings.
2002-01-26 Werner Koch <wk@gnupg.org>
* libgcrypt-config.in: Add copyright notice.
2002-01-11 Werner Koch <wk@gnupg.org>
* sexp.c (gcry_sexp_canon_len): Fixed last change.
2002-01-01 Timo Schulz <ts@winpt.org>
* stdmem.c (_gcry_private_realloc): If pointer is NULL now realloc
behaves like malloc.
2001-12-20 Werner Koch <wk@gnupg.org>
* sexp.c (gcry_sexp_canon_len): Describe the error codes and
return an error if this is not a S-Exp; i.e. it does not start
with an open parenthesis.
2001-12-18 Werner Koch <wk@gnupg.org>
* sexp.c (gcry_sexp_canon_len): Fixed the test on NULL buffer.
* Makefile.am (DISTCLEANFILES): Include libgcrypt.sym
* sexp.c: Removed the commented test code because we now have a
test in ../tests/
2001-12-17 Werner Koch <wk@gnupg.org>
* sexp.c (gcry_sexp_canon_len): New.
2001-12-11 Werner Koch <wk@gnupg.org>
* gcrypt.h: Fixed AES128 macro, add enum for OFB mode.
2001-12-05 Werner Koch <wk@gnupg.org>
* misc.c (_gcry_log_printf): New.
* sexp.c (dump_string,gcry_sexp_dump): Use logging functions
instead of stderr.
2001-11-16 Werner Koch <wk@gnupg.org>
* gcrypt.h: New constant GCRYCTL_IS_ALGO_ENABLED.
2001-10-02 Werner Koch <wk@gnupg.org>
* gcrypt.h: Removed a couple of trailing commas.
2001-08-28 Werner Koch <wk@gnupg.org>
* sexp.c (sexp_sscan): Add an argument to enable the
arg_ptr. Changed all callers. Suggested by Tom Holroyd.
2001-08-03 Werner Koch <wk@gnupg.org>
* global.c (gcry_strerror): Updated list of error codes.
2001-07-23 Werner Koch <wk@gnupg.org>
* gcrypt.h: Replaced the last ulong. Noted by Rami Lehti.
2001-05-31 Werner Koch <wk@gnupg.org>
* gcrypt.h, mpi.h: Made some mpi functions public.
* wrapper.c: Removed.
* global.c: Renamed all g10_ prefixed functions which had wrappers
to gcry_xxx. So we now use the exported memory functions inernally.
Renamed all g10_ prefixed functions to _gcry_ prefixed ones.
* g10lib.h (_GCRYPT_IN_LIBGCRYPT): Replace defintion by a test on it.
2001-05-28 Werner Koch <wk@gnupg.org>
* libgcrypt.m4: Check GCRYPT_VERSION macro and not LIBGCRYPT_VERSION.
* mpi.h: Removed mpi_fromstr prototype.
2001-01-11 Werner Koch <wk@gnupg.org>
* Makefile.am (libgcrypt_la_SOURCES): Add mpi.h
2000-12-19 Werner Koch <wk@gnupg.org>
* types.h: Moved from ../include to here.
Major change:
Removed all GnuPG stuff and renamed this piece of software
to gcrypt.
2000-11-14 Werner Koch <wk@gnupg.org>
* mpi.h: Moved to ../mpi.
* Makefile.am (OMIT_DEPENDENCIES): Hack to work around dependency
problems.
2000-10-11 Werner Koch <wk@gnupg.org>
* mpi.h: Changed the way mpi_limb_t is defined.
2000-10-10 Werner Koch <wk@gnupg.org>
* Makefile.am: Take version-info from configure.
2000-10-09 Werner Koch <wk@gnupg.org>
* gcrypt.h: New cipher mode, new algo Arcfour and new error code
GCRYERR_INV_CIPHER_MODE.
* global.c (gcry_strerror): New errorcode.
Wed Oct 4 13:16:18 CEST 2000 Werner Koch <wk@openit.de>
* gcrypt.h (gcry_md_setkey): Replaced macro by function prototype.
Mon Sep 18 16:35:45 CEST 2000 Werner Koch <wk@openit.de>
* gcrypt.h (GCRYCTL_GET_ALGO_USAGE): New.
* secmem.c (secmem_realloc): check for failed secmem_malloc. By
Matt Kraai.
Mon Jul 31 10:04:47 CEST 2000 Werner Koch <wk@openit.de>
* sexp.c: Removed the datalen fields from list tags.
(gcry_sexp_car_data,gcry_sexp_cdr_data,gcry_sexp_car_mpi,
gcry_sexp_cdr_mpi): Removed.
(gcry_sexp_nth,gcry_sexp_nth_data,gcry_sexp_nth_mpi): New.
Fri Jul 28 18:19:11 CEST 2000 Werner Koch <wk@openit.de>
* sexp.c (sexp_sscan): Fixed reallocation to secure memory.
(new_empty_list): Removed
(gcry_sexp_length): New.
(gcry_sexp_enum): Removed.
(normalize): New. Reworked the whole thing to use NULL for an empty list.
(make_space): New instead of the macro.
Tue Jul 25 17:44:15 CEST 2000 Werner Koch <wk@openit.de>
* sexp.c: Major rewrite.
(gcry_sexp_sscan): Reordered arguments. Moved functionality to ..
(sexp_sscan): .. this.
(gcry_sexp_build): New.
(gcry_sexp_new_name_mpi, gcry_sexp_new_name_data, gcry_sexp_new_data,
gcry_sexp_new_mpi): Removed.
Fri Jul 14 19:38:23 CEST 2000 Werner Koch <wk@>
* gcrypt.h (gcry_md_start_debug, gcry_md_stop_debug): New.
(gcry_ctl_cmds): New control values
* sexp.c (gcry_sexp_sscan): Add hex format parsing.
* secmem.c (lock_pool): Check for ENOSYS return my mlock() on old SCOs.
(pool_is_mmapped): Made volatile.
(lock_pool): No more warning for QNX. By Sam Roberts.
(lock_pool,secmem_init): Additional check for dropped privs.
2000-03-21 09:18:48 Werner Koch (wk@habibti.gnupg.de)
* gcrypt.h (gcry_md_setkey): New.
(GCRY_MD_FLAG_HMAC): New.
Mon Jan 31 16:37:34 CET 2000 Werner Koch <wk@gnupg.de>
* Makefile.am: Add g10lib.h
Thu Jan 27 18:00:44 CET 2000 Werner Koch <wk@gnupg.de>
* sexp.c (gcry_sexp_sscan): Allow NULL for erroff.
Mon Jan 24 22:24:38 CET 2000 Werner Koch <wk@gnupg.de>
* sexp.c (gcry_sexp_alist): New.
Mon Jan 24 13:04:28 CET 2000 Werner Koch <wk@gnupg.de>
* secmem.c: Moved from ../util to here.
* secmem.h: New.
* stdmem.c: New. Based on the old ../util/memory.c.
* stdmem.h: New.
Wed Dec 8 21:58:32 CET 1999 Werner Koch <wk@gnupg.de>
* gcrypt.m4: New.
* gcrypt-config: New.
* mpi.h (mpi_get_nbit_info): Removed
(mpi_set_nbit_info): Removed.
(struct gcry_mpi): Removed the nbits field.
* misc.c (g10_log_verbosity): New.
* global.c (g10_xstrdup): New.
* mpiapi.c: Removed.
* mpi.h: Moved from ../include to here. Removed some obsolete
prototypes and the iobuf.h header.
* cipher.h: Moved from ../include to here. Removed the mpi.h header.
* g10lib.h: Moved from ../include to here.
Fri Nov 19 17:15:20 CET 1999 Werner Koch <wk@gnupg.de>
* sexp.c (dump_string): New. Taken from gnupg/util/miscutil.c.
(do_dump_list): s/print_string/dump_string/.
* testapi.c: New.
* mpiapi.c (gcry_mpi_randomize): Use new random API.
Sat Nov 13 17:44:23 CET 1999 Werner Koch <wk@gnupg.de>
* gloabl.c (gcry_control): Add cases for dumping random
and secmem stats.
Tue Oct 26 14:10:21 CEST 1999 Werner Koch <wk@gnupg.de>
* pkapi.c: Removed.
* symapi.c: Removed.
* g10lib.h: Moved to ../include.
* mdapi.c: Removed.
Wed Jul 7 13:08:40 CEST 1999 Werner Koch <wk@isil.d.shuttle.de>
* sexp.c: New.
Tue Dec 8 13:15:16 CET 1998 Werner Koch <wk@isil.d.shuttle.de>
* gcrypt.h: New
* mpiapi.c: New
Copyright (C) 1998,1999,2000,2001,2002,2003
2004, 2005, 2008 Free Software Foundation, Inc.
This file is free software; as a special exception the author gives
unlimited permission to copy and/or distribute it, with or without
modifications, as long as this notice is preserved.
This file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
diff --git a/src/cipher-proto.h b/src/cipher-proto.h
index 2382a68d..43ed0886 100644
--- a/src/cipher-proto.h
+++ b/src/cipher-proto.h
@@ -1,104 +1,107 @@
/* cipher-proto.h - Internal declarations
* Copyright (C) 2008 Free Software Foundation, Inc.
*
* This file is part of Libgcrypt.
*
* Libgcrypt is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser general Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* Libgcrypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
/* This file has been factored out from cipher.h so that it can be
used standalone in visibility.c . */
#ifndef G10_CIPHER_PROTO_H
#define G10_CIPHER_PROTO_H
/* Definition of a function used to report selftest failures.
DOMAIN is a string describing the function block:
"cipher", "digest", "pubkey or "random",
ALGO is the algorithm under test,
WHAT is a string describing what has been tested,
DESC is a string describing the error. */
typedef void (*selftest_report_func_t)(const char *domain,
int algo,
const char *what,
const char *errdesc);
/* Definition of the selftest functions. */
typedef gpg_err_code_t (*selftest_func_t)
(int algo, int extended, selftest_report_func_t report);
/* An extended type of the generate function. */
typedef gcry_err_code_t (*pk_ext_generate_t)
(int algo,
unsigned int nbits,
+ unsigned int qbits,
unsigned long use_e,
+ const char *name,
+ gcry_sexp_t domain,
unsigned int keygen_flags,
gcry_mpi_t *skey,
gcry_mpi_t **retfactors);
/* The type is used to compute the keygrip. */
typedef gpg_err_code_t (*pk_comp_keygrip_t)
(gcry_md_hd_t md, gcry_sexp_t keyparm);
/* Extra module specification structures. These are used for internal
modules which provide more functions than available through the
public algorithm register APIs. */
typedef struct cipher_extra_spec
{
selftest_func_t selftest;
} cipher_extra_spec_t;
typedef struct md_extra_spec
{
selftest_func_t selftest;
} md_extra_spec_t;
typedef struct pk_extra_spec
{
selftest_func_t selftest;
pk_ext_generate_t ext_generate;
pk_comp_keygrip_t comp_keygrip;
} pk_extra_spec_t;
/* The private register functions. */
gcry_error_t _gcry_cipher_register (gcry_cipher_spec_t *cipher,
cipher_extra_spec_t *extraspec,
int *algorithm_id,
gcry_module_t *module);
gcry_error_t _gcry_md_register (gcry_md_spec_t *cipher,
md_extra_spec_t *extraspec,
unsigned int *algorithm_id,
gcry_module_t *module);
gcry_error_t _gcry_pk_register (gcry_pk_spec_t *cipher,
pk_extra_spec_t *extraspec,
unsigned int *algorithm_id,
gcry_module_t *module);
/* The selftest functions. */
gcry_error_t _gcry_cipher_selftest (int algo, int extended,
selftest_report_func_t report);
gcry_error_t _gcry_md_selftest (int algo, int extended,
selftest_report_func_t report);
gcry_error_t _gcry_pk_selftest (int algo, int extended,
selftest_report_func_t report);
gcry_error_t _gcry_hmac_selftest (int algo, int extended,
selftest_report_func_t report);
gcry_error_t _gcry_random_selftest (selftest_report_func_t report);
#endif /*G10_CIPHER_PROTO_H*/
diff --git a/src/cipher.h b/src/cipher.h
index 8a4c2de1..3e0ba9d2 100644
--- a/src/cipher.h
+++ b/src/cipher.h
@@ -1,147 +1,142 @@
/* cipher.h
* Copyright (C) 1998, 2002, 2003 Free Software Foundation, Inc.
*
* This file is part of Libgcrypt.
*
* Libgcrypt is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser general Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* Libgcrypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#ifndef G10_CIPHER_H
#define G10_CIPHER_H
#include <gcrypt.h>
#define DBG_CIPHER _gcry_get_debug_flag( 1 )
#include "../random/random.h"
#define PUBKEY_FLAG_NO_BLINDING (1 << 0)
#define PUBKEY_FLAG_TRANSIENT_KEY (1 << 1)
#include "cipher-proto.h"
/*-- rmd160.c --*/
void _gcry_rmd160_hash_buffer (void *outbuf,
const void *buffer, size_t length);
/*-- sha1.c --*/
void _gcry_sha1_hash_buffer (void *outbuf,
const void *buffer, size_t length);
/*-- rijndael.c --*/
void _gcry_aes_cfb_enc (void *context, unsigned char *iv,
void *outbuf, const void *inbuf,
unsigned int nblocks);
void _gcry_aes_cfb_dec (void *context, unsigned char *iv,
void *outbuf_arg, const void *inbuf_arg,
unsigned int nblocks);
void _gcry_aes_cbc_enc (void *context, unsigned char *iv,
void *outbuf_arg, const void *inbuf_arg,
unsigned int nblocks, int cbc_mac);
void _gcry_aes_cbc_dec (void *context, unsigned char *iv,
void *outbuf_arg, const void *inbuf_arg,
unsigned int nblocks);
/*-- dsa.c --*/
void _gcry_register_pk_dsa_progress (gcry_handler_progress_t cbc, void *cb_data);
-gcry_err_code_t _gcry_dsa_generate2 (int algo, unsigned int nbits,
- unsigned int qbits,
- unsigned long dummy,
- gcry_mpi_t *skey,
- gcry_mpi_t **retfactors);
/*-- elgamal.c --*/
void _gcry_register_pk_elg_progress (gcry_handler_progress_t cb,
void *cb_data);
gcry_err_code_t _gcry_elg_generate_using_x (int algo, unsigned int nbits,
gcry_mpi_t x,
gcry_mpi_t *skey,
gcry_mpi_t **retfactors);
/*-- ecc.c --*/
void _gcry_register_pk_ecc_progress (gcry_handler_progress_t cbc,
void *cb_data);
gcry_err_code_t _gcry_ecc_generate (int algo, unsigned int nbits,
const char *curve,
gcry_mpi_t *skey, gcry_mpi_t **retfactors);
gcry_err_code_t _gcry_ecc_get_param (const char *name, gcry_mpi_t *pkey);
/*-- primegen.c --*/
void _gcry_register_primegen_progress (gcry_handler_progress_t cb,
void *cb_data);
/*-- pubkey.c --*/
const char * _gcry_pk_aliased_algo_name (int algorithm);
/* Declarations for the cipher specifications. */
extern gcry_cipher_spec_t _gcry_cipher_spec_blowfish;
extern gcry_cipher_spec_t _gcry_cipher_spec_des;
extern gcry_cipher_spec_t _gcry_cipher_spec_tripledes;
extern gcry_cipher_spec_t _gcry_cipher_spec_arcfour;
extern gcry_cipher_spec_t _gcry_cipher_spec_cast5;
extern gcry_cipher_spec_t _gcry_cipher_spec_aes;
extern gcry_cipher_spec_t _gcry_cipher_spec_aes192;
extern gcry_cipher_spec_t _gcry_cipher_spec_aes256;
extern gcry_cipher_spec_t _gcry_cipher_spec_twofish;
extern gcry_cipher_spec_t _gcry_cipher_spec_twofish128;
extern gcry_cipher_spec_t _gcry_cipher_spec_serpent128;
extern gcry_cipher_spec_t _gcry_cipher_spec_serpent192;
extern gcry_cipher_spec_t _gcry_cipher_spec_serpent256;
extern gcry_cipher_spec_t _gcry_cipher_spec_rfc2268_40;
extern gcry_cipher_spec_t _gcry_cipher_spec_seed;
extern gcry_cipher_spec_t _gcry_cipher_spec_camellia128;
extern gcry_cipher_spec_t _gcry_cipher_spec_camellia192;
extern gcry_cipher_spec_t _gcry_cipher_spec_camellia256;
extern cipher_extra_spec_t _gcry_cipher_extraspec_tripledes;
extern cipher_extra_spec_t _gcry_cipher_extraspec_aes;
extern cipher_extra_spec_t _gcry_cipher_extraspec_aes192;
extern cipher_extra_spec_t _gcry_cipher_extraspec_aes256;
/* Declarations for the digest specifications. */
extern gcry_md_spec_t _gcry_digest_spec_crc32;
extern gcry_md_spec_t _gcry_digest_spec_crc32_rfc1510;
extern gcry_md_spec_t _gcry_digest_spec_crc24_rfc2440;
extern gcry_md_spec_t _gcry_digest_spec_md4;
extern gcry_md_spec_t _gcry_digest_spec_md5;
extern gcry_md_spec_t _gcry_digest_spec_rmd160;
extern gcry_md_spec_t _gcry_digest_spec_sha1;
extern gcry_md_spec_t _gcry_digest_spec_sha224;
extern gcry_md_spec_t _gcry_digest_spec_sha256;
extern gcry_md_spec_t _gcry_digest_spec_sha512;
extern gcry_md_spec_t _gcry_digest_spec_sha384;
extern gcry_md_spec_t _gcry_digest_spec_tiger;
extern gcry_md_spec_t _gcry_digest_spec_whirlpool;
extern md_extra_spec_t _gcry_digest_extraspec_sha1;
extern md_extra_spec_t _gcry_digest_extraspec_sha224;
extern md_extra_spec_t _gcry_digest_extraspec_sha256;
extern md_extra_spec_t _gcry_digest_extraspec_sha384;
extern md_extra_spec_t _gcry_digest_extraspec_sha512;
/* Declarations for the pubkey cipher specifications. */
extern gcry_pk_spec_t _gcry_pubkey_spec_rsa;
extern gcry_pk_spec_t _gcry_pubkey_spec_elg;
extern gcry_pk_spec_t _gcry_pubkey_spec_dsa;
extern gcry_pk_spec_t _gcry_pubkey_spec_ecdsa;
extern pk_extra_spec_t _gcry_pubkey_extraspec_rsa;
extern pk_extra_spec_t _gcry_pubkey_extraspec_dsa;
extern pk_extra_spec_t _gcry_pubkey_extraspec_ecdsa;
#endif /*G10_CIPHER_H*/
diff --git a/src/dumpsexp.c b/src/dumpsexp.c
index 157c4105..8f5c0d30 100644
--- a/src/dumpsexp.c
+++ b/src/dumpsexp.c
@@ -1,611 +1,613 @@
/* dumpsexp.c - Dump S-expressions.
* Copyright (C) 2007 Free Software Foundation, Inc.
*
* Getrandom is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published
* by the Free Software Foundation; either version 2 of the License,
* or (at your option) any later version.
*
* Getrandom is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <assert.h>
#include <stdarg.h>
#include <errno.h>
#define PGM "dumpsexp"
#define MYVERSION_LINE PGM " (Libgcrypt) " VERSION
#define BUGREPORT_LINE "\nReport bugs to <bug-libgcrypt@gnupg.org>.\n"
static int verbose; /* Verbose mode. */
static int decimal; /* Print addresses in decimal. */
static int assume_hex; /* Assume input is hexencoded. */
static void
print_version (int with_help)
{
fputs (MYVERSION_LINE "\n"
"Copyright (C) 2007 Free Software Foundation, Inc.\n"
"License GPLv2+: GNU GPL version 2 or later "
"<http://www.gnu.org/licenses/old-licenses/gpl-2.0.html>\n"
"This is free software: you are free to change and redistribute it.\n"
"There is NO WARRANTY, to the extent permitted by law.\n",
stdout);
if (with_help)
fputs ("\n"
"Usage: " PGM " [OPTIONS] [file]\n"
"Debug tool for S-expressions\n"
"\n"
" --decimal Print offsets using decimal notation\n"
" --assume-hex Assume input is a hex dump\n"
" --verbose Show what we are doing\n"
" --version Print version of the program and exit\n"
" --help Display this help and exit\n"
BUGREPORT_LINE, stdout );
exit (0);
}
static int
print_usage (void)
{
fputs ("usage: " PGM " [OPTIONS] NBYTES\n", stderr);
fputs (" (use --help to display options)\n", stderr);
exit (1);
}
#define space_p(a) ((a)==' ' || (a)=='\n' || (a)=='\r' || (a)=='\t')
#define digit_p(a) ((a) >= '0' && (a) <= '9')
#define octdigit_p(a) ((a) >= '0' && (a) <= '7')
#define alpha_p(a) ( ((a) >= 'A' && (a) <= 'Z') \
|| ((a) >= 'a' && (a) <= 'z'))
#define hexdigit_p(a) (digit_p (a) \
|| ((a) >= 'A' && (a) <= 'F') \
|| ((a) >= 'a' && (a) <= 'f'))
#define xtoi_1(a) ((a) <= '9'? ((a)- '0'): \
(a) <= 'F'? ((a)-'A'+10):((a)-'a'+10))
/* Return true if P points to a byte containing a whitespace according
to the S-expressions definition. */
static inline int
whitespace_p (int c)
{
switch (c)
{
case ' ': case '\t': case '\v': case '\f': case '\r': case '\n': return 1;
default: return 0;
}
}
static void
logit (const char *format, ...)
{
va_list arg_ptr;
va_start (arg_ptr, format) ;
fputs (PGM ": ", stderr);
vfprintf (stderr, format, arg_ptr);
putc ('\n', stderr);
va_end (arg_ptr);
}
/* The raw data buffer and its current length */
static unsigned char databuffer[16];
static int databufferlen;
/* The number of bytes in databuffer which should be skipped at a flush. */
static int skipdatabufferlen;
/* The number of raw bytes printed on the last line. */
static int nbytesprinted;
/* The file offset of the current data buffer . */
static unsigned long databufferoffset;
static int
my_getc (FILE *fp)
{
int c1, c2;
if (!assume_hex)
return getc (fp);
while ( (c1=getc (fp)) != EOF && space_p (c1) )
;
if (c1 == EOF)
return EOF;
if (!hexdigit_p (c1))
{
logit ("non hex-digit encountered\n");
return EOF;
}
while ( (c2=getc (fp)) != EOF && space_p (c2) )
;
if (c2 == EOF)
{
logit ("error reading second hex nibble\n");
return EOF;
}
if (!hexdigit_p (c2))
{
logit ("second hex nibble is not a hex-digit\n");
return EOF;
}
return xtoi_1 (c1) * 16 + xtoi_1 (c2);
}
/* Flush the raw data buffer. */
static void
flushdatabuffer (void)
{
int i;
if (!databufferlen)
return;
nbytesprinted = 0;
if (decimal)
printf ("%08lu ", databufferoffset);
else
printf ("%08lx ", databufferoffset);
for (i=0; i < databufferlen; i++)
{
if (i == 8)
putchar (' ');
if (i < skipdatabufferlen)
fputs (" ", stdout);
else
{
printf (" %02x", databuffer[i]);
databufferoffset++;
}
nbytesprinted++;
}
for (; i < sizeof (databuffer); i++)
{
if (i == 8)
putchar (' ');
fputs (" ", stdout);
}
fputs (" |", stdout);
for (i=0; i < databufferlen; i++)
{
if (i < skipdatabufferlen)
putchar (' ');
else if (databuffer[i] >= ' ' && databuffer[i] <= '~'
&& databuffer[i] != '|')
putchar (databuffer[i]);
else
putchar ('.');
}
putchar ('|');
putchar ('\n');
databufferlen = 0;
skipdatabufferlen = 0;
}
/* Add C to the raw data buffer and flush as needed. */
static void
addrawdata (int c)
{
if ( databufferlen >= sizeof databuffer )
flushdatabuffer ();
databuffer[databufferlen++] = c;
}
static void
printcursor (int both)
{
int i;
flushdatabuffer ();
printf ("%8s ", "");
for (i=0; i < sizeof (databuffer); i++)
{
if (i == 8)
putchar (' ');
if (i+1 == nbytesprinted)
{
fputs (" ^ ", stdout);
if (!both)
break;
}
else
fputs (" ", stdout);
}
if (both)
{
fputs (" ", stdout);
for (i=0; i < nbytesprinted-1; i++)
putchar (' ');
putchar ('^');
}
databufferlen = skipdatabufferlen = nbytesprinted;
}
static void
printerr (const char *text)
{
printcursor (1);
printf ("\n Error: %s\n", text);
}
static void
printctl (const char *text)
{
if (verbose)
{
printcursor (0);
printf ("%s\n", text);
}
}
static void
printchr (int c)
{
+ (void)c;
}
static void
printhex (int c)
{
+ (void)c;
}
static int
parse_and_print (FILE *fp)
{
static const char tokenchars[] =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789-./_:*+=";
int c;
int level = 0;
int tokenc = 0;
int hexcount = 0;
int disphint = 0;
unsigned long datalen = 0;
char quote_buf[10];
int quote_idx = 0;
enum
{
INIT_STATE = 0, IN_NUMBER, PRE_DATA, IN_DATA, IN_STRING,
IN_ESCAPE, IN_OCT_ESC, IN_HEX_ESC,
CR_ESC, LF_ESC, IN_HEXFMT, IN_BASE64
}
state = INIT_STATE;
while ((c = my_getc (fp)) != EOF )
{
addrawdata (c);
switch (state)
{
case INIT_STATE:
if (tokenc)
{
if (strchr (tokenchars, c))
{
printchr (c);
continue;
}
tokenc = 0;
}
parse_init_state:
if (c == '(')
{
if (disphint)
{
printerr ("unmatched display hint");
disphint = 0;
}
printctl ("open");
level++;
}
else if (c == ')')
{
if (disphint)
{
printerr ("unmatched display hint");
disphint = 0;
}
printctl ("close");
level--;
}
else if (c == '\"')
{
state = IN_STRING;
printctl ("beginstring");
}
else if (c == '#')
{
state = IN_HEXFMT;
hexcount = 0;
printctl ("beginhex");
}
else if (c == '|')
{
state = IN_BASE64;
printctl ("beginbase64");
}
else if (c == '[')
{
if (disphint)
printerr ("nested display hint");
disphint = c;
}
else if (c == ']')
{
if (!disphint)
printerr ("no open display hint");
disphint = 0;
}
else if (c >= '0' && c <= '9')
{
if (c == '0')
printerr ("zero prefixed length");
state = IN_NUMBER;
datalen = (c - '0');
}
else if (strchr (tokenchars, c))
{
printchr (c);
tokenc = c;
}
else if (whitespace_p (c))
;
else if (c == '{')
{
printerr ("rescanning is not supported");
}
else if (c == '&' || c == '\\')
{
printerr ("reserved punctuation detected");
}
else
{
printerr ("bad character detected");
}
break;
case IN_NUMBER:
if (digit_p (c))
{
unsigned long tmp = datalen * 10 + (c - '0');
if (tmp < datalen)
{
printerr ("overflow in data length");
state = INIT_STATE;
datalen = 0;
}
else
datalen = tmp;
}
else if (c == ':')
{
if (!datalen)
{
printerr ("no data length");
state = INIT_STATE;
}
else
state = PRE_DATA;
}
else if (c == '\"' || c == '#' || c == '|' )
{
/* We ignore the optional length and divert to the init
state parser code. */
goto parse_init_state;
}
else
printerr ("invalid length specification");
break;
case PRE_DATA:
state = IN_DATA;
printctl ("begindata");
case IN_DATA:
if (datalen)
{
printhex (c);
datalen--;
}
if (!datalen)
{
state = INIT_STATE;
printctl ("enddata");
}
break;
case IN_STRING:
if (c == '\"')
{
printctl ("endstring");
state = INIT_STATE;
}
else if (c == '\\')
state = IN_ESCAPE;
else
printchr (c);
break;
case IN_ESCAPE:
switch (c)
{
case 'b': case 't': case 'v': case 'n': case 'f':
case 'r': case '"': case '\'': case '\\':
printhex (c);
state = IN_STRING;
break;
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7':
state = IN_OCT_ESC;
quote_idx = 0;
quote_buf[quote_idx++] = c;
break;
case 'x':
state = IN_HEX_ESC;
quote_idx = 0;
break;
case '\r':
state = CR_ESC;
break;
case '\n':
state = LF_ESC;
break;
default:
printerr ("invalid escape sequence");
state = IN_STRING;
break;
}
case IN_OCT_ESC:
state = IN_STRING;
break;
case IN_HEX_ESC:
state = IN_STRING;
break;
case CR_ESC:
state = IN_STRING;
break;
case LF_ESC:
state = IN_STRING;
break;
case IN_HEXFMT:
if (hexdigit_p (c))
{
printchr (c);
hexcount++;
}
else if (c == '#')
{
if ((hexcount & 1))
printerr ("odd number of hex digits");
printctl ("endhex");
state = INIT_STATE;
}
else if (!whitespace_p (c))
printerr ("bad hex character");
break;
case IN_BASE64:
if (c == '|')
{
printctl ("endbase64");
state = INIT_STATE;
}
else
printchr (c);
break;
default:
logit ("invalid state %d detected", state);
exit (1);
}
}
flushdatabuffer ();
if (ferror (fp))
{
logit ("error reading input: %s\n", strerror (errno));
return -1;
}
return 0;
}
int
main (int argc, char **argv)
{
int rc;
if (argc)
{
argc--; argv++;
}
while (argc && **argv == '-' && (*argv)[1] == '-')
{
if (!(*argv)[2])
{
argc--; argv++;
break;
}
else if (!strcmp (*argv, "--version"))
print_version (0);
else if (!strcmp (*argv, "--help"))
print_version (1);
else if (!strcmp (*argv, "--verbose"))
{
argc--; argv++;
verbose = 1;
}
else if (!strcmp (*argv, "--decimal"))
{
argc--; argv++;
decimal = 1;
}
else if (!strcmp (*argv, "--assume-hex"))
{
argc--; argv++;
assume_hex = 1;
}
else
print_usage ();
}
if (!argc)
{
rc = parse_and_print (stdin);
}
else
{
for (; argc; argc--)
{
FILE *fp = fopen (*argv, "rb");
if (!fp)
{
logit ("can't open `%s': %s\n", *argv, strerror (errno));
rc = 1;
}
else
{
if ( parse_and_print (fp) )
rc = 1;
fclose (fp);
}
}
}
return !rc;
}
diff --git a/src/fips.c b/src/fips.c
index 90fb3e22..0a8a15e9 100644
--- a/src/fips.c
+++ b/src/fips.c
@@ -1,797 +1,798 @@
/* fips.c - FIPS mode management
* Copyright (C) 2008 Free Software Foundation, Inc.
*
* This file is part of Libgcrypt.
*
* Libgcrypt is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* Libgcrypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#ifdef ENABLE_HMAC_BINARY_CHECK
# include <dlfcn.h>
#endif
#ifdef HAVE_SYSLOG
# include <syslog.h>
#endif /*HAVE_SYSLOG*/
#include "g10lib.h"
#include "ath.h"
#include "cipher-proto.h"
#include "hmac256.h"
/* The name of the file used to foce libgcrypt into fips mode. */
#define FIPS_FORCE_FILE "/etc/gcrypt/fips_enabled"
/* The states of the finite state machine used in fips mode. */
enum module_states
{
/* POWEROFF cannot be represented. */
STATE_POWERON = 0,
STATE_INIT,
STATE_SELFTEST,
STATE_OPERATIONAL,
STATE_ERROR,
STATE_FATALERROR,
STATE_SHUTDOWN
};
/* Flag telling whether we are in fips mode. It uses inverse logic so
that fips mode is the default unless changed by the intialization
code. To check whether fips mode is enabled, use the function
fips_mode()! */
static int no_fips_mode_required;
/* Flag to indicate that we are in the enforced FIPS mode. */
static int enforced_fips_mode;
/* This is the lock we use to protect the FSM. */
static ath_mutex_t fsm_lock = ATH_MUTEX_INITIALIZER;
/* The current state of the FSM. The whole state machinery is only
used while in fips mode. Change this only while holding fsm_lock. */
static enum module_states current_state;
static void fips_new_state (enum module_states new_state);
/* Convert lowercase hex digits; assumes valid hex digits. */
#define loxtoi_1(p) (*(p) <= '9'? (*(p)- '0'): (*(p)-'a'+10))
#define loxtoi_2(p) ((loxtoi_1(p) * 16) + loxtoi_1((p)+1))
/* Returns true if P points to a lowercase hex digit. */
#define loxdigit_p(p) !!strchr ("01234567890abcdef", *(p))
/* Check whether the OS is in FIPS mode and record that in a module
local variable. If FORCE is passed as true, fips mode will be
enabled anyway. Note: This function is not thread-safe and should
be called before any threads are created. This function may only
be called once. */
void
_gcry_initialize_fips_mode (int force)
{
static int done;
gpg_error_t err;
/* Make sure we are not accidently called twice. */
if (done)
{
if ( fips_mode () )
{
fips_new_state (STATE_FATALERROR);
fips_noreturn ();
}
/* If not in fips mode an assert is sufficient. */
gcry_assert (!done);
}
done = 1;
/* If the calling application explicitly requested fipsmode, do so. */
if (force)
{
gcry_assert (!no_fips_mode_required);
goto leave;
}
/* For testing the system it is useful to override the system
provided detection of the FIPS mode and force FIPS mode using a
file. The filename is hardwired so that there won't be any
confusion on whether /etc/gcrypt/ or /usr/local/etc/gcrypt/ is
actually used. The file itself may be empty. */
if ( !access (FIPS_FORCE_FILE, F_OK) )
{
gcry_assert (!no_fips_mode_required);
goto leave;
}
/* Checking based on /proc file properties. */
{
FILE *fp;
int saved_errno;
static const char const procfname[] = "/proc/sys/crypto/fips_enabled";
fp = fopen (procfname, "r");
if (fp)
{
char line[256];
if (fgets (line, sizeof line, fp) && atoi (line))
{
/* System is in fips mode. */
fclose (fp);
gcry_assert (!no_fips_mode_required);
goto leave;
}
fclose (fp);
}
else if ((saved_errno = errno) != ENOENT
&& !access ("/proc/version", F_OK) )
{
/* Problem reading the fips file despite that we have the proc
file system. We better stop right away. */
log_info ("FATAL: error reading `%s' in libgcrypt: %s\n",
procfname, strerror (saved_errno));
#ifdef HAVE_SYSLOG
syslog (LOG_USER|LOG_ERR, "Libgcrypt error: "
"reading `%s' failed: %s - abort",
procfname, strerror (saved_errno));
#endif /*HAVE_SYSLOG*/
abort ();
}
}
/* Fips not not requested, set flag. */
no_fips_mode_required = 1;
leave:
if (!no_fips_mode_required)
{
/* Yes, we are in FIPS mode. */
FILE *fp;
/* Intitialize the lock to protect the FSM. */
err = ath_mutex_init (&fsm_lock);
if (err)
{
/* If that fails we can't do anything but abort the
process. We need to use log_info so that the FSM won't
get involved. */
log_info ("FATAL: failed to create the FSM lock in libgcrypt: %s\n",
strerror (err));
#ifdef HAVE_SYSLOG
syslog (LOG_USER|LOG_ERR, "Libgcrypt error: "
"creating FSM lock failed: %s - abort",
strerror (err));
#endif /*HAVE_SYSLOG*/
abort ();
}
/* If the FIPS force files exists, is readable and has a number
!= 0 on its first line, we enable the enforced fips mode. */
fp = fopen (FIPS_FORCE_FILE, "r");
if (fp)
{
char line[256];
if (fgets (line, sizeof line, fp) && atoi (line))
enforced_fips_mode = 1;
fclose (fp);
}
/* Now get us into the INIT state. */
fips_new_state (STATE_INIT);
}
return;
}
static void
lock_fsm (void)
{
gpg_error_t err;
err = ath_mutex_lock (&fsm_lock);
if (err)
{
log_info ("FATAL: failed to acquire the FSM lock in libgrypt: %s\n",
strerror (err));
#ifdef HAVE_SYSLOG
syslog (LOG_USER|LOG_ERR, "Libgcrypt error: "
"acquiring FSM lock failed: %s - abort",
strerror (err));
#endif /*HAVE_SYSLOG*/
abort ();
}
}
static void
unlock_fsm (void)
{
gpg_error_t err;
err = ath_mutex_unlock (&fsm_lock);
if (err)
{
log_info ("FATAL: failed to release the FSM lock in libgrypt: %s\n",
strerror (err));
#ifdef HAVE_SYSLOG
syslog (LOG_USER|LOG_ERR, "Libgcrypt error: "
"releasing FSM lock failed: %s - abort",
strerror (err));
#endif /*HAVE_SYSLOG*/
abort ();
}
}
/* This function returns true if fips mode is enabled. This is
independent of the fips required finite state machine and only used
to enable fips specific code. Please use the fips_mode macro
instead of calling this function directly. */
int
_gcry_fips_mode (void)
{
/* No locking is required becuase we have the requirement that this
variable is only intialized once with no other threads
exiisting. */
return !no_fips_mode_required;
}
/* Return a flag telling whether we are in the enforced fips mode. */
int
_gcry_enforced_fips_mode (void)
{
return enforced_fips_mode;
}
static const char *
state2str (enum module_states state)
{
const char *s;
switch (state)
{
case STATE_POWERON: s = "Power-On"; break;
case STATE_INIT: s = "Init"; break;
case STATE_SELFTEST: s = "Self-Test"; break;
case STATE_OPERATIONAL: s = "Operational"; break;
case STATE_ERROR: s = "Error"; break;
case STATE_FATALERROR: s = "Fatal-Error"; break;
case STATE_SHUTDOWN: s = "Shutdown"; break;
default: s = "?"; break;
}
return s;
}
/* Return true if the library is in the operational state. */
int
_gcry_fips_is_operational (void)
{
int result;
if (!fips_mode ())
result = 1;
else
{
lock_fsm ();
if (current_state == STATE_INIT)
{
/* If we are still in the INIT state, we need to run the
selftests so that the FSM can eventually get into
operational state. Given that we would need a 2-phase
initialization of libgcrypt, but that has traditionally
not been enforced, we use this on demand self-test
checking. Note that Proper applications would do the
application specific libgcrypt initialization between a
gcry_check_version() and gcry_control
(GCRYCTL_INITIALIZATION_FINISHED) where the latter will
run the selftests. The drawback of these on-demand
self-tests are a small chance that self-tests are
performed by severeal threads; that is no problem because
our FSM make sure that we won't oversee any error. */
unlock_fsm ();
_gcry_fips_run_selftests (0);
lock_fsm ();
}
result = (current_state == STATE_OPERATIONAL);
unlock_fsm ();
}
return result;
}
/* This is test on wether the library is in the operational state. In
contrast to _gcry_fips_is_operational this function won't do a
state transition on the fly. */
int
_gcry_fips_test_operational (void)
{
int result;
if (!fips_mode ())
result = 1;
else
{
lock_fsm ();
result = (current_state == STATE_OPERATIONAL);
unlock_fsm ();
}
return result;
}
/* This is a test on whether the library is in the error or
operational state. */
int
_gcry_fips_test_error_or_operational (void)
{
int result;
if (!fips_mode ())
result = 1;
else
{
lock_fsm ();
result = (current_state == STATE_OPERATIONAL
|| current_state == STATE_ERROR);
unlock_fsm ();
}
return result;
}
static void
reporter (const char *domain, int algo, const char *what, const char *errtxt)
{
if (!errtxt && !_gcry_log_verbosity (2))
return;
log_info ("libgcrypt selftest: %s %s%s (%d): %s%s%s%s\n",
!strcmp (domain, "hmac")? "digest":domain,
!strcmp (domain, "hmac")? "HMAC-":"",
!strcmp (domain, "cipher")? _gcry_cipher_algo_name (algo) :
!strcmp (domain, "digest")? _gcry_md_algo_name (algo) :
!strcmp (domain, "hmac")? _gcry_md_algo_name (algo) :
!strcmp (domain, "pubkey")? _gcry_pk_algo_name (algo) : "",
algo, errtxt? errtxt:"Okay",
what?" (":"", what? what:"", what?")":"");
}
/* Run self-tests for all required cipher algorithms. Return 0 on
success. */
static int
run_cipher_selftests (int extended)
{
static int algos[] =
{
GCRY_CIPHER_3DES,
GCRY_CIPHER_AES128,
GCRY_CIPHER_AES192,
GCRY_CIPHER_AES256,
0
};
int idx;
gpg_error_t err;
int anyerr = 0;
for (idx=0; algos[idx]; idx++)
{
err = _gcry_cipher_selftest (algos[idx], extended, reporter);
reporter ("cipher", algos[idx], NULL,
err? gpg_strerror (err):NULL);
if (err)
anyerr = 1;
}
return anyerr;
}
/* Run self-tests for all required hash algorithms. Return 0 on
success. */
static int
run_digest_selftests (int extended)
{
static int algos[] =
{
GCRY_MD_SHA1,
GCRY_MD_SHA224,
GCRY_MD_SHA256,
GCRY_MD_SHA384,
GCRY_MD_SHA512,
0
};
int idx;
gpg_error_t err;
int anyerr = 0;
for (idx=0; algos[idx]; idx++)
{
err = _gcry_md_selftest (algos[idx], extended, reporter);
reporter ("digest", algos[idx], NULL,
err? gpg_strerror (err):NULL);
if (err)
anyerr = 1;
}
return anyerr;
}
/* Run self-tests for all HMAC algorithms. Return 0 on success. */
static int
run_hmac_selftests (int extended)
{
static int algos[] =
{
GCRY_MD_SHA1,
GCRY_MD_SHA224,
GCRY_MD_SHA256,
GCRY_MD_SHA384,
GCRY_MD_SHA512,
0
};
int idx;
gpg_error_t err;
int anyerr = 0;
for (idx=0; algos[idx]; idx++)
{
err = _gcry_hmac_selftest (algos[idx], extended, reporter);
reporter ("hmac", algos[idx], NULL,
err? gpg_strerror (err):NULL);
if (err)
anyerr = 1;
}
return anyerr;
}
/* Run self-tests for all required public key algorithms. Return 0 on
success. */
static int
run_pubkey_selftests (int extended)
{
static int algos[] =
{
GCRY_PK_RSA,
GCRY_PK_DSA,
/* GCRY_PK_ECDSA is not enabled in fips mode. */
0
};
int idx;
gpg_error_t err;
int anyerr = 0;
for (idx=0; algos[idx]; idx++)
{
err = _gcry_pk_selftest (algos[idx], extended, reporter);
reporter ("pubkey", algos[idx], NULL,
err? gpg_strerror (err):NULL);
if (err)
anyerr = 1;
}
return anyerr;
}
/* Run self-tests for the random number generator. Returns 0 on
success. */
static int
run_random_selftests (void)
{
gpg_error_t err;
err = _gcry_random_selftest (reporter);
reporter ("random", 0, NULL, err? gpg_strerror (err):NULL);
return !!err;
}
/* Run an integrity check on the binary. Returns 0 on success. */
static int
check_binary_integrity (void)
{
#ifdef ENABLE_HMAC_BINARY_CHECK
gpg_error_t err;
Dl_info info;
unsigned char digest[32];
int dlen;
char *fname = NULL;
const char key[] = "What am I, a doctor or a moonshuttle conductor?";
if (!dladdr ("gcry_check_version", &info))
err = gpg_error_from_syserror ();
else
{
dlen = _gcry_hmac256_file (digest, sizeof digest, info.dli_fname,
key, strlen (key));
if (dlen < 0)
err = gpg_error_from_syserror ();
else if (dlen != 32)
err = gpg_error (GPG_ERR_INTERNAL);
else
{
fname = gcry_malloc (strlen (info.dli_fname) + 1 + 5 + 1 );
if (!fname)
err = gpg_error_from_syserror ();
else
{
FILE *fp;
char *p;
/* Prefix the basename with a dot. */
strcpy (fname, info.dli_fname);
p = strrchr (fname, '/');
if (p)
p++;
else
p = fname;
memmove (p+1, p, strlen (p)+1);
*p = '.';
strcat (fname, ".hmac");
/* Open the file. */
fp = fopen (fname, "r");
if (!fp)
err = gpg_error_from_syserror ();
else
{
/* A buffer of 64 bytes plus one for a LF and one to
detect garbage. */
unsigned char buffer[64+1+1];
const unsigned char *s;
int n;
/* The HMAC files consists of lowercase hex digits
only with an optional trailing linefeed. Fail if
there is any garbage. */
err = gpg_error (GPG_ERR_SELFTEST_FAILED);
n = fread (buffer, 1, sizeof buffer, fp);
if (n == 64 || (n == 65 && buffer[64] == '\n'))
{
buffer[64] = 0;
for (n=0, s= buffer;
n < 32 && loxdigit_p (s) && loxdigit_p (s+1);
n++, s += 2)
buffer[n] = loxtoi_2 (s);
if ( n == 32 && !memcmp (digest, buffer, 32) )
err = 0;
}
fclose (fp);
}
}
}
}
reporter ("binary", 0, fname, err? gpg_strerror (err):NULL);
#ifdef HAVE_SYSLOG
if (err)
syslog (LOG_USER|LOG_ERR, "Libgcrypt error: "
"integrity check using `%s' failed: %s",
fname? fname:"[?]", gpg_strerror (err));
#endif /*HAVE_SYSLOG*/
gcry_free (fname);
return !!err;
#else
return 0;
#endif
}
/* Run the self-tests. If EXTENDED is true, extended versions of the
selftest are run, that is more tests than required by FIPS. */
gpg_err_code_t
_gcry_fips_run_selftests (int extended)
{
enum module_states result = STATE_ERROR;
gcry_err_code_t ec = GPG_ERR_SELFTEST_FAILED;
if (fips_mode ())
fips_new_state (STATE_SELFTEST);
if (run_cipher_selftests (extended))
goto leave;
if (run_digest_selftests (extended))
goto leave;
if (run_hmac_selftests (extended))
goto leave;
/* Run random tests before the pubkey tests because the latter
require random. */
if (run_random_selftests ())
goto leave;
if (run_pubkey_selftests (extended))
goto leave;
/* Now check the integrity of the binary. We do this this after
having checked the HMAC code. */
if (check_binary_integrity ())
goto leave;
/* All selftests passed. */
result = STATE_OPERATIONAL;
ec = 0;
leave:
if (fips_mode ())
fips_new_state (result);
return ec;
}
/* This function is used to tell the FSM about errors in the library.
The FSM will be put into an error state. This function should not
be called directly but by one of the macros
fips_signal_error (description)
fips_signal_fatal_error (description)
where DESCRIPTION is a string describing the error. */
void
_gcry_fips_signal_error (const char *srcfile, int srcline, const char *srcfunc,
int is_fatal, const char *description)
{
if (!fips_mode ())
return; /* Not required. */
/* Set new state before printing an error. */
fips_new_state (is_fatal? STATE_FATALERROR : STATE_ERROR);
/* Print error. */
log_info ("%serror in libgcrypt, file %s, line %d%s%s: %s\n",
is_fatal? "fatal ":"",
srcfile, srcline,
srcfunc? ", function ":"", srcfunc? srcfunc:"",
description? description : "no description available");
#ifdef HAVE_SYSLOG
syslog (LOG_USER|LOG_ERR, "Libgcrypt error: "
"%serror in file %s, line %d%s%s: %s",
is_fatal? "fatal ":"",
srcfile, srcline,
srcfunc? ", function ":"", srcfunc? srcfunc:"",
description? description : "no description available");
#endif /*HAVE_SYSLOG*/
}
/* Perform a state transition to NEW_STATE. If this is an invalid
transition, the module will go into a fatal error state. */
static void
fips_new_state (enum module_states new_state)
{
int ok = 0;
enum module_states last_state;
lock_fsm ();
last_state = current_state;
switch (current_state)
{
case STATE_POWERON:
if (new_state == STATE_INIT
|| new_state == STATE_ERROR
|| new_state == STATE_FATALERROR)
ok = 1;
break;
case STATE_INIT:
if (new_state == STATE_SELFTEST
|| new_state == STATE_ERROR
|| new_state == STATE_FATALERROR)
ok = 1;
break;
case STATE_SELFTEST:
if (new_state == STATE_OPERATIONAL
|| new_state == STATE_ERROR
|| new_state == STATE_FATALERROR)
ok = 1;
break;
case STATE_OPERATIONAL:
if (new_state == STATE_SHUTDOWN
|| new_state == STATE_SELFTEST
|| new_state == STATE_ERROR
|| new_state == STATE_FATALERROR)
ok = 1;
break;
case STATE_ERROR:
if (new_state == STATE_SHUTDOWN
+ || new_state == STATE_ERROR
|| new_state == STATE_FATALERROR
|| new_state == STATE_SELFTEST)
ok = 1;
break;
case STATE_FATALERROR:
if (new_state == STATE_SHUTDOWN )
ok = 1;
break;
case STATE_SHUTDOWN:
/* We won't see any transition *from* Shutdown because the only
allowed new state is Power-Off and that one can't be
represented. */
break;
}
if (ok)
{
current_state = new_state;
}
unlock_fsm ();
if (!ok || _gcry_log_verbosity (2))
log_info ("libgcrypt state transition %s => %s %s\n",
state2str (last_state), state2str (new_state),
ok? "granted":"denied");
if (!ok)
{
/* Invalid state transition. Halting library. */
#ifdef HAVE_SYSLOG
syslog (LOG_USER|LOG_ERR,
"Libgcrypt error: invalid state transition %s => %s",
state2str (last_state), state2str (new_state));
#endif /*HAVE_SYSLOG*/
fips_noreturn ();
}
else if (new_state == STATE_ERROR || new_state == STATE_FATALERROR)
{
#ifdef HAVE_SYSLOG
syslog (LOG_USER|LOG_WARNING,
"Libgcrypt notice: state transition %s => %s",
state2str (last_state), state2str (new_state));
#endif /*HAVE_SYSLOG*/
}
}
/* This function should be called to ensure that the execution shall
not continue. */
void
_gcry_fips_noreturn (void)
{
#ifdef HAVE_SYSLOG
syslog (LOG_USER|LOG_ERR, "Libgcrypt terminated the application");
#endif /*HAVE_SYSLOG*/
fflush (NULL);
abort ();
/*NOTREACHED*/
}
diff --git a/src/gcrypt-module.h b/src/gcrypt-module.h
index 39d39c86..e717b70c 100644
--- a/src/gcrypt-module.h
+++ b/src/gcrypt-module.h
@@ -1,226 +1,233 @@
/* gcrypt-module.h - GNU Cryptographic Library Interface
Copyright (C) 2003, 2007 Free Software Foundation, Inc.
This file is part of Libgcrypt.
Libgcrypt is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of
the License, or (at your option) any later version.
Libgcrypt is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
/*
This file contains the necessary declarations/definitions for
working with Libgcrypt modules.
*/
#ifndef _GCRYPT_MODULE_H
#define _GCRYPT_MODULE_H
#ifdef __cplusplus
extern "C" {
#if 0 /* keep Emacsens's auto-indent happy */
}
#endif
#endif
+/* The interfaces using the module system reserve a certain range of
+ IDs for application use. These IDs are not valid within Libgcrypt
+ but Libgcrypt makes sure never to allocate such a module ID. */
+#define GCRY_MODULE_ID_USER 1024
+#define GCRY_MODULE_ID_USER_LAST 4095
+
+
/* This type represents a `module'. */
typedef struct gcry_module *gcry_module_t;
/* Check that the library fulfills the version requirement. */
/* Type for the cipher_setkey function. */
typedef gcry_err_code_t (*gcry_cipher_setkey_t) (void *c,
const unsigned char *key,
unsigned keylen);
/* Type for the cipher_encrypt function. */
typedef void (*gcry_cipher_encrypt_t) (void *c,
unsigned char *outbuf,
const unsigned char *inbuf);
/* Type for the cipher_decrypt function. */
typedef void (*gcry_cipher_decrypt_t) (void *c,
unsigned char *outbuf,
const unsigned char *inbuf);
/* Type for the cipher_stencrypt function. */
typedef void (*gcry_cipher_stencrypt_t) (void *c,
unsigned char *outbuf,
const unsigned char *inbuf,
unsigned int n);
/* Type for the cipher_stdecrypt function. */
typedef void (*gcry_cipher_stdecrypt_t) (void *c,
unsigned char *outbuf,
const unsigned char *inbuf,
unsigned int n);
typedef struct gcry_cipher_oid_spec
{
const char *oid;
int mode;
} gcry_cipher_oid_spec_t;
/* Module specification structure for ciphers. */
typedef struct gcry_cipher_spec
{
const char *name;
const char **aliases;
gcry_cipher_oid_spec_t *oids;
size_t blocksize;
size_t keylen;
size_t contextsize;
gcry_cipher_setkey_t setkey;
gcry_cipher_encrypt_t encrypt;
gcry_cipher_decrypt_t decrypt;
gcry_cipher_stencrypt_t stencrypt;
gcry_cipher_stdecrypt_t stdecrypt;
} gcry_cipher_spec_t;
/* Register a new cipher module whose specification can be found in
CIPHER. On success, a new algorithm ID is stored in ALGORITHM_ID
and a pointer representing this module is stored in MODULE. */
gcry_error_t gcry_cipher_register (gcry_cipher_spec_t *cipher,
int *algorithm_id,
gcry_module_t *module);
/* Unregister the cipher identified by MODULE, which must have been
registered with gcry_cipher_register. */
void gcry_cipher_unregister (gcry_module_t module);
/* ********************** */
/* Type for the pk_generate function. */
typedef gcry_err_code_t (*gcry_pk_generate_t) (int algo,
unsigned int nbits,
unsigned long use_e,
gcry_mpi_t *skey,
gcry_mpi_t **retfactors);
/* Type for the pk_check_secret_key function. */
typedef gcry_err_code_t (*gcry_pk_check_secret_key_t) (int algo,
gcry_mpi_t *skey);
/* Type for the pk_encrypt function. */
typedef gcry_err_code_t (*gcry_pk_encrypt_t) (int algo,
gcry_mpi_t *resarr,
gcry_mpi_t data,
gcry_mpi_t *pkey,
int flags);
/* Type for the pk_decrypt function. */
typedef gcry_err_code_t (*gcry_pk_decrypt_t) (int algo,
gcry_mpi_t *result,
gcry_mpi_t *data,
gcry_mpi_t *skey,
int flags);
/* Type for the pk_sign function. */
typedef gcry_err_code_t (*gcry_pk_sign_t) (int algo,
gcry_mpi_t *resarr,
gcry_mpi_t data,
gcry_mpi_t *skey);
/* Type for the pk_verify function. */
typedef gcry_err_code_t (*gcry_pk_verify_t) (int algo,
gcry_mpi_t hash,
gcry_mpi_t *data,
gcry_mpi_t *pkey,
int (*cmp) (void *, gcry_mpi_t),
void *opaquev);
/* Type for the pk_get_nbits function. */
typedef unsigned (*gcry_pk_get_nbits_t) (int algo, gcry_mpi_t *pkey);
/* Module specification structure for message digests. */
typedef struct gcry_pk_spec
{
const char *name;
const char **aliases;
const char *elements_pkey;
const char *elements_skey;
const char *elements_enc;
const char *elements_sig;
const char *elements_grip;
int use;
gcry_pk_generate_t generate;
gcry_pk_check_secret_key_t check_secret_key;
gcry_pk_encrypt_t encrypt;
gcry_pk_decrypt_t decrypt;
gcry_pk_sign_t sign;
gcry_pk_verify_t verify;
gcry_pk_get_nbits_t get_nbits;
} gcry_pk_spec_t;
/* Register a new pubkey module whose specification can be found in
PUBKEY. On success, a new algorithm ID is stored in ALGORITHM_ID
and a pointer representhing this module is stored in MODULE. */
gcry_error_t gcry_pk_register (gcry_pk_spec_t *pubkey,
unsigned int *algorithm_id,
gcry_module_t *module);
/* Unregister the pubkey identified by ID, which must have been
registered with gcry_pk_register. */
void gcry_pk_unregister (gcry_module_t module);
/* ********************** */
/* Type for the md_init function. */
typedef void (*gcry_md_init_t) (void *c);
/* Type for the md_write function. */
typedef void (*gcry_md_write_t) (void *c, const void *buf, size_t nbytes);
/* Type for the md_final function. */
typedef void (*gcry_md_final_t) (void *c);
/* Type for the md_read function. */
typedef unsigned char *(*gcry_md_read_t) (void *c);
typedef struct gcry_md_oid_spec
{
const char *oidstring;
} gcry_md_oid_spec_t;
/* Module specification structure for message digests. */
typedef struct gcry_md_spec
{
const char *name;
unsigned char *asnoid;
int asnlen;
gcry_md_oid_spec_t *oids;
int mdlen;
gcry_md_init_t init;
gcry_md_write_t write;
gcry_md_final_t final;
gcry_md_read_t read;
size_t contextsize; /* allocate this amount of context */
} gcry_md_spec_t;
/* Register a new digest module whose specification can be found in
DIGEST. On success, a new algorithm ID is stored in ALGORITHM_ID
and a pointer representhing this module is stored in MODULE. */
gcry_error_t gcry_md_register (gcry_md_spec_t *digest,
unsigned int *algorithm_id,
gcry_module_t *module);
/* Unregister the digest identified by ID, which must have been
registered with gcry_digest_register. */
void gcry_md_unregister (gcry_module_t module);
#if 0 /* keep Emacsens's auto-indent happy */
{
#endif
#ifdef __cplusplus
}
#endif
#endif
diff --git a/src/gcrypt.h.in b/src/gcrypt.h.in
index f040ed84..ae34d106 100644
--- a/src/gcrypt.h.in
+++ b/src/gcrypt.h.in
@@ -1,1831 +1,1831 @@
/* gcrypt.h - GNU Cryptographic Library Interface -*- c -*-
Copyright (C) 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2006
2007, 2008 Free Software Foundation, Inc.
This file is part of Libgcrypt.
Libgcrypt is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of
the License, or (at your option) any later version.
Libgcrypt is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this program; if not, see <http://www.gnu.org/licenses/>.
File: @configure_input@ */
#ifndef _GCRYPT_H
#define _GCRYPT_H
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <gpg-error.h>
#include <sys/types.h>
#if defined _WIN32 || defined __WIN32__
# include <winsock2.h>
# include <ws2tcpip.h>
#else
# include <sys/socket.h>
#endif /*!_WIN32*/
@FALLBACK_SOCKLEN_T@
#include <sys/time.h>
/* This is required for error code compatibility. */
#define _GCRY_ERR_SOURCE_DEFAULT GPG_ERR_SOURCE_GCRYPT
#ifdef __cplusplus
extern "C" {
#if 0 /* (Keep Emacsens' auto-indent happy.) */
}
#endif
#endif
/* The version of this header should match the one of the library. It
should not be used by a program because gcry_check_version() should
return the same version. The purpose of this macro is to let
autoconf (using the AM_PATH_GCRYPT macro) check that this header
matches the installed library. */
#define GCRYPT_VERSION "@VERSION@"
/* Internal: We can't use the convenience macros for the multi
precision integer functions when building this library. */
#ifdef _GCRYPT_IN_LIBGCRYPT
#ifndef GCRYPT_NO_MPI_MACROS
#define GCRYPT_NO_MPI_MACROS 1
#endif
#endif
/* We want to use gcc attributes when possible. Warning: Don't use
these macros in your programs: As indicated by the leading
underscore they are subject to change without notice. */
#ifdef __GNUC__
#define _GCRY_GCC_VERSION (__GNUC__ * 10000 \
+ __GNUC_MINOR__ * 100 \
+ __GNUC_PATCHLEVEL__)
#if _GCRY_GCC_VERSION >= 30100
#define _GCRY_GCC_ATTR_DEPRECATED __attribute__ ((__deprecated__))
#endif
#if _GCRY_GCC_VERSION >= 29600
#define _GCRY_GCC_ATTR_PURE __attribute__ ((__pure__))
#endif
#if _GCRY_GCC_VERSION >= 30200
#define _GCRY_GCC_ATTR_MALLOC __attribute__ ((__malloc__))
#endif
#endif /*__GNUC__*/
#ifndef _GCRY_GCC_ATTR_DEPRECATED
#define _GCRY_GCC_ATTR_DEPRECATED
#endif
#ifndef _GCRY_GCC_ATTR_PURE
#define _GCRY_GCC_ATTR_PURE
#endif
#ifndef _GCRY_GCC_ATTR_MALLOC
#define _GCRY_GCC_ATTR_MALLOC
#endif
/* Some members in a public type should only be used internally.
There is no "internal" attribute, so we abuse the deprecated
attribute to discourage external use. */
#ifdef _GCRYPT_IN_LIBGCRYPT
#define _GCRY_ATTR_INTERNAL
#else
#define _GCRY_ATTR_INTERNAL _GCRY_GCC_ATTR_DEPRECATED
#endif
/* Wrappers for the libgpg-error library. */
typedef gpg_error_t gcry_error_t;
typedef gpg_err_code_t gcry_err_code_t;
typedef gpg_err_source_t gcry_err_source_t;
static GPG_ERR_INLINE gcry_error_t
gcry_err_make (gcry_err_source_t source, gcry_err_code_t code)
{
return gpg_err_make (source, code);
}
/* The user can define GPG_ERR_SOURCE_DEFAULT before including this
file to specify a default source for gpg_error. */
#ifndef GCRY_ERR_SOURCE_DEFAULT
#define GCRY_ERR_SOURCE_DEFAULT GPG_ERR_SOURCE_USER_1
#endif
static GPG_ERR_INLINE gcry_error_t
gcry_error (gcry_err_code_t code)
{
return gcry_err_make (GCRY_ERR_SOURCE_DEFAULT, code);
}
static GPG_ERR_INLINE gcry_err_code_t
gcry_err_code (gcry_error_t err)
{
return gpg_err_code (err);
}
static GPG_ERR_INLINE gcry_err_source_t
gcry_err_source (gcry_error_t err)
{
return gpg_err_source (err);
}
/* Return a pointer to a string containing a description of the error
code in the error value ERR. */
const char *gcry_strerror (gcry_error_t err);
/* Return a pointer to a string containing a description of the error
source in the error value ERR. */
const char *gcry_strsource (gcry_error_t err);
/* Retrieve the error code for the system error ERR. This returns
GPG_ERR_UNKNOWN_ERRNO if the system error is not mapped (report
this). */
gcry_err_code_t gcry_err_code_from_errno (int err);
/* Retrieve the system error for the error code CODE. This returns 0
if CODE is not a system error code. */
int gcry_err_code_to_errno (gcry_err_code_t code);
/* Return an error value with the error source SOURCE and the system
error ERR. */
gcry_error_t gcry_err_make_from_errno (gcry_err_source_t source, int err);
/* Return an error value with the system error ERR. */
gcry_err_code_t gcry_error_from_errno (int err);
/* This enum is deprecated; it is only declared for the sake of
complete API compatibility. */
enum gcry_thread_option
{
_GCRY_THREAD_OPTION_DUMMY
} _GCRY_GCC_ATTR_DEPRECATED;
/* Constants defining the thread model to use. Used with the OPTION
field of the struct gcry_thread_cbs. */
#define GCRY_THREAD_OPTION_DEFAULT 0
#define GCRY_THREAD_OPTION_USER 1
#define GCRY_THREAD_OPTION_PTH 2
#define GCRY_THREAD_OPTION_PTHREAD 3
/* The version number encoded in the OPTION field of the struct
gcry_thread_cbs. */
#define GCRY_THREAD_OPTION_VERSION 0
/* Wrapper for struct ath_ops. */
struct gcry_thread_cbs
{
/* The OPTION field encodes the thread model and the version number
of this structure.
Bits 7 - 0 are used for the thread model
Bits 15 - 8 are used for the version number.
*/
unsigned int option;
int (*init) (void);
int (*mutex_init) (void **priv);
int (*mutex_destroy) (void **priv);
int (*mutex_lock) (void **priv);
int (*mutex_unlock) (void **priv);
ssize_t (*read) (int fd, void *buf, size_t nbytes);
ssize_t (*write) (int fd, const void *buf, size_t nbytes);
#ifdef _WIN32
ssize_t (*select) (int nfd, void *rset, void *wset, void *eset,
struct timeval *timeout);
ssize_t (*waitpid) (pid_t pid, int *status, int options);
int (*accept) (int s, void *addr, int *length_ptr);
int (*connect) (int s, void *addr, gcry_socklen_t length);
int (*sendmsg) (int s, const void *msg, int flags);
int (*recvmsg) (int s, void *msg, int flags);
#else
ssize_t (*select) (int nfd, fd_set *rset, fd_set *wset, fd_set *eset,
struct timeval *timeout);
ssize_t (*waitpid) (pid_t pid, int *status, int options);
int (*accept) (int s, struct sockaddr *addr, gcry_socklen_t *length_ptr);
int (*connect) (int s, struct sockaddr *addr, gcry_socklen_t length);
int (*sendmsg) (int s, const struct msghdr *msg, int flags);
int (*recvmsg) (int s, struct msghdr *msg, int flags);
#endif
};
#ifdef _WIN32
# define _GCRY_THREAD_OPTION_PTH_IMPL_NET \
static ssize_t gcry_pth_select (int nfd, void *rset, void *wset, \
void *eset, struct timeval *timeout) \
{ return pth_select (nfd, rset, wset, eset, timeout); } \
static ssize_t gcry_pth_waitpid (pid_t pid, int *status, int options) \
{ return pth_waitpid (pid, status, options); } \
static int gcry_pth_accept (int s, void *addr, \
gcry_socklen_t *length_ptr) \
{ return pth_accept (s, addr, length_ptr); } \
static int gcry_pth_connect (int s, void *addr, \
gcry_socklen_t length) \
{ return pth_connect (s, addr, length); }
#else /*!_WIN32*/
# define _GCRY_THREAD_OPTION_PTH_IMPL_NET \
static ssize_t gcry_pth_select (int nfd, fd_set *rset, fd_set *wset, \
fd_set *eset, struct timeval *timeout) \
{ return pth_select (nfd, rset, wset, eset, timeout); } \
static ssize_t gcry_pth_waitpid (pid_t pid, int *status, int options) \
{ return pth_waitpid (pid, status, options); } \
static int gcry_pth_accept (int s, struct sockaddr *addr, \
gcry_socklen_t *length_ptr) \
{ return pth_accept (s, addr, length_ptr); } \
static int gcry_pth_connect (int s, struct sockaddr *addr, \
gcry_socklen_t length) \
{ return pth_connect (s, addr, length); }
#endif /*!_WIN32*/
#define GCRY_THREAD_OPTION_PTH_IMPL \
static int gcry_pth_init (void) \
{ return (pth_init () == FALSE) ? errno : 0; } \
static int gcry_pth_mutex_init (void **priv) \
{ \
int err = 0; \
pth_mutex_t *lock = malloc (sizeof (pth_mutex_t)); \
\
if (!lock) \
err = ENOMEM; \
if (!err) \
{ \
err = pth_mutex_init (lock); \
if (err == FALSE) \
err = errno; \
else \
err = 0; \
if (err) \
free (lock); \
else \
*priv = lock; \
} \
return err; \
} \
static int gcry_pth_mutex_destroy (void **lock) \
{ /* GNU Pth has no destructor function. */ free (*lock); return 0; } \
static int gcry_pth_mutex_lock (void **lock) \
{ return ((pth_mutex_acquire (*lock, 0, NULL)) == FALSE) \
? errno : 0; } \
static int gcry_pth_mutex_unlock (void **lock) \
{ return ((pth_mutex_release (*lock)) == FALSE) \
? errno : 0; } \
static ssize_t gcry_pth_read (int fd, void *buf, size_t nbytes) \
{ return pth_read (fd, buf, nbytes); } \
static ssize_t gcry_pth_write (int fd, const void *buf, size_t nbytes) \
{ return pth_write (fd, buf, nbytes); } \
_GCRY_THREAD_OPTION_PTH_IMPL_NET \
\
/* Note: GNU Pth is missing pth_sendmsg and pth_recvmsg. */ \
static struct gcry_thread_cbs gcry_threads_pth = { \
(GCRY_THREAD_OPTION_PTH | (GCRY_THREAD_OPTION_VERSION << 8)), \
gcry_pth_init, gcry_pth_mutex_init, gcry_pth_mutex_destroy, \
gcry_pth_mutex_lock, gcry_pth_mutex_unlock, gcry_pth_read, gcry_pth_write, \
gcry_pth_select, gcry_pth_waitpid, gcry_pth_accept, gcry_pth_connect, \
NULL, NULL }
#define GCRY_THREAD_OPTION_PTHREAD_IMPL \
static int gcry_pthread_mutex_init (void **priv) \
{ \
int err = 0; \
pthread_mutex_t *lock = (pthread_mutex_t*)malloc (sizeof (pthread_mutex_t));\
\
if (!lock) \
err = ENOMEM; \
if (!err) \
{ \
err = pthread_mutex_init (lock, NULL); \
if (err) \
free (lock); \
else \
*priv = lock; \
} \
return err; \
} \
static int gcry_pthread_mutex_destroy (void **lock) \
{ int err = pthread_mutex_destroy ((pthread_mutex_t*)*lock); \
free (*lock); return err; } \
static int gcry_pthread_mutex_lock (void **lock) \
{ return pthread_mutex_lock ((pthread_mutex_t*)*lock); } \
static int gcry_pthread_mutex_unlock (void **lock) \
{ return pthread_mutex_unlock ((pthread_mutex_t*)*lock); } \
\
static struct gcry_thread_cbs gcry_threads_pthread = { \
(GCRY_THREAD_OPTION_PTHREAD | (GCRY_THREAD_OPTION_VERSION << 8)), \
NULL, gcry_pthread_mutex_init, gcry_pthread_mutex_destroy, \
gcry_pthread_mutex_lock, gcry_pthread_mutex_unlock, \
NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL }
/* The data object used to hold a multi precision integer. */
struct gcry_mpi;
typedef struct gcry_mpi *gcry_mpi_t;
#ifndef GCRYPT_NO_DEPRECATED
typedef struct gcry_mpi *GCRY_MPI _GCRY_GCC_ATTR_DEPRECATED;
typedef struct gcry_mpi *GcryMPI _GCRY_GCC_ATTR_DEPRECATED;
#endif
/* Check that the library fulfills the version requirement. */
const char *gcry_check_version (const char *req_version);
/* Codes for function dispatchers. */
/* Codes used with the gcry_control function. */
enum gcry_ctl_cmds
{
GCRYCTL_SET_KEY = 1,
GCRYCTL_SET_IV = 2,
GCRYCTL_CFB_SYNC = 3,
GCRYCTL_RESET = 4, /* e.g. for MDs */
GCRYCTL_FINALIZE = 5,
GCRYCTL_GET_KEYLEN = 6,
GCRYCTL_GET_BLKLEN = 7,
GCRYCTL_TEST_ALGO = 8,
GCRYCTL_IS_SECURE = 9,
GCRYCTL_GET_ASNOID = 10,
GCRYCTL_ENABLE_ALGO = 11,
GCRYCTL_DISABLE_ALGO = 12,
GCRYCTL_DUMP_RANDOM_STATS = 13,
GCRYCTL_DUMP_SECMEM_STATS = 14,
GCRYCTL_GET_ALGO_NPKEY = 15,
GCRYCTL_GET_ALGO_NSKEY = 16,
GCRYCTL_GET_ALGO_NSIGN = 17,
GCRYCTL_GET_ALGO_NENCR = 18,
GCRYCTL_SET_VERBOSITY = 19,
GCRYCTL_SET_DEBUG_FLAGS = 20,
GCRYCTL_CLEAR_DEBUG_FLAGS = 21,
GCRYCTL_USE_SECURE_RNDPOOL= 22,
GCRYCTL_DUMP_MEMORY_STATS = 23,
GCRYCTL_INIT_SECMEM = 24,
GCRYCTL_TERM_SECMEM = 25,
GCRYCTL_DISABLE_SECMEM_WARN = 27,
GCRYCTL_SUSPEND_SECMEM_WARN = 28,
GCRYCTL_RESUME_SECMEM_WARN = 29,
GCRYCTL_DROP_PRIVS = 30,
GCRYCTL_ENABLE_M_GUARD = 31,
GCRYCTL_START_DUMP = 32,
GCRYCTL_STOP_DUMP = 33,
GCRYCTL_GET_ALGO_USAGE = 34,
GCRYCTL_IS_ALGO_ENABLED = 35,
GCRYCTL_DISABLE_INTERNAL_LOCKING = 36,
GCRYCTL_DISABLE_SECMEM = 37,
GCRYCTL_INITIALIZATION_FINISHED = 38,
GCRYCTL_INITIALIZATION_FINISHED_P = 39,
GCRYCTL_ANY_INITIALIZATION_P = 40,
GCRYCTL_SET_CBC_CTS = 41,
GCRYCTL_SET_CBC_MAC = 42,
GCRYCTL_SET_CTR = 43,
GCRYCTL_ENABLE_QUICK_RANDOM = 44,
GCRYCTL_SET_RANDOM_SEED_FILE = 45,
GCRYCTL_UPDATE_RANDOM_SEED_FILE = 46,
GCRYCTL_SET_THREAD_CBS = 47,
GCRYCTL_FAST_POLL = 48,
GCRYCTL_SET_RANDOM_DAEMON_SOCKET = 49,
GCRYCTL_USE_RANDOM_DAEMON = 50,
GCRYCTL_FAKED_RANDOM_P = 51,
GCRYCTL_SET_RNDEGD_SOCKET = 52,
GCRYCTL_PRINT_CONFIG = 53,
GCRYCTL_OPERATIONAL_P = 54,
GCRYCTL_FIPS_MODE_P = 55,
GCRYCTL_FORCE_FIPS_MODE = 56,
GCRYCTL_SELFTEST = 57
/* Note: 58, 59 and 60 are used internally. */
};
/* Perform various operations defined by CMD. */
gcry_error_t gcry_control (enum gcry_ctl_cmds CMD, ...);
/* S-expression management. */
/* The object to represent an S-expression as used with the public key
functions. */
struct gcry_sexp;
typedef struct gcry_sexp *gcry_sexp_t;
#ifndef GCRYPT_NO_DEPRECATED
typedef struct gcry_sexp *GCRY_SEXP _GCRY_GCC_ATTR_DEPRECATED;
typedef struct gcry_sexp *GcrySexp _GCRY_GCC_ATTR_DEPRECATED;
#endif
/* The possible values for the S-expression format. */
enum gcry_sexp_format
{
GCRYSEXP_FMT_DEFAULT = 0,
GCRYSEXP_FMT_CANON = 1,
GCRYSEXP_FMT_BASE64 = 2,
GCRYSEXP_FMT_ADVANCED = 3
};
/* Create an new S-expression object from BUFFER of size LENGTH and
return it in RETSEXP. With AUTODETECT set to 0 the data in BUFFER
is expected to be in canonized format. */
gcry_error_t gcry_sexp_new (gcry_sexp_t *retsexp,
const void *buffer, size_t length,
int autodetect);
/* Same as gcry_sexp_new but allows to pass a FREEFNC which has the
effect to transfer ownership of BUFFER to the created object. */
gcry_error_t gcry_sexp_create (gcry_sexp_t *retsexp,
void *buffer, size_t length,
int autodetect, void (*freefnc) (void *));
/* Scan BUFFER and return a new S-expression object in RETSEXP. This
function expects a printf like string in BUFFER. */
gcry_error_t gcry_sexp_sscan (gcry_sexp_t *retsexp, size_t *erroff,
const char *buffer, size_t length);
/* Same as gcry_sexp_sscan but expects a string in FORMAT and can thus
only be used for certain encodings. */
gcry_error_t gcry_sexp_build (gcry_sexp_t *retsexp, size_t *erroff,
const char *format, ...);
/* Like gcry_sexp_build, but uses an array instead of variable
function arguments. */
gcry_error_t gcry_sexp_build_array (gcry_sexp_t *retsexp, size_t *erroff,
const char *format, void **arg_list);
/* Release the S-expression object SEXP */
void gcry_sexp_release (gcry_sexp_t sexp);
/* Calculate the length of an canonized S-expresion in BUFFER and
check for a valid encoding. */
size_t gcry_sexp_canon_len (const unsigned char *buffer, size_t length,
size_t *erroff, gcry_error_t *errcode);
/* Copies the S-expression object SEXP into BUFFER using the format
specified in MODE. */
size_t gcry_sexp_sprint (gcry_sexp_t sexp, int mode, void *buffer,
size_t maxlength);
-/* Dumps the S-expression object A in a aformat suitable for debugging
+/* Dumps the S-expression object A in a format suitable for debugging
to Libgcrypt's logging stream. */
void gcry_sexp_dump (const gcry_sexp_t a);
gcry_sexp_t gcry_sexp_cons (const gcry_sexp_t a, const gcry_sexp_t b);
gcry_sexp_t gcry_sexp_alist (const gcry_sexp_t *array);
gcry_sexp_t gcry_sexp_vlist (const gcry_sexp_t a, ...);
gcry_sexp_t gcry_sexp_append (const gcry_sexp_t a, const gcry_sexp_t n);
gcry_sexp_t gcry_sexp_prepend (const gcry_sexp_t a, const gcry_sexp_t n);
/* Scan the S-expression for a sublist with a type (the car of the
list) matching the string TOKEN. If TOKLEN is not 0, the token is
assumed to be raw memory of this length. The function returns a
newly allocated S-expression consisting of the found sublist or
`NULL' when not found. */
gcry_sexp_t gcry_sexp_find_token (gcry_sexp_t list,
const char *tok, size_t toklen);
/* Return the length of the LIST. For a valid S-expression this
should be at least 1. */
int gcry_sexp_length (const gcry_sexp_t list);
/* Create and return a new S-expression from the element with index
NUMBER in LIST. Note that the first element has the index 0. If
there is no such element, `NULL' is returned. */
gcry_sexp_t gcry_sexp_nth (const gcry_sexp_t list, int number);
/* Create and return a new S-expression from the first element in
LIST; this called the "type" and should always exist and be a
string. `NULL' is returned in case of a problem. */
gcry_sexp_t gcry_sexp_car (const gcry_sexp_t list);
/* Create and return a new list form all elements except for the first
one. Note, that this function may return an invalid S-expression
because it is not guaranteed, that the type exists and is a string.
However, for parsing a complex S-expression it might be useful for
intermediate lists. Returns `NULL' on error. */
gcry_sexp_t gcry_sexp_cdr (const gcry_sexp_t list);
gcry_sexp_t gcry_sexp_cadr (const gcry_sexp_t list);
/* This function is used to get data from a LIST. A pointer to the
actual data with index NUMBER is returned and the length of this
data will be stored to DATALEN. If there is no data at the given
index or the index represents another list, `NULL' is returned.
*Note:* The returned pointer is valid as long as LIST is not
modified or released. */
const char *gcry_sexp_nth_data (const gcry_sexp_t list, int number,
size_t *datalen);
/* This function is used to get and convert data from a LIST. The
data is assumed to be a Nul terminated string. The caller must
release the returned value using `gcry_free'. If there is no data
at the given index, the index represents a list or the value can't
be converted to a string, `NULL' is returned. */
char *gcry_sexp_nth_string (gcry_sexp_t list, int number);
/* This function is used to get and convert data from a LIST. This
data is assumed to be an MPI stored in the format described by
MPIFMT and returned as a standard Libgcrypt MPI. The caller must
release this returned value using `gcry_mpi_release'. If there is
no data at the given index, the index represents a list or the
value can't be converted to an MPI, `NULL' is returned. */
gcry_mpi_t gcry_sexp_nth_mpi (gcry_sexp_t list, int number, int mpifmt);
/*******************************************
* *
* Multi Precision Integer Functions *
* *
*******************************************/
/* Different formats of external big integer representation. */
enum gcry_mpi_format
{
GCRYMPI_FMT_NONE= 0,
GCRYMPI_FMT_STD = 1, /* Twos complement stored without length. */
GCRYMPI_FMT_PGP = 2, /* As used by OpenPGP (unsigned only). */
GCRYMPI_FMT_SSH = 3, /* As used by SSH (like STD but with length). */
GCRYMPI_FMT_HEX = 4, /* Hex format. */
GCRYMPI_FMT_USG = 5 /* Like STD but unsigned. */
};
/* Flags used for creating big integers. */
enum gcry_mpi_flag
{
GCRYMPI_FLAG_SECURE = 1, /* Allocate the number in "secure" memory. */
GCRYMPI_FLAG_OPAQUE = 2 /* The number is not a real one but just
a way to store some bytes. This is
useful for encrypted big integers. */
};
/* Allocate a new big integer object, initialize it with 0 and
initially allocate memory for a number of at least NBITS. */
gcry_mpi_t gcry_mpi_new (unsigned int nbits);
/* Same as gcry_mpi_new() but allocate in "secure" memory. */
gcry_mpi_t gcry_mpi_snew (unsigned int nbits);
/* Release the number A and free all associated resources. */
void gcry_mpi_release (gcry_mpi_t a);
/* Create a new number with the same value as A. */
gcry_mpi_t gcry_mpi_copy (const gcry_mpi_t a);
/* Store the big integer value U in W. */
gcry_mpi_t gcry_mpi_set (gcry_mpi_t w, const gcry_mpi_t u);
/* Store the unsigned integer value U in W. */
gcry_mpi_t gcry_mpi_set_ui (gcry_mpi_t w, unsigned long u);
/* Swap the values of A and B. */
void gcry_mpi_swap (gcry_mpi_t a, gcry_mpi_t b);
/* Compare the big integer number U and V returning 0 for equality, a
positive value for U > V and a negative for U < V. */
int gcry_mpi_cmp (const gcry_mpi_t u, const gcry_mpi_t v);
/* Compare the big integer number U with the unsigned integer V
returning 0 for equality, a positive value for U > V and a negative
for U < V. */
int gcry_mpi_cmp_ui (const gcry_mpi_t u, unsigned long v);
/* Convert the external representation of an integer stored in BUFFER
with a length of BUFLEN into a newly create MPI returned in
RET_MPI. If NSCANNED is not NULL, it will receive the number of
bytes actually scanned after a successful operation. */
gcry_error_t gcry_mpi_scan (gcry_mpi_t *ret_mpi, enum gcry_mpi_format format,
const void *buffer, size_t buflen,
size_t *nscanned);
/* Convert the big integer A into the external representation
described by FORMAT and store it in the provided BUFFER which has
been allocated by the user with a size of BUFLEN bytes. NWRITTEN
receives the actual length of the external representation unless it
has been passed as NULL. */
gcry_error_t gcry_mpi_print (enum gcry_mpi_format format,
unsigned char *buffer, size_t buflen,
size_t *nwritten,
const gcry_mpi_t a);
/* Convert the big integer A int the external representation described
by FORMAT and store it in a newly allocated buffer which address
will be put into BUFFER. NWRITTEN receives the actual lengths of the
external representation. */
gcry_error_t gcry_mpi_aprint (enum gcry_mpi_format format,
unsigned char **buffer, size_t *nwritten,
const gcry_mpi_t a);
/* Dump the value of A in a format suitable for debugging to
Libgcrypt's logging stream. Note that one leading space but no
trailing space or linefeed will be printed. It is okay to pass
NULL for A. */
void gcry_mpi_dump (const gcry_mpi_t a);
/* W = U + V. */
void gcry_mpi_add (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v);
/* W = U + V. V is an unsigned integer. */
void gcry_mpi_add_ui (gcry_mpi_t w, gcry_mpi_t u, unsigned long v);
/* W = U + V mod M. */
void gcry_mpi_addm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, gcry_mpi_t m);
/* W = U - V. */
void gcry_mpi_sub (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v);
/* W = U - V. V is an unsigned integer. */
void gcry_mpi_sub_ui (gcry_mpi_t w, gcry_mpi_t u, unsigned long v );
/* W = U - V mod M */
void gcry_mpi_subm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, gcry_mpi_t m);
/* W = U * V. */
void gcry_mpi_mul (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v);
/* W = U * V. V is an unsigned integer. */
void gcry_mpi_mul_ui (gcry_mpi_t w, gcry_mpi_t u, unsigned long v );
/* W = U * V mod M. */
void gcry_mpi_mulm (gcry_mpi_t w, gcry_mpi_t u, gcry_mpi_t v, gcry_mpi_t m);
/* W = U * (2 ^ CNT). */
void gcry_mpi_mul_2exp (gcry_mpi_t w, gcry_mpi_t u, unsigned long cnt);
/* Q = DIVIDEND / DIVISOR, R = DIVIDEND % DIVISOR,
Q or R may be passed as NULL. ROUND should be negative or 0. */
void gcry_mpi_div (gcry_mpi_t q, gcry_mpi_t r,
gcry_mpi_t dividend, gcry_mpi_t divisor, int round);
/* R = DIVIDEND % DIVISOR */
void gcry_mpi_mod (gcry_mpi_t r, gcry_mpi_t dividend, gcry_mpi_t divisor);
/* W = B ^ E mod M. */
void gcry_mpi_powm (gcry_mpi_t w,
const gcry_mpi_t b, const gcry_mpi_t e,
const gcry_mpi_t m);
/* Set G to the greatest common divisor of A and B.
Return true if the G is 1. */
int gcry_mpi_gcd (gcry_mpi_t g, gcry_mpi_t a, gcry_mpi_t b);
/* Set X to the multiplicative inverse of A mod M.
Return true if the value exists. */
int gcry_mpi_invm (gcry_mpi_t x, gcry_mpi_t a, gcry_mpi_t m);
/* Return the number of bits required to represent A. */
unsigned int gcry_mpi_get_nbits (gcry_mpi_t a);
/* Return true when bit number N (counting from 0) is set in A. */
int gcry_mpi_test_bit (gcry_mpi_t a, unsigned int n);
/* Set bit number N in A. */
void gcry_mpi_set_bit (gcry_mpi_t a, unsigned int n);
/* Clear bit number N in A. */
void gcry_mpi_clear_bit (gcry_mpi_t a, unsigned int n);
/* Set bit number N in A and clear all bits greater than N. */
void gcry_mpi_set_highbit (gcry_mpi_t a, unsigned int n);
/* Clear bit number N in A and all bits greater than N. */
void gcry_mpi_clear_highbit (gcry_mpi_t a, unsigned int n);
/* Shift the value of A by N bits to the right and store the result in X. */
void gcry_mpi_rshift (gcry_mpi_t x, gcry_mpi_t a, unsigned int n);
/* Shift the value of A by N bits to the left and store the result in X. */
void gcry_mpi_lshift (gcry_mpi_t x, gcry_mpi_t a, unsigned int n);
/* Store NBITS of the value P points to in A and mark A as an opaque
value. WARNING: Never use an opaque MPI for anything thing else then
gcry_mpi_release, gcry_mpi_get_opaque. */
gcry_mpi_t gcry_mpi_set_opaque (gcry_mpi_t a, void *p, unsigned int nbits);
/* Return a pointer to an opaque value stored in A and return its size
in NBITS. Note that the returned pointer is still owned by A and
that the function should never be used for an non-opaque MPI. */
void *gcry_mpi_get_opaque (gcry_mpi_t a, unsigned int *nbits);
/* Set the FLAG for the big integer A. Currently only the flag
GCRYMPI_FLAG_SECURE is allowed to convert A into an big intger
stored in "secure" memory. */
void gcry_mpi_set_flag (gcry_mpi_t a, enum gcry_mpi_flag flag);
/* Clear FLAG for the big integer A. Note that this function is
currently useless as no flags are allowed. */
void gcry_mpi_clear_flag (gcry_mpi_t a, enum gcry_mpi_flag flag);
/* Return true when the FLAG is set for A. */
int gcry_mpi_get_flag (gcry_mpi_t a, enum gcry_mpi_flag flag);
/* Unless the GCRYPT_NO_MPI_MACROS is used, provide a couple of
convenience macros for the big integer functions. */
#ifndef GCRYPT_NO_MPI_MACROS
#define mpi_new(n) gcry_mpi_new( (n) )
#define mpi_secure_new( n ) gcry_mpi_snew( (n) )
#define mpi_release(a) \
do \
{ \
gcry_mpi_release ((a)); \
(a) = NULL; \
} \
while (0)
#define mpi_copy( a ) gcry_mpi_copy( (a) )
#define mpi_set( w, u) gcry_mpi_set( (w), (u) )
#define mpi_set_ui( w, u) gcry_mpi_set_ui( (w), (u) )
#define mpi_cmp( u, v ) gcry_mpi_cmp( (u), (v) )
#define mpi_cmp_ui( u, v ) gcry_mpi_cmp_ui( (u), (v) )
#define mpi_add_ui(w,u,v) gcry_mpi_add_ui((w),(u),(v))
#define mpi_add(w,u,v) gcry_mpi_add ((w),(u),(v))
#define mpi_addm(w,u,v,m) gcry_mpi_addm ((w),(u),(v),(m))
#define mpi_sub_ui(w,u,v) gcry_mpi_sub_ui ((w),(u),(v))
#define mpi_sub(w,u,v) gcry_mpi_sub ((w),(u),(v))
#define mpi_subm(w,u,v,m) gcry_mpi_subm ((w),(u),(v),(m))
#define mpi_mul_ui(w,u,v) gcry_mpi_mul_ui ((w),(u),(v))
#define mpi_mul_2exp(w,u,v) gcry_mpi_mul_2exp ((w),(u),(v))
#define mpi_mul(w,u,v) gcry_mpi_mul ((w),(u),(v))
#define mpi_mulm(w,u,v,m) gcry_mpi_mulm ((w),(u),(v),(m))
#define mpi_powm(w,b,e,m) gcry_mpi_powm ( (w), (b), (e), (m) )
#define mpi_tdiv(q,r,a,m) gcry_mpi_div ( (q), (r), (a), (m), 0)
#define mpi_fdiv(q,r,a,m) gcry_mpi_div ( (q), (r), (a), (m), -1)
#define mpi_mod(r,a,m) gcry_mpi_mod ((r), (a), (m))
#define mpi_gcd(g,a,b) gcry_mpi_gcd ( (g), (a), (b) )
#define mpi_invm(g,a,b) gcry_mpi_invm ( (g), (a), (b) )
#define mpi_get_nbits(a) gcry_mpi_get_nbits ((a))
#define mpi_test_bit(a,b) gcry_mpi_test_bit ((a),(b))
#define mpi_set_bit(a,b) gcry_mpi_set_bit ((a),(b))
#define mpi_set_highbit(a,b) gcry_mpi_set_highbit ((a),(b))
#define mpi_clear_bit(a,b) gcry_mpi_clear_bit ((a),(b))
#define mpi_clear_highbit(a,b) gcry_mpi_clear_highbit ((a),(b))
#define mpi_rshift(a,b,c) gcry_mpi_rshift ((a),(b),(c))
#define mpi_lshift(a,b,c) gcry_mpi_lshift ((a),(b),(c))
#define mpi_set_opaque(a,b,c) gcry_mpi_set_opaque( (a), (b), (c) )
#define mpi_get_opaque(a,b) gcry_mpi_get_opaque( (a), (b) )
#endif /* GCRYPT_NO_MPI_MACROS */
/************************************
* *
* Symmetric Cipher Functions *
* *
************************************/
/* The data object used to hold a handle to an encryption object. */
struct gcry_cipher_handle;
typedef struct gcry_cipher_handle *gcry_cipher_hd_t;
#ifndef GCRYPT_NO_DEPRECATED
typedef struct gcry_cipher_handle *GCRY_CIPHER_HD _GCRY_GCC_ATTR_DEPRECATED;
typedef struct gcry_cipher_handle *GcryCipherHd _GCRY_GCC_ATTR_DEPRECATED;
#endif
/* All symmetric encryption algorithms are identified by their IDs.
More IDs may be registered at runtime. */
enum gcry_cipher_algos
{
GCRY_CIPHER_NONE = 0,
GCRY_CIPHER_IDEA = 1,
GCRY_CIPHER_3DES = 2,
GCRY_CIPHER_CAST5 = 3,
GCRY_CIPHER_BLOWFISH = 4,
GCRY_CIPHER_SAFER_SK128 = 5,
GCRY_CIPHER_DES_SK = 6,
GCRY_CIPHER_AES = 7,
GCRY_CIPHER_AES192 = 8,
GCRY_CIPHER_AES256 = 9,
GCRY_CIPHER_TWOFISH = 10,
/* Other cipher numbers are above 300 for OpenPGP reasons. */
GCRY_CIPHER_ARCFOUR = 301, /* Fully compatible with RSA's RC4 (tm). */
GCRY_CIPHER_DES = 302, /* Yes, this is single key 56 bit DES. */
GCRY_CIPHER_TWOFISH128 = 303,
GCRY_CIPHER_SERPENT128 = 304,
GCRY_CIPHER_SERPENT192 = 305,
GCRY_CIPHER_SERPENT256 = 306,
GCRY_CIPHER_RFC2268_40 = 307, /* Ron's Cipher 2 (40 bit). */
GCRY_CIPHER_RFC2268_128 = 308, /* Ron's Cipher 2 (128 bit). */
GCRY_CIPHER_SEED = 309, /* 128 bit cipher described in RFC4269. */
GCRY_CIPHER_CAMELLIA128 = 310,
GCRY_CIPHER_CAMELLIA192 = 311,
GCRY_CIPHER_CAMELLIA256 = 312
};
/* The Rijndael algorithm is basically AES, so provide some macros. */
#define GCRY_CIPHER_AES128 GCRY_CIPHER_AES
#define GCRY_CIPHER_RIJNDAEL GCRY_CIPHER_AES
#define GCRY_CIPHER_RIJNDAEL128 GCRY_CIPHER_AES128
#define GCRY_CIPHER_RIJNDAEL192 GCRY_CIPHER_AES192
#define GCRY_CIPHER_RIJNDAEL256 GCRY_CIPHER_AES256
/* The supported encryption modes. Note that not all of them are
supported for each algorithm. */
enum gcry_cipher_modes
{
GCRY_CIPHER_MODE_NONE = 0, /* Not yet specified. */
GCRY_CIPHER_MODE_ECB = 1, /* Electronic codebook. */
GCRY_CIPHER_MODE_CFB = 2, /* Cipher feedback. */
GCRY_CIPHER_MODE_CBC = 3, /* Cipher block chaining. */
GCRY_CIPHER_MODE_STREAM = 4, /* Used with stream ciphers. */
GCRY_CIPHER_MODE_OFB = 5, /* Outer feedback. */
GCRY_CIPHER_MODE_CTR = 6 /* Counter. */
};
/* Flags used with the open function. */
enum gcry_cipher_flags
{
GCRY_CIPHER_SECURE = 1, /* Allocate in secure memory. */
GCRY_CIPHER_ENABLE_SYNC = 2, /* Enable CFB sync mode. */
GCRY_CIPHER_CBC_CTS = 4, /* Enable CBC cipher text stealing (CTS). */
GCRY_CIPHER_CBC_MAC = 8 /* Enable CBC message auth. code (MAC). */
};
/* Create a handle for algorithm ALGO to be used in MODE. FLAGS may
be given as an bitwise OR of the gcry_cipher_flags values. */
gcry_error_t gcry_cipher_open (gcry_cipher_hd_t *handle,
int algo, int mode, unsigned int flags);
/* Close the cioher handle H and release all resource. */
void gcry_cipher_close (gcry_cipher_hd_t h);
/* Perform various operations on the cipher object H. */
gcry_error_t gcry_cipher_ctl (gcry_cipher_hd_t h, int cmd, void *buffer,
size_t buflen);
/* Retrieve various information about the cipher object H. */
gcry_error_t gcry_cipher_info (gcry_cipher_hd_t h, int what, void *buffer,
size_t *nbytes);
/* Retrieve various information about the cipher algorithm ALGO. */
gcry_error_t gcry_cipher_algo_info (int algo, int what, void *buffer,
size_t *nbytes);
/* Map the cipher algorithm whose ID is contained in ALGORITHM to a
string representation of the algorithm name. For unknown algorithm
IDs this function returns "?". */
const char *gcry_cipher_algo_name (int algorithm) _GCRY_GCC_ATTR_PURE;
/* Map the algorithm name NAME to an cipher algorithm ID. Return 0 if
the algorithm name is not known. */
int gcry_cipher_map_name (const char *name) _GCRY_GCC_ATTR_PURE;
/* Given an ASN.1 object identifier in standard IETF dotted decimal
format in STRING, return the encryption mode associated with that
OID or 0 if not known or applicable. */
int gcry_cipher_mode_from_oid (const char *string) _GCRY_GCC_ATTR_PURE;
/* Encrypt the plaintext of size INLEN in IN using the cipher handle H
into the buffer OUT which has an allocated length of OUTSIZE. For
most algorithms it is possible to pass NULL for in and 0 for INLEN
and do a in-place decryption of the data provided in OUT. */
gcry_error_t gcry_cipher_encrypt (gcry_cipher_hd_t h,
void *out, size_t outsize,
const void *in, size_t inlen);
/* The counterpart to gcry_cipher_encrypt. */
gcry_error_t gcry_cipher_decrypt (gcry_cipher_hd_t h,
void *out, size_t outsize,
const void *in, size_t inlen);
/* Set KEY of length KEYLEN for the cipher handle HD. */
gcry_error_t gcry_cipher_setkey (gcry_cipher_hd_t hd,
const void *key, size_t keylen);
/* Set initialization vector IV of length IVLEN for the cipher handle HD. */
gcry_error_t gcry_cipher_setiv (gcry_cipher_hd_t hd,
const void *iv, size_t ivlen);
/* Reset the handle to the state after open. */
#define gcry_cipher_reset(h) gcry_cipher_ctl ((h), GCRYCTL_RESET, NULL, 0)
/* Perform the OpenPGP sync operation if this is enabled for the
cipher handle H. */
#define gcry_cipher_sync(h) gcry_cipher_ctl( (h), GCRYCTL_CFB_SYNC, NULL, 0)
/* Enable or disable CTS in future calls to gcry_encrypt(). CBC mode only. */
#define gcry_cipher_cts(h,on) gcry_cipher_ctl( (h), GCRYCTL_SET_CBC_CTS, \
NULL, on )
/* Set counter for CTR mode. (CTR,CTRLEN) must denote a buffer of
block size length, or (NULL,0) to set the CTR to the all-zero block. */
gpg_error_t gcry_cipher_setctr (gcry_cipher_hd_t hd,
const void *ctr, size_t ctrlen);
/* Retrieved the key length used with algorithm A. */
size_t gcry_cipher_get_algo_keylen (int algo);
/* Retrieve the block length used with algorithm A. */
size_t gcry_cipher_get_algo_blklen (int algo);
/* Return 0 if the algorithm A is available for use. */
#define gcry_cipher_test_algo(a) \
gcry_cipher_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL )
/* Get a list consisting of the IDs of the loaded cipher modules. If
LIST is zero, write the number of loaded cipher modules to
LIST_LENGTH and return. If LIST is non-zero, the first
*LIST_LENGTH algorithm IDs are stored in LIST, which must be of
according size. In case there are less cipher modules than
*LIST_LENGTH, *LIST_LENGTH is updated to the correct number. */
gcry_error_t gcry_cipher_list (int *list, int *list_length);
/************************************
* *
* Asymmetric Cipher Functions *
* *
************************************/
/* The algorithms and their IDs we support. */
enum gcry_pk_algos
{
GCRY_PK_RSA = 1,
GCRY_PK_RSA_E = 2, /* (deprecated) */
GCRY_PK_RSA_S = 3, /* (deprecated) */
GCRY_PK_ELG_E = 16,
GCRY_PK_DSA = 17,
GCRY_PK_ELG = 20,
GCRY_PK_ECDSA = 301
};
/* Flags describing usage capabilities of a PK algorithm. */
#define GCRY_PK_USAGE_SIGN 1 /* Good for signatures. */
#define GCRY_PK_USAGE_ENCR 2 /* Good for encryption. */
#define GCRY_PK_USAGE_CERT 4 /* Good to certify other keys. */
#define GCRY_PK_USAGE_AUTH 8 /* Good for authentication. */
#define GCRY_PK_USAGE_UNKN 128 /* Unknown usage flag. */
/* Encrypt the DATA using the public key PKEY and store the result as
a newly created S-expression at RESULT. */
gcry_error_t gcry_pk_encrypt (gcry_sexp_t *result,
gcry_sexp_t data, gcry_sexp_t pkey);
/* Decrypt the DATA using the private key SKEY and store the result as
a newly created S-expression at RESULT. */
gcry_error_t gcry_pk_decrypt (gcry_sexp_t *result,
gcry_sexp_t data, gcry_sexp_t skey);
/* Sign the DATA using the private key SKEY and store the result as
a newly created S-expression at RESULT. */
gcry_error_t gcry_pk_sign (gcry_sexp_t *result,
gcry_sexp_t data, gcry_sexp_t skey);
/* Check the signature SIGVAL on DATA using the public key PKEY. */
gcry_error_t gcry_pk_verify (gcry_sexp_t sigval,
gcry_sexp_t data, gcry_sexp_t pkey);
/* Check that private KEY is sane. */
gcry_error_t gcry_pk_testkey (gcry_sexp_t key);
/* Generate a new key pair according to the parameters given in
S_PARMS. The new key pair is returned in as an S-expression in
R_KEY. */
gcry_error_t gcry_pk_genkey (gcry_sexp_t *r_key, gcry_sexp_t s_parms);
/* Catch all function for miscellaneous operations. */
gcry_error_t gcry_pk_ctl (int cmd, void *buffer, size_t buflen);
/* Retrieve information about the public key algorithm ALGO. */
gcry_error_t gcry_pk_algo_info (int algo, int what,
void *buffer, size_t *nbytes);
/* Map the public key algorithm whose ID is contained in ALGORITHM to
a string representation of the algorithm name. For unknown
algorithm IDs this functions returns "?". */
const char *gcry_pk_algo_name (int algorithm) _GCRY_GCC_ATTR_PURE;
/* Map the algorithm NAME to a public key algorithm Id. Return 0 if
the algorithm name is not known. */
int gcry_pk_map_name (const char* name) _GCRY_GCC_ATTR_PURE;
/* Return what is commonly referred as the key length for the given
public or private KEY. */
unsigned int gcry_pk_get_nbits (gcry_sexp_t key) _GCRY_GCC_ATTR_PURE;
/* Please note that keygrip is still experimental and should not be
used without contacting the author. */
unsigned char *gcry_pk_get_keygrip (gcry_sexp_t key, unsigned char *array);
/* Return 0 if the public key algorithm A is available for use. */
#define gcry_pk_test_algo(a) \
gcry_pk_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL )
/* Get a list consisting of the IDs of the loaded pubkey modules. If
LIST is zero, write the number of loaded pubkey modules to
LIST_LENGTH and return. If LIST is non-zero, the first
*LIST_LENGTH algorithm IDs are stored in LIST, which must be of
according size. In case there are less pubkey modules than
*LIST_LENGTH, *LIST_LENGTH is updated to the correct number. */
gcry_error_t gcry_pk_list (int *list, int *list_length);
/************************************
* *
* Cryptograhic Hash Functions *
* *
************************************/
/* Algorithm IDs for the hash functions we know about. Not all of them
are implemnted. */
enum gcry_md_algos
{
GCRY_MD_NONE = 0,
GCRY_MD_MD5 = 1,
GCRY_MD_SHA1 = 2,
GCRY_MD_RMD160 = 3,
GCRY_MD_MD2 = 5,
GCRY_MD_TIGER = 6, /* TIGER/192. */
GCRY_MD_HAVAL = 7, /* HAVAL, 5 pass, 160 bit. */
GCRY_MD_SHA256 = 8,
GCRY_MD_SHA384 = 9,
GCRY_MD_SHA512 = 10,
GCRY_MD_SHA224 = 11,
GCRY_MD_MD4 = 301,
GCRY_MD_CRC32 = 302,
GCRY_MD_CRC32_RFC1510 = 303,
GCRY_MD_CRC24_RFC2440 = 304,
GCRY_MD_WHIRLPOOL = 305
};
/* Flags used with the open function. */
enum gcry_md_flags
{
GCRY_MD_FLAG_SECURE = 1, /* Allocate all buffers in "secure" memory. */
GCRY_MD_FLAG_HMAC = 2 /* Make an HMAC out of this algorithm. */
};
/* (Forward declaration.) */
struct gcry_md_context;
/* This object is used to hold a handle to a message digest object.
This structure is private - only to be used by the public gcry_md_*
macros. */
typedef struct gcry_md_handle
{
/* Actual context. */
struct gcry_md_context *ctx;
/* Buffer management. */
int bufpos;
int bufsize;
unsigned char buf[1];
} *gcry_md_hd_t;
/* Compatibility types, do not use them. */
#ifndef GCRYPT_NO_DEPRECATED
typedef struct gcry_md_handle *GCRY_MD_HD _GCRY_GCC_ATTR_DEPRECATED;
typedef struct gcry_md_handle *GcryMDHd _GCRY_GCC_ATTR_DEPRECATED;
#endif
/* Create a message digest object for algorithm ALGO. FLAGS may be
given as an bitwise OR of the gcry_md_flags values. ALGO may be
given as 0 if the algorithms to be used are later set using
gcry_md_enable. */
gcry_error_t gcry_md_open (gcry_md_hd_t *h, int algo, unsigned int flags);
/* Release the message digest object HD. */
void gcry_md_close (gcry_md_hd_t hd);
/* Add the message digest algorithm ALGO to the digest object HD. */
gcry_error_t gcry_md_enable (gcry_md_hd_t hd, int algo);
/* Create a new digest object as an exact copy of the object HD. */
gcry_error_t gcry_md_copy (gcry_md_hd_t *bhd, gcry_md_hd_t ahd);
/* Reset the digest object HD to its initial state. */
void gcry_md_reset (gcry_md_hd_t hd);
/* Perform various operations on the digest object HD. */
gcry_error_t gcry_md_ctl (gcry_md_hd_t hd, int cmd,
void *buffer, size_t buflen);
/* Pass LENGTH bytes of data in BUFFER to the digest object HD so that
it can update the digest values. This is the actual hash
function. */
void gcry_md_write (gcry_md_hd_t hd, const void *buffer, size_t length);
/* Read out the final digest from HD return the digest value for
algorithm ALGO. */
unsigned char *gcry_md_read (gcry_md_hd_t hd, int algo);
/* Convenience function to calculate the hash from the data in BUFFER
of size LENGTH using the algorithm ALGO avoiding the creating of a
hash object. The hash is returned in the caller provided buffer
DIGEST which must be large enough to hold the digest of the given
algorithm. */
void gcry_md_hash_buffer (int algo, void *digest,
const void *buffer, size_t length);
/* Retrieve the algorithm used with HD. This does not work reliable
if more than one algorithm is enabled in HD. */
int gcry_md_get_algo (gcry_md_hd_t hd);
/* Retrieve the length in bytes of the digest yielded by algorithm
ALGO. */
unsigned int gcry_md_get_algo_dlen (int algo);
/* Return true if the the algorithm ALGO is enabled in the digest
object A. */
int gcry_md_is_enabled (gcry_md_hd_t a, int algo);
/* Return true if the digest object A is allocated in "secure" memory. */
int gcry_md_is_secure (gcry_md_hd_t a);
/* Retrieve various information about the object H. */
gcry_error_t gcry_md_info (gcry_md_hd_t h, int what, void *buffer,
size_t *nbytes);
/* Retrieve various information about the algorithm ALGO. */
gcry_error_t gcry_md_algo_info (int algo, int what, void *buffer,
size_t *nbytes);
/* Map the digest algorithm id ALGO to a string representation of the
- algorithm name. For unknown algorithms this functions returns
+ algorithm name. For unknown algorithms this function returns
"?". */
const char *gcry_md_algo_name (int algo) _GCRY_GCC_ATTR_PURE;
/* Map the algorithm NAME to a digest algorithm Id. Return 0 if
the algorithm name is not known. */
int gcry_md_map_name (const char* name) _GCRY_GCC_ATTR_PURE;
/* For use with the HMAC feature, the set MAC key to the KEY of
KEYLEN. */
gcry_error_t gcry_md_setkey (gcry_md_hd_t hd, const void *key, size_t keylen);
/* Start or stop debugging for digest handle HD; i.e. create a file
named dbgmd-<n>.<suffix> while hashing. If SUFFIX is NULL,
debugging stops and the file will be closed. */
void gcry_md_debug (gcry_md_hd_t hd, const char *suffix);
/* Update the hash(s) of H with the character C. This is a buffered
version of the gcry_md_write function. */
#define gcry_md_putc(h,c) \
do { \
gcry_md_hd_t h__ = (h); \
if( (h__)->bufpos == (h__)->bufsize ) \
gcry_md_write( (h__), NULL, 0 ); \
(h__)->buf[(h__)->bufpos++] = (c) & 0xff; \
} while(0)
/* Finalize the digest calculation. This is not really needed because
gcry_md_read() does this implicitly. */
#define gcry_md_final(a) \
gcry_md_ctl ((a), GCRYCTL_FINALIZE, NULL, 0)
/* Return 0 if the algorithm A is available for use. */
#define gcry_md_test_algo(a) \
gcry_md_algo_info( (a), GCRYCTL_TEST_ALGO, NULL, NULL )
/* Return an DER encoded ASN.1 OID for the algorithm A in buffer B. N
must point to size_t variable with the available size of buffer B.
After return it will receive the actual size of the returned
OID. */
#define gcry_md_get_asnoid(a,b,n) \
gcry_md_algo_info((a), GCRYCTL_GET_ASNOID, (b), (n))
/* Enable debugging for digest object A; i.e. create files named
dbgmd-<n>.<string> while hashing. B is a string used as the suffix
for the filename. This macro is deprecated, use gcry_md_debug. */
#ifndef GCRYPT_NO_DEPRECATED
#define gcry_md_start_debug(a,b) \
gcry_md_ctl( (a), GCRYCTL_START_DUMP, (b), 0 )
/* Disable the debugging of A. This macro is deprecated, use
gcry_md_debug. */
#define gcry_md_stop_debug(a,b) \
gcry_md_ctl( (a), GCRYCTL_STOP_DUMP, (b), 0 )
#endif
/* Get a list consisting of the IDs of the loaded message digest
modules. If LIST is zero, write the number of loaded message
digest modules to LIST_LENGTH and return. If LIST is non-zero, the
first *LIST_LENGTH algorithm IDs are stored in LIST, which must be
of according size. In case there are less message digest modules
than *LIST_LENGTH, *LIST_LENGTH is updated to the correct
number. */
gcry_error_t gcry_md_list (int *list, int *list_length);
/* Alternative interface for asymmetric cryptography. This interface
is deprecated. */
/* The algorithm IDs. */
typedef enum gcry_ac_id
{
GCRY_AC_RSA = 1,
GCRY_AC_DSA = 17,
GCRY_AC_ELG = 20,
GCRY_AC_ELG_E = 16
}
gcry_ac_id_t;
/* Key types. */
typedef enum gcry_ac_key_type
{
GCRY_AC_KEY_SECRET,
GCRY_AC_KEY_PUBLIC
}
gcry_ac_key_type_t;
/* Encoding methods. */
typedef enum gcry_ac_em
{
GCRY_AC_EME_PKCS_V1_5,
GCRY_AC_EMSA_PKCS_V1_5
}
gcry_ac_em_t;
/* Encryption and Signature schemes. */
typedef enum gcry_ac_scheme
{
GCRY_AC_ES_PKCS_V1_5,
GCRY_AC_SSA_PKCS_V1_5
}
gcry_ac_scheme_t;
/* AC data. */
#define GCRY_AC_FLAG_DEALLOC (1 << 0)
#define GCRY_AC_FLAG_COPY (1 << 1)
#define GCRY_AC_FLAG_NO_BLINDING (1 << 2)
/* This type represents a `data set'. */
typedef struct gcry_ac_data *gcry_ac_data_t;
/* This type represents a single `key', either a secret one or a
public one. */
typedef struct gcry_ac_key *gcry_ac_key_t;
/* This type represents a `key pair' containing a secret and a public
key. */
typedef struct gcry_ac_key_pair *gcry_ac_key_pair_t;
/* This type represents a `handle' that is needed by functions
performing cryptographic operations. */
typedef struct gcry_ac_handle *gcry_ac_handle_t;
typedef gpg_error_t (*gcry_ac_data_read_cb_t) (void *opaque,
unsigned char *buffer,
size_t *buffer_n);
typedef gpg_error_t (*gcry_ac_data_write_cb_t) (void *opaque,
unsigned char *buffer,
size_t buffer_n);
typedef enum
{
GCRY_AC_IO_READABLE,
GCRY_AC_IO_WRITABLE
}
gcry_ac_io_mode_t;
typedef enum
{
GCRY_AC_IO_STRING,
GCRY_AC_IO_CALLBACK
}
gcry_ac_io_type_t;
typedef struct gcry_ac_io
{
/* This is an INTERNAL structure, do NOT use manually. */
gcry_ac_io_mode_t mode _GCRY_ATTR_INTERNAL;
gcry_ac_io_type_t type _GCRY_ATTR_INTERNAL;
union
{
union
{
struct
{
gcry_ac_data_read_cb_t cb;
void *opaque;
} callback;
struct
{
unsigned char *data;
size_t data_n;
} string;
void *opaque;
} readable;
union
{
struct
{
gcry_ac_data_write_cb_t cb;
void *opaque;
} callback;
struct
{
unsigned char **data;
size_t *data_n;
} string;
void *opaque;
} writable;
} io _GCRY_ATTR_INTERNAL;
}
gcry_ac_io_t;
/* The caller of gcry_ac_key_pair_generate can provide one of these
structures in order to influence the key generation process in an
algorithm-specific way. */
typedef struct gcry_ac_key_spec_rsa
{
gcry_mpi_t e; /* E to use. */
} gcry_ac_key_spec_rsa_t;
/* Structure used for passing data to the implementation of the
`EME-PKCS-V1_5' encoding method. */
typedef struct gcry_ac_eme_pkcs_v1_5
{
size_t key_size;
} gcry_ac_eme_pkcs_v1_5_t;
typedef enum gcry_md_algos gcry_md_algo_t;
/* Structure used for passing data to the implementation of the
`EMSA-PKCS-V1_5' encoding method. */
typedef struct gcry_ac_emsa_pkcs_v1_5
{
gcry_md_algo_t md;
size_t em_n;
} gcry_ac_emsa_pkcs_v1_5_t;
/* Structure used for passing data to the implementation of the
`SSA-PKCS-V1_5' signature scheme. */
typedef struct gcry_ac_ssa_pkcs_v1_5
{
gcry_md_algo_t md;
} gcry_ac_ssa_pkcs_v1_5_t;
/* Returns a new, empty data set in DATA. */
gcry_error_t gcry_ac_data_new (gcry_ac_data_t *data);
/* Destroy the data set DATA. */
void gcry_ac_data_destroy (gcry_ac_data_t data);
/* Create a copy of the data set DATA and store it in DATA_CP. */
gcry_error_t gcry_ac_data_copy (gcry_ac_data_t *data_cp,
gcry_ac_data_t data);
/* Return the number of named MPI values inside of the data set
DATA. */
unsigned int gcry_ac_data_length (gcry_ac_data_t data);
/* Destroy any values contained in the data set DATA. */
void gcry_ac_data_clear (gcry_ac_data_t data);
/* Add the value MPI to DATA with the label NAME. If FLAGS contains
GCRY_AC_FLAG_DATA_COPY, the data set will contain copies of NAME
and MPI. If FLAGS contains GCRY_AC_FLAG_DATA_DEALLOC or
GCRY_AC_FLAG_DATA_COPY, the values contained in the data set will
be deallocated when they are to be removed from the data set. */
gcry_error_t gcry_ac_data_set (gcry_ac_data_t data, unsigned int flags,
const char *name, gcry_mpi_t mpi);
/* Store the value labelled with NAME found in DATA in MPI. If FLAGS
contains GCRY_AC_FLAG_COPY, store a copy of the MPI value contained
in the data set. MPI may be NULL. */
gcry_error_t gcry_ac_data_get_name (gcry_ac_data_t data, unsigned int flags,
const char *name, gcry_mpi_t *mpi);
/* Stores in NAME and MPI the named MPI value contained in the data
set DATA with the index IDX. If FLAGS contains GCRY_AC_FLAG_COPY,
store copies of the values contained in the data set. NAME or MPI
may be NULL. */
gcry_error_t gcry_ac_data_get_index (gcry_ac_data_t data, unsigned int flags,
unsigned int idx,
const char **name, gcry_mpi_t *mpi);
/* Convert the data set DATA into a new S-Expression, which is to be
stored in SEXP, according to the identifiers contained in
IDENTIFIERS. */
gcry_error_t gcry_ac_data_to_sexp (gcry_ac_data_t data, gcry_sexp_t *sexp,
const char **identifiers);
/* Create a new data set, which is to be stored in DATA_SET, from the
S-Expression SEXP, according to the identifiers contained in
IDENTIFIERS. */
gcry_error_t gcry_ac_data_from_sexp (gcry_ac_data_t *data, gcry_sexp_t sexp,
const char **identifiers);
/* Initialize AC_IO according to MODE, TYPE and the variable list of
arguments. The list of variable arguments to specify depends on
the given TYPE. */
void gcry_ac_io_init (gcry_ac_io_t *ac_io, gcry_ac_io_mode_t mode,
gcry_ac_io_type_t type, ...);
/* Initialize AC_IO according to MODE, TYPE and the variable list of
arguments AP. The list of variable arguments to specify depends on
the given TYPE. */
void gcry_ac_io_init_va (gcry_ac_io_t *ac_io, gcry_ac_io_mode_t mode,
gcry_ac_io_type_t type, va_list ap);
/* Create a new ac handle. */
gcry_error_t gcry_ac_open (gcry_ac_handle_t *handle,
gcry_ac_id_t algorithm, unsigned int flags);
/* Destroy an ac handle. */
void gcry_ac_close (gcry_ac_handle_t handle);
/* Initialize a key from a given data set. */
gcry_error_t gcry_ac_key_init (gcry_ac_key_t *key, gcry_ac_handle_t handle,
gcry_ac_key_type_t type, gcry_ac_data_t data);
/* Generates a new key pair via the handle HANDLE of NBITS bits and
stores it in KEY_PAIR. In case non-standard settings are wanted, a
pointer to a structure of type gcry_ac_key_spec_<algorithm>_t,
matching the selected algorithm, can be given as KEY_SPEC.
MISC_DATA is not used yet. */
gcry_error_t gcry_ac_key_pair_generate (gcry_ac_handle_t handle,
unsigned int nbits, void *spec,
gcry_ac_key_pair_t *key_pair,
gcry_mpi_t **misc_data);
/* Returns the key of type WHICH out of the key pair KEY_PAIR. */
gcry_ac_key_t gcry_ac_key_pair_extract (gcry_ac_key_pair_t key_pair,
gcry_ac_key_type_t which);
/* Returns the data set contained in the key KEY. */
gcry_ac_data_t gcry_ac_key_data_get (gcry_ac_key_t key);
/* Verifies that the key KEY is sane via HANDLE. */
gcry_error_t gcry_ac_key_test (gcry_ac_handle_t handle, gcry_ac_key_t key);
/* Stores the number of bits of the key KEY in NBITS via HANDLE. */
gcry_error_t gcry_ac_key_get_nbits (gcry_ac_handle_t handle,
gcry_ac_key_t key, unsigned int *nbits);
/* Writes the 20 byte long key grip of the key KEY to KEY_GRIP via
HANDLE. */
gcry_error_t gcry_ac_key_get_grip (gcry_ac_handle_t handle, gcry_ac_key_t key,
unsigned char *key_grip);
/* Destroy a key. */
void gcry_ac_key_destroy (gcry_ac_key_t key);
/* Destroy a key pair. */
void gcry_ac_key_pair_destroy (gcry_ac_key_pair_t key_pair);
/* Encodes a message according to the encoding method METHOD. OPTIONS
must be a pointer to a method-specific structure
(gcry_ac_em*_t). */
gcry_error_t gcry_ac_data_encode (gcry_ac_em_t method,
unsigned int flags, void *options,
gcry_ac_io_t *io_read,
gcry_ac_io_t *io_write);
/* Decodes a message according to the encoding method METHOD. OPTIONS
must be a pointer to a method-specific structure
(gcry_ac_em*_t). */
gcry_error_t gcry_ac_data_decode (gcry_ac_em_t method,
unsigned int flags, void *options,
gcry_ac_io_t *io_read,
gcry_ac_io_t *io_write);
/* Encrypt the plain text MPI value DATA_PLAIN with the key KEY under
the control of the flags FLAGS and store the resulting data set
into DATA_ENCRYPTED. */
gcry_error_t gcry_ac_data_encrypt (gcry_ac_handle_t handle,
unsigned int flags,
gcry_ac_key_t key,
gcry_mpi_t data_plain,
gcry_ac_data_t *data_encrypted);
/* Decrypt the decrypted data contained in the data set DATA_ENCRYPTED
with the key KEY under the control of the flags FLAGS and store the
resulting plain text MPI value in DATA_PLAIN. */
gcry_error_t gcry_ac_data_decrypt (gcry_ac_handle_t handle,
unsigned int flags,
gcry_ac_key_t key,
gcry_mpi_t *data_plain,
gcry_ac_data_t data_encrypted);
/* Sign the data contained in DATA with the key KEY and store the
resulting signature in the data set DATA_SIGNATURE. */
gcry_error_t gcry_ac_data_sign (gcry_ac_handle_t handle,
gcry_ac_key_t key,
gcry_mpi_t data,
gcry_ac_data_t *data_signature);
/* Verify that the signature contained in the data set DATA_SIGNATURE
is indeed the result of signing the data contained in DATA with the
secret key belonging to the public key KEY. */
gcry_error_t gcry_ac_data_verify (gcry_ac_handle_t handle,
gcry_ac_key_t key,
gcry_mpi_t data,
gcry_ac_data_t data_signature);
/* Encrypts the plain text readable from IO_MESSAGE through HANDLE
with the public key KEY according to SCHEME, FLAGS and OPTS. If
OPTS is not NULL, it has to be a pointer to a structure specific to
the chosen scheme (gcry_ac_es_*_t). The encrypted message is
written to IO_CIPHER. */
gcry_error_t gcry_ac_data_encrypt_scheme (gcry_ac_handle_t handle,
gcry_ac_scheme_t scheme,
unsigned int flags, void *opts,
gcry_ac_key_t key,
gcry_ac_io_t *io_message,
gcry_ac_io_t *io_cipher);
/* Decrypts the cipher text readable from IO_CIPHER through HANDLE
with the secret key KEY according to SCHEME, @var{flags} and OPTS.
If OPTS is not NULL, it has to be a pointer to a structure specific
to the chosen scheme (gcry_ac_es_*_t). The decrypted message is
written to IO_MESSAGE. */
gcry_error_t gcry_ac_data_decrypt_scheme (gcry_ac_handle_t handle,
gcry_ac_scheme_t scheme,
unsigned int flags, void *opts,
gcry_ac_key_t key,
gcry_ac_io_t *io_cipher,
gcry_ac_io_t *io_message);
/* Signs the message readable from IO_MESSAGE through HANDLE with the
secret key KEY according to SCHEME, FLAGS and OPTS. If OPTS is not
NULL, it has to be a pointer to a structure specific to the chosen
scheme (gcry_ac_ssa_*_t). The signature is written to
IO_SIGNATURE. */
gcry_error_t gcry_ac_data_sign_scheme (gcry_ac_handle_t handle,
gcry_ac_scheme_t scheme,
unsigned int flags, void *opts,
gcry_ac_key_t key,
gcry_ac_io_t *io_message,
gcry_ac_io_t *io_signature);
/* Verifies through HANDLE that the signature readable from
IO_SIGNATURE is indeed the result of signing the message readable
from IO_MESSAGE with the secret key belonging to the public key KEY
according to SCHEME and OPTS. If OPTS is not NULL, it has to be an
anonymous structure (gcry_ac_ssa_*_t) specific to the chosen
scheme. */
gcry_error_t gcry_ac_data_verify_scheme (gcry_ac_handle_t handle,
gcry_ac_scheme_t scheme,
unsigned int flags, void *opts,
gcry_ac_key_t key,
gcry_ac_io_t *io_message,
gcry_ac_io_t *io_signature);
/* Store the textual representation of the algorithm whose id is given
in ALGORITHM in NAME. This function is deprecated; use
gcry_pk_algo_name. */
#ifndef GCRYPT_NO_DEPRECATED
gcry_error_t gcry_ac_id_to_name (gcry_ac_id_t algorithm,
const char **name)
/* */ _GCRY_GCC_ATTR_DEPRECATED;
/* Store the numeric ID of the algorithm whose textual representation
is contained in NAME in ALGORITHM. This function is deprecated;
use gcry_pk_map_name. */
gcry_error_t gcry_ac_name_to_id (const char *name,
gcry_ac_id_t *algorithm)
/* */ _GCRY_GCC_ATTR_DEPRECATED;
#endif
/************************************
* *
* Random Generating Functions *
* *
************************************/
/* The possible values for the random quality. The rule of thumb is
to use STRONG for session keys and VERY_STRONG for key material.
WEAK is usually an alias for STRONG and should not be used anymore
(except with gcry_mpi_randomize); use gcry_create_nonce instead. */
typedef enum gcry_random_level
{
GCRY_WEAK_RANDOM = 0,
GCRY_STRONG_RANDOM = 1,
GCRY_VERY_STRONG_RANDOM = 2
}
gcry_random_level_t;
/* Fill BUFFER with LENGTH bytes of random, using random numbers of
quality LEVEL. */
void gcry_randomize (void *buffer, size_t length,
enum gcry_random_level level);
/* Add the external random from BUFFER with LENGTH bytes into the
pool. QUALITY should either be -1 for unknown or in the range of 0
to 100 */
gcry_error_t gcry_random_add_bytes (const void *buffer, size_t length,
int quality);
/* If random numbers are used in an application, this macro should be
called from time to time so that new stuff gets added to the
internal pool of the RNG. */
#define gcry_fast_random_poll() gcry_control (GCRYCTL_FAST_POLL, NULL)
/* Return NBYTES of allocated random using a random numbers of quality
LEVEL. */
void *gcry_random_bytes (size_t nbytes, enum gcry_random_level level)
_GCRY_GCC_ATTR_MALLOC;
/* Return NBYTES of allocated random using a random numbers of quality
LEVEL. The random numbers are created returned in "secure"
memory. */
void *gcry_random_bytes_secure (size_t nbytes, enum gcry_random_level level)
_GCRY_GCC_ATTR_MALLOC;
/* Set the big integer W to a random value of NBITS using a random
generator with quality LEVEL. Note that using a level of
GCRY_WEAK_RANDOM here, uses gcry_create_nonce internally. */
void gcry_mpi_randomize (gcry_mpi_t w,
unsigned int nbits, enum gcry_random_level level);
/* Create an unpredicable nonce of LENGTH bytes in BUFFER. */
void gcry_create_nonce (void *buffer, size_t length);
/*******************************/
/* */
/* Prime Number Functions */
/* */
/*******************************/
/* Mode values passed to a gcry_prime_check_func_t. */
#define GCRY_PRIME_CHECK_AT_FINISH 0
#define GCRY_PRIME_CHECK_AT_GOT_PRIME 1
#define GCRY_PRIME_CHECK_AT_MAYBE_PRIME 2
/* The function should return 1 if the operation shall continue, 0 to
reject the prime candidate. */
typedef int (*gcry_prime_check_func_t) (void *arg, int mode,
gcry_mpi_t candidate);
/* Flags for gcry_prime_generate(): */
/* Allocate prime numbers and factors in secure memory. */
#define GCRY_PRIME_FLAG_SECRET (1 << 0)
/* Make sure that at least one prime factor is of size
`FACTOR_BITS'. */
#define GCRY_PRIME_FLAG_SPECIAL_FACTOR (1 << 1)
/* Generate a new prime number of PRIME_BITS bits and store it in
PRIME. If FACTOR_BITS is non-zero, one of the prime factors of
(prime - 1) / 2 must be FACTOR_BITS bits long. If FACTORS is
non-zero, allocate a new, NULL-terminated array holding the prime
factors and store it in FACTORS. FLAGS might be used to influence
the prime number generation process. */
gcry_error_t gcry_prime_generate (gcry_mpi_t *prime,
unsigned int prime_bits,
unsigned int factor_bits,
gcry_mpi_t **factors,
gcry_prime_check_func_t cb_func,
void *cb_arg,
gcry_random_level_t random_level,
unsigned int flags);
/* Find a generator for PRIME where the factorization of (prime-1) is
in the NULL terminated array FACTORS. Return the generator as a
newly allocated MPI in R_G. If START_G is not NULL, use this as
teh start for the search. */
gcry_error_t gcry_prime_group_generator (gcry_mpi_t *r_g,
gcry_mpi_t prime,
gcry_mpi_t *factors,
gcry_mpi_t start_g);
/* Convenience function to release the FACTORS array. */
void gcry_prime_release_factors (gcry_mpi_t *factors);
/* Check wether the number X is prime. */
gcry_error_t gcry_prime_check (gcry_mpi_t x, unsigned int flags);
/************************************
* *
* Miscellaneous Stuff *
* *
************************************/
/* Log levels used by the internal logging facility. */
enum gcry_log_levels
{
GCRY_LOG_CONT = 0, /* (Continue the last log line.) */
GCRY_LOG_INFO = 10,
GCRY_LOG_WARN = 20,
GCRY_LOG_ERROR = 30,
GCRY_LOG_FATAL = 40,
GCRY_LOG_BUG = 50,
GCRY_LOG_DEBUG = 100
};
/* Type for progress handlers. */
typedef void (*gcry_handler_progress_t) (void *, const char *, int, int, int);
/* Type for memory allocation handlers. */
typedef void *(*gcry_handler_alloc_t) (size_t n);
/* Type for secure memory check handlers. */
typedef int (*gcry_handler_secure_check_t) (const void *);
/* Type for memory reallocation handlers. */
typedef void *(*gcry_handler_realloc_t) (void *p, size_t n);
/* Type for memory free handlers. */
typedef void (*gcry_handler_free_t) (void *);
/* Type for out-of-memory handlers. */
typedef int (*gcry_handler_no_mem_t) (void *, size_t, unsigned int);
/* Type for fatal error handlers. */
typedef void (*gcry_handler_error_t) (void *, int, const char *);
/* Type for logging handlers. */
typedef void (*gcry_handler_log_t) (void *, int, const char *, va_list);
/* Certain operations can provide progress information. This function
is used to register a handler for retrieving these information. */
void gcry_set_progress_handler (gcry_handler_progress_t cb, void *cb_data);
/* Register a custom memory allocation functions. */
void gcry_set_allocation_handler (
gcry_handler_alloc_t func_alloc,
gcry_handler_alloc_t func_alloc_secure,
gcry_handler_secure_check_t func_secure_check,
gcry_handler_realloc_t func_realloc,
gcry_handler_free_t func_free);
/* Register a function used instead of the internal out of memory
handler. */
void gcry_set_outofcore_handler (gcry_handler_no_mem_t h, void *opaque);
/* Register a function used instead of the internal fatal error
handler. */
void gcry_set_fatalerror_handler (gcry_handler_error_t fnc, void *opaque);
/* Register a function used instead of the internal logging
facility. */
void gcry_set_log_handler (gcry_handler_log_t f, void *opaque);
/* Reserved for future use. */
void gcry_set_gettext_handler (const char *(*f)(const char*));
/* Libgcrypt uses its own memory allocation. It is important to use
gcry_free () to release memory allocated by libgcrypt. */
void *gcry_malloc (size_t n) _GCRY_GCC_ATTR_MALLOC;
void *gcry_calloc (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC;
void *gcry_malloc_secure (size_t n) _GCRY_GCC_ATTR_MALLOC;
void *gcry_calloc_secure (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC;
void *gcry_realloc (void *a, size_t n);
char *gcry_strdup (const char *string) _GCRY_GCC_ATTR_MALLOC;
void *gcry_xmalloc (size_t n) _GCRY_GCC_ATTR_MALLOC;
void *gcry_xcalloc (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC;
void *gcry_xmalloc_secure (size_t n) _GCRY_GCC_ATTR_MALLOC;
void *gcry_xcalloc_secure (size_t n, size_t m) _GCRY_GCC_ATTR_MALLOC;
void *gcry_xrealloc (void *a, size_t n);
char *gcry_xstrdup (const char * a) _GCRY_GCC_ATTR_MALLOC;
void gcry_free (void *a);
/* Return true if A is allocated in "secure" memory. */
int gcry_is_secure (const void *a) _GCRY_GCC_ATTR_PURE;
/* Return true if Libgcrypt is in FIPS mode. */
#define gcry_fips_mode_active() !!gcry_control (GCRYCTL_FIPS_MODE_P, 0)
/* Include support for Libgcrypt modules. */
#include <gcrypt-module.h>
#if 0 /* (Keep Emacsens' auto-indent happy.) */
{
#endif
#ifdef __cplusplus
}
#endif
#endif /* _GCRYPT_H */
diff --git a/src/module.c b/src/module.c
index f6a24209..c70a44c0 100644
--- a/src/module.c
+++ b/src/module.c
@@ -1,212 +1,212 @@
/* module.c - Module management for libgcrypt.
* Copyright (C) 2003, 2008 Free Software Foundation, Inc.
*
* This file is part of Libgcrypt.
*
* Libgcrypt is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser general Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* Libgcrypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#include <config.h>
#include <errno.h>
#include "g10lib.h"
/* Please match these numbers with the allocated algorithm
numbers. */
#define MODULE_ID_MIN 600
#define MODULE_ID_LAST 65500
-#define MODULE_ID_USER 1024
-#define MODULE_ID_USER_LAST 4095
+#define MODULE_ID_USER GCRY_MODULE_ID_USER
+#define MODULE_ID_USER_LAST GCRY_MODULE_ID_USER_LAST
#if MODULE_ID_MIN >= MODULE_ID_USER
#error Need to implement a different search strategy
#endif
/* Internal function. Generate a new, unique module ID for a module
that should be inserted into the module chain starting at
MODULES. */
static gcry_err_code_t
_gcry_module_id_new (gcry_module_t modules, unsigned int *id_new)
{
unsigned int mod_id;
gcry_err_code_t err = GPG_ERR_NO_ERROR;
gcry_module_t module;
/* Search for unused ID. */
for (mod_id = MODULE_ID_MIN; mod_id < MODULE_ID_LAST; mod_id++)
{
if (mod_id == MODULE_ID_USER)
{
mod_id = MODULE_ID_USER_LAST;
continue;
}
/* Search for a module with the current ID. */
for (module = modules; module; module = module->next)
if (mod_id == module->mod_id)
break;
if (! module)
/* None found -> the ID is available for use. */
break;
}
if (mod_id < MODULE_ID_LAST)
/* Done. */
*id_new = mod_id;
else
/* No free ID found. */
err = GPG_ERR_INTERNAL;
return err;
}
/* Add a module specification to the list ENTRIES. The new module has
it's use-counter set to one. */
gcry_err_code_t
_gcry_module_add (gcry_module_t *entries, unsigned int mod_id,
void *spec, void *extraspec, gcry_module_t *module)
{
gcry_err_code_t err = 0;
gcry_module_t entry;
if (! mod_id)
err = _gcry_module_id_new (*entries, &mod_id);
if (! err)
{
entry = gcry_malloc (sizeof (struct gcry_module));
if (! entry)
err = gpg_err_code_from_errno (errno);
}
if (! err)
{
/* Fill new module entry. */
entry->flags = 0;
entry->counter = 1;
entry->spec = spec;
entry->extraspec = extraspec;
entry->mod_id = mod_id;
/* Link it into the list. */
entry->next = *entries;
entry->prevp = entries;
if (*entries)
(*entries)->prevp = &entry->next;
*entries = entry;
/* And give it to the caller. */
if (module)
*module = entry;
}
return err;
}
/* Internal function. Unlink CIPHER_ENTRY from the list of registered
ciphers and destroy it. */
static void
_gcry_module_drop (gcry_module_t entry)
{
*entry->prevp = entry->next;
if (entry->next)
entry->next->prevp = entry->prevp;
gcry_free (entry);
}
/* Lookup a module specification by it's ID. After a successfull
lookup, the module has it's resource counter incremented. */
gcry_module_t
_gcry_module_lookup_id (gcry_module_t entries, unsigned int mod_id)
{
gcry_module_t entry;
for (entry = entries; entry; entry = entry->next)
if (entry->mod_id == mod_id)
{
entry->counter++;
break;
}
return entry;
}
/* Lookup a module specification. After a successfull lookup, the
module has it's resource counter incremented. FUNC is a function
provided by the caller, which is responsible for identifying the
wanted module. */
gcry_module_t
_gcry_module_lookup (gcry_module_t entries, void *data,
gcry_module_lookup_t func)
{
gcry_module_t entry;
for (entry = entries; entry; entry = entry->next)
if ((*func) (entry->spec, data))
{
entry->counter++;
break;
}
return entry;
}
/* Release a module. In case the use-counter reaches zero, destroy
the module. Passing MODULE as NULL is a dummy operation (similar
to free()). */
void
_gcry_module_release (gcry_module_t module)
{
if (module && ! --module->counter)
_gcry_module_drop (module);
}
/* Add a reference to a module. */
void
_gcry_module_use (gcry_module_t module)
{
++module->counter;
}
/* If LIST is zero, write the number of modules identified by MODULES
to LIST_LENGTH and return. If LIST is non-zero, the first
*LIST_LENGTH algorithm IDs are stored in LIST, which must be of
according size. In case there are less cipher modules than
*LIST_LENGTH, *LIST_LENGTH is updated to the correct number. */
gcry_err_code_t
_gcry_module_list (gcry_module_t modules,
int *list, int *list_length)
{
gcry_err_code_t err = GPG_ERR_NO_ERROR;
gcry_module_t module;
int length, i;
for (module = modules, length = 0; module; module = module->next, length++);
if (list)
{
if (length > *list_length)
length = *list_length;
for (module = modules, i = 0; i < length; module = module->next, i++)
list[i] = module->mod_id;
if (length < *list_length)
*list_length = length;
}
else
*list_length = length;
return err;
}
diff --git a/tests/ChangeLog b/tests/ChangeLog
index 6e6a3117..4a5c68b8 100644
--- a/tests/ChangeLog
+++ b/tests/ChangeLog
@@ -1,615 +1,637 @@
+2008-10-02 Werner Koch <wk@g10code.com>
+
+ * fipsdrv.c (print_buffer): Add base64 printing code.
+ (base64_decode, read_key_file,parse_tag): New.
+ (run_rsa_gen, run_rsa_sign): New.
+ (main): Add mode rsa-gen and rsa-sign.
+
+2008-09-29 Werner Koch <wk@g10code.com>
+
+ * fipsdrv.c: Merge code from fipsrngdrv.c
+ * fipsrngdrv.c: Remove.
+
+2008-09-26 Werner Koch <wk@g10code.com>
+
+ * Makefile.am: Distribute cavs_driver.pl.
+ * cavs_tests.sh: New.
+ * fipsdrv.c: New.
+
+2008-09-18 Werner Koch <wk@g10code.com>
+
+ * benchmark.c (main): Do not disable secure memory in FIPS mode.
+
2008-09-18 Werner Koch <wk@g10code.com>
* basic.c (main): Do not disable secure memory in FIPS mode.
2008-09-16 Werner Koch <wk@g10code.com>
* fipsrngdrv.c (main): Bail out on write error. Implement verbose
option.
(main): Use flag to disable dup block checks.
2008-09-15 Werner Koch <wk@g10code.com>
* fipsrngdrv.c: New.
2008-09-09 Werner Koch <wk@g10code.com>
* basic.c (main): New option --selftest.
2008-08-29 Werner Koch <wk@g10code.com>
* keygrip.c: Update to also check ECDSA.
2008-08-28 Werner Koch <wk@g10code.com>
* rsa-16k.key: New sample key.
2008-08-27 Werner Koch <wk@g10code.com>
* pkbench.c (read_file): New.
(process_key_pair_file): Replace mmap by read_file.
(main): Add a --fips option.
* Makefile.am (EXTRA_DIST): Remove.
(EXTRA_PROGRAMS): Add pkbench.
* basic.c (main): Extended FIPS self-test test.
2008-08-26 Werner Koch <wk@g10code.com>
* basic.c (get_keys_new): Use transient-key flag.
* benchmark.c (main): First check options then do the libgcrypt
initialization.
(rsa_bench): Use transient-key flag if not in fips mode.
2008-08-20 Werner Koch <wk@g10code.com>
* t-mpi-bit.c (test_lshift): New.
(mpi2bitstr_nlz, lshiftbitstring): New.
(main): Run test.
2008-08-18 Werner Koch <wk@g10code.com>
* basic.c (main): Add option --fips.
2008-08-15 Werner Koch <wk@g10code.com>
* register.c (main): Check for fips mode.
(check_run): Take care of fips mode.
* basic.c (check_cbc_mac_cipher, check_ciphers, check_digests)
(check_hmac, check_pubkey): Do not test unavalaible algorithms in
fips mode.
(main): Check for fips mode.
2008-04-22 Werner Koch <wk@g10code.com>
* basic.c (check_one_cipher): Also check in-place encryption.
2008-03-17 Werner Koch <wk@g10code.com>
* benchmark.c (main): Add option --cipher-repetition.
(cipher_bench): Use it.
2008-03-12 Werner Koch <wk@g10code.com>
* benchmark.c (rsa_bench): Add arg NO_BLINDING.
(main): Add option --no-blinding.
2007-12-05 Werner Koch <wk@g10code.com>
* pubkey.c (sample_private_key_1_1,sample_private_key_1_2): New.
(get_keys_sample): Add arg SECRET_VARIANT.
(check_run): Check all variants. Also check gcry_pk_testkey.
(check_keys_crypt): Add DECRYPT_FAIL_CODE.
(check_keys): Ditto.
2007-11-30 Werner Koch <wk@g10code.com>
* benchmark.c (main): Add optione --verbose and reworked the
option parsing.
(random_bench): Dump random stats.
2007-10-31 Werner Koch <wk@g10code.com>
* benchmark.c (start_timer, stop_timer, elapsed_time) [W32]: Fixed.
2007-06-20 Werner Koch <wk@g10code.com>
* benchmark.c (rsa_bench): New.
(main): New command "rsa".
2007-05-03 Werner Koch <wk@g10code.com>
* Makefile.am (EXTRA_DIST): Do not build pkbench.c
2007-05-02 David Shaw <dshaw@jabberwocky.com>
* basic.c (check_ciphers): Add Camellia.
2007-04-30 David Shaw <dshaw@jabberwocky.com>
* basic.c (check_ciphers): #if out ciphers we don't have. Add
test for GCRY_CIPHER_RFC2268_40.
2007-04-30 Werner Koch <wk@g10code.com>
* version.c: New.
* Makefile.am (TESTS): Add version.
2007-04-30 Marcus Brinkmann <marcus@g10code.de>
* benchmark.c (ecc_bench): Release KEY_SPEC.
2007-04-28 Marcus Brinkmann <marcus@g10code.de>
* ac-data.c (check_run): Don't give redundant GCRY_AC_FLAG_DEALLOC
in addition to GCRY_AC_FLAG_COPY. Don't release LABEL1 or MPI0,
as those are donated to libgcrypt, but do release MPI0 and MPI2.
2007-04-12 Marcus Brinkmann <marcus@g10code.de>
* ac-schemes.c (scheme_spec): Revert last change.
* ac-schemes.c (scheme_spec): Remove const qualifier from member M.
(es_check): Remove const qualifier from C and M2.
2007-03-28 Werner Koch <wk@g10code.com>
* pkbench.c (generate_key): Support named curves.
* benchmark.c (dsa_bench): New args ITERATIONS and PRINT_HEADER.
(main): Call dsa and ecc benchs.
(show_sexp): New.
* Makefile.am (TESTS): Move pkbench to EXTRA_PROGRAMS.
2007-03-22 Werner Koch <wk@g10code.com>
* benchmark.c (die): New.
(ecc_bench): New.
* pkbench.c (main): Reworked to provide proper option handling.
2007-03-13 Werner Koch <wk@g10code.com>
* mpitests.c: Reformatted to GNU standards.
(main): Add options --verbose and --debug for future use.
2007-03-13 Werner Dittmann <Werner.Dittmann@t-online.de> (wk)
* mpitests.c: New.
2007-02-23 Werner Koch <wk@g10code.com>
* Makefile.am (TEST): Run benchmark as last.
* ac-data.c (check_sexp_conversion): Print label only in verbose
mode.
* pubkey.c (main): Run test just 2 times instead of 10.
(get_elg_key_new): New.
(check_run): Also run tests with Elgamal keys.
(check_keys): New arg NBITS_DATA.
(get_elg_key_new): Use only 400 for the 512 bit Elgamal test.
* random.c: New.
2007-02-22 Werner Koch <wk@g10code.com>
* basic.c (check_pubkey_sign): Also try signing using an OID.
* Makefile.am (TESTS) [W32]: Removed pkbench for now.
* pkbench.c (benchmark): Fixed for W32.
2007-02-21 Werner Koch <wk@g10code.com>
* hmac.c (check_one_mac): Make pointer args const.
* basic.c (check_one_md): Ditto.
(check_one_hmac): Ditto.
* keygen.c (progress_cb): Filter out line feeds.
* basic.c (progress_handler): Ditto.
2006-12-18 Werner Koch <wk@g10code.com>
* Makefile.am (AM_CFLAGS, AM_CPPFLAGS): Splitted and merged with
Moritz' changes.
(INCLUDES): Removed.
* keygen.c (progress_handler): New.
(main): Use it in verbose mode.
2006-11-05 Moritz Schulte <moritz@g10code.com>
* Makefile.am (AM_CFLAGS): Added -I$(top_builddir)/src so that the
new gcrypt.h is used, not the one installed in the system.
2006-10-17 Werner Koch <wk@g10code.com>
* keygen.c (check_rsa_keys): Also create an 1536 bit DSA key.
2006-08-03 Werner Koch <wk@g10code.com>
* t-mpi-bit.c: New.
2006-07-06 Werner Koch <wk@g10code.com>
* benchmark.c (main): New option --use-random-daemon. New command
strongrandom.
(random_bench): New arg VERY_STRONG.
2006-03-14 Werner Koch <wk@g10code.com>
* benchmark.c (main): Allow for seed file argument to random bench.
* basic.c (main): Use progress handler only in verbose mode.
(main): Speed up test key generation.
* ac-data.c (check_sexp_conversion, check_run): Take care of VERBOSE.
* ac.c (main): Ditto.
* pubkey.c (main): Ditto.
* pkbench.c (main): Ditto.
* keygen.c (main): Ditto.
(check_rsa_keys): Print key only in verbose mode.
2006-03-10 Brad Hards <bradh@frogmouth.net> (wk, patch 2006-02-18)
* basic.c (check_one_hmac, check_hmac): New.
2006-03-07 Werner Koch <wk@g10code.com>
* benchmark.c (cipher_bench): Add OFB mode.
2006-01-18 Brad Hards <bradh@frogmouth.net> (wk 2006-03-07)
* basic.c: Added test cases for OFB and CFB modes. Fixed some
compiler warnings for signedness.
2005-11-12 Moritz Schulte <moritz@g10code.com>
* ac-data.c: Added way more test cases.
2005-09-15 Moritz Schulte <moritz@g10code.com>
* Makefile.am (TESTS): Added keygrip.
* keygrip.c: New.
2005-09-19 Werner Koch <wk@g10code.com>
* benchmark.c (dsa_bench): New.
2005-08-19 Werner Koch <wk@g10code.com>
* hmac.c (main): Added all FIPS tests.
2005-08-18 Werner Koch <wk@g10code.com>
* hmac.c: New.
2005-04-22 Moritz Schulte <moritz@g10code.com>
* tsexp.c: Include <config.h> in case HAVE_CONFIG_H is defined;
thanks to Albert Chin.
* testapi.c: Likewise.
* register.c: Likewise.
* pubkey.c: Likewise.
* prime.c: Likewise.
* pkbench.c: Likewise.
* keygen.c: Likewise.
* benchmark.c: Likewise.
* basic.c: Likewise.
* ac-schemes.c: Likewise.
* ac-data.c: Likewise.
* ac.c: Likewise.
2005-04-16 Moritz Schulte <moritz@g10code.com>
* ac-data.c (check_run): Include new test.
2005-04-11 Moritz Schulte <moritz@g10code.com>
* basic.c (check_digests): Add tests for Whirlpool.
2005-03-30 Moritz Schulte <moritz@g10code.com>
* ac-schemes.c: New file.
* ac-data.c: New file.
* Makefile.am (TESTS): Added ac-schemes and ac-data.
2004-09-15 Moritz Schulte <moritz@g10code.com>
* pkbench.c: Include <time.h>.
2004-08-24 Moritz Schulte <moritz@g10code.com>
* pkbench.c (context_init): Improve generation of test data.
2004-08-23 Moritz Schulte <moritz@g10code.com>
* Makefile.am (TESTS): Added: pkbench.
* pkbench.c: New file.
2004-02-25 Werner Koch <wk@gnupg.org>
* Makefile.am (TEST): Add benchmark.
* benchmark.c (md_bench, cipher_bench): Allow NULL arg to to run
tests for all algorithms.
(main): Run all tests by default.
2004-02-03 Werner Koch <wk@gnupg.org>
* tsexp.c (basic): New pass to check secure memory switching.
2004-01-12 Moritz Schulte <mo@g10code.com>
* ac.c (check_one): Adjust to new ac API.
2003-11-22 Werner Koch <wk@gnupg.org>
* pubkey.c (check_keys_crypt): Fixed my last patch.
2003-11-11 Werner Koch <wk@gnupg.org>
* tsexp.c (basic): Add pass structure and a test for the %b
format.
2003-11-04 Werner Koch <wk@gnupg.org>
* Makefile.am (noinst_PROGRAMS): Use this so that test programs
get always build.
* keygen.c (check_nonce): New.
(main): Add a basic check for the nocen function.
2003-10-31 Werner Koch <wk@gnupg.org>
* basic.c (check_aes128_cbc_cts_cipher): Make it a prototype
* ac.c (check_run): Comment unused variable.
2003-10-10 Werner Koch <wk@gnupg.org>
* prime.c (check_primes): Generate a generator and avoid printing
unless in verbose mode.
2003-10-07 Werner Koch <wk@gnupg.org>
* tsexp.c (check_sscan): New.
2003-09-04 Werner Koch <wk@gnupg.org>
* pubkey.c (check_keys_crypt): Fix for compatibility mode.
2003-09-02 Moritz Schulte <mo@g10code.com>
* Makefile.am (TESTS): Added: prime.
* prime.c: New file.
2003-08-27 Moritz Schulte <mo@g10code.com>
* basic.c (check_ciphers): Added: Serpent.
Write braces around flags.
2003-08-04 Moritz Schulte <moritz@g10code.com>
* benchmark.c (do_powm): Adjust for new gcry_mpi_scan interface.
2003-07-23 Moritz Schulte <moritz@g10code.com>
* ac.c (key_copy): New function...
(check_one): ... use it.
2003-07-22 Moritz Schulte <moritz@g10code.com>
* basic.c (check_ciphers): Use gcry_cipher_map_name.
2003-07-18 Moritz Schulte <moritz@g10code.com>
* ac.c (check_run): Renamed to ...
(check_one): ... this, changed calling interface.
(check_run): New function.
* register.c: Adjust gcry_cipher_spec_t structure.
2003-07-14 Moritz Schulte <moritz@g10code.com>
* register.c: Adjust cipher specification structure.
* benchmark.c: New file.
* testapi.c: New file.
* Makefile.am (EXTRA_PROGRAMS): Set to: benchmark testapi.
(check_PROGRAMS): Set to: $(TESTS).
2003-07-12 Moritz Schulte <moritz@g10code.com>
* ac.c, basic.c, keygen.c, register.c, sexp.c, tsexp.c: Used
gcry_err* wrappers for libgpg symbols.
* basic.c (check_ciphers): Added: GCRY_CIPHER_TWOFISH128.
2003-07-08 Moritz Schulte <moritz@g10code.com>
* Makefile.am (LIBS): Remove: -lpthread.
* basic.c (check_one_cipher): Fix variable initialization. Thanks
to Simon Joseffson <jas@extundo.com>.
2003-07-07 Moritz Schulte <moritz@g10code.com>
* Makefile.am (TESTS): Added: register.
2003-07-05 Moritz Schulte <moritz@g10code.com>
* register.c (check_run): Adjusted for new gcry_cipher_register API.
2003-07-02 Moritz Schulte <moritz@g10code.com>
* Makefile.am (TESTS): Added: ac.
* ac.c: New file.
2003-06-18 Werner Koch <wk@gnupg.org>
* basic.c (check_cbc_mac_cipher): Adjusted for new API of get_blklen
and get_keylen.
(check_ctr_cipher): Ditto.
(check_one_cipher): Ditto.
(check_one_md): Adjusted for new API of gcry_md_copy.
2003-06-18 Moritz Schulte <moritz@g10code.com>
* register.c: Replace old type GcryModule with newer one:
gcry_module_t.
Adjusted for new API.
* Makefile.am (AM_CFLAGS): Added: @GPG_ERROR_CFLAGS@.
2003-06-15 Moritz Schulte <moritz@g10code.com>
* basic.c (get_keys_new): New function.
(do_check_one_pubkey): New function ...
(check_one_pubkey): ... use it.
(progress_handler): New function.
(main): Use gcry_set_progress_handler.
2003-06-14 Moritz Schulte <moritz@g10code.com>
* basic.c: Replaced calls to gcry_strerror with calls to
gpg_strerror.
(check_one_md): Adjust for new gcry_md_copy API.
* tsexp.c: Likewise.
* keygen.c: Likewise.
2003-06-12 Moritz Schulte <moritz@g10code.com>
* basic.c: Changed here and there, reorganized pubkey checks,
added DSA and ELG keys.
2003-06-09 Moritz Schulte <moritz@g10code.com>
* basic.c, keygen.c, pubkey.c, register.c, tsexp.c: Changed to use
new API.
2003-06-01 Moritz Schulte <moritz@g10code.com>
* tsexp.c (canon_len): Adjust for new gcry_sexp_canon_len API.
2003-05-26 Moritz Schulte <moritz@g10code.com>
* basic.c (verify_one_signature): Adjust for libgpg-error.
(check_pubkey_sign): Likewise.
(check_pubkey): Likewise.
* basic.c (check_pubkey_sign): Likewise.
* tsexp.c (canon_len): Likewise.
(back_and_forth_one): Likewise.
2003-04-27 Moritz Schulte <moritz@g10code.com>
* pubkey.c: Changed the sample private key to contain the
identifier `openpgp-rsa' instead of `rsa'.
* basic.c (check_digests): Enabled/fixed some tests for TIGER.
2003-04-17 Moritz Schulte <moritz@g10code.com>
* Makefile.am (TESTS): Removed `register' for now.
2003-04-17 Moritz Schulte <moritz@g10code.com>
* basic.c (check_digests): Include checks for SHA512 and SHA384.
2003-04-16 Moritz Schulte <moritz@g10code.com>
* basic.c (check_one_md): Also test md_copy.
2003-04-07 Moritz Schulte <moritz@g10code.com>
* Makefile.am (TESTS): Added register.
* register.c: New file.
2003-03-30 Simon Josefsson <jas@extundo.com>
* basic.c (check_one_cipher): New. Test CTR.
(main): Call it.
(check_ciphers): Check CTR mode.
2003-03-26 Moritz Schulte <moritz@g10code.com>
* Makefile.am (TESTS): Added pubkey.
* pubkey.c: New file.
2003-03-22 Simon Josefsson <jas@extundo.com>
* basic.c (check_cbc_mac_cipher): New.
(main): Use it.
2003-03-19 Werner Koch <wk@gnupg.org>
* keygen.c (check_rsa_keys): Don't expect an exponent when asking
for e=0.
(check_generated_rsa_key): Just print exponent if EXPECTED_E is 0.
2003-03-02 Moritz Schulte <moritz@g10code.com>
* basic.c (check_one_cipher): Use gcry_cipher_reset() instead of
gcry_cipher_close(), gcry_cipher_open and gcry_cipher_setkey().
2003-01-23 Werner Koch <wk@gnupg.org>
* keygen.c: New.
2003-01-20 Simon Josefsson <jas@extundo.com>
* basic.c (check_digests): Add CRC.
(check_one_md): Print computed and expected values on error.
2003-01-20 Werner Koch <wk@gnupg.org>
* basic.c (check_one_md): Kludge to check a one million "a".
(check_digests): Add checks for SHA-256.
2003-01-20 Werner Koch <wk@gnupg.org>
* basic.c (check_pubkey): Check the keygrip for the sample key.
2003-01-15 Werner Koch <wk@gnupg.org>
* basic.c (verify_one_signature,check_pubkey_sign)
(check_pubkey): New.
(main): Check public key functions. Add a --debug option.
2002-11-23 Werner Koch <wk@gnupg.org>
* basic.c (check_digests): Add another test for MD4. By Simon
Josefsson.
2002-11-10 Simon Josefsson <jas@extundo.com>
* basic.c (check_aes128_cbc_cts_cipher): New function.
(check_one_cipher): Add flags parameter.
(check_ciphers): Support flags parameter.
(main): Check CTS.
2002-11-10 Werner Koch <wk@gnupg.org>
* basic.c (check_one_md): New. By Simon Josefsson.
(check_digests): New tests for MD4. By Simon.
2002-08-26 Werner Koch <wk@gnupg.org>
* basic.c (check_ciphers): Check simple DES.
2002-05-16 Werner Koch <wk@gnupg.org>
* tsexp.c (back_and_forth): Very minimal test of the new functions.
2002-05-14 Werner Koch <wk@gnupg.org>
Changed license of all files to the LGPL.
2002-05-02 Werner Koch <wk@gnupg.org>
* basic.c: Add option --verbose.
2002-01-11 Werner Koch <wk@gnupg.org>
* tsexp.c (canon_len): Fixed tests.
2001-12-18 Werner Koch <wk@gnupg.org>
* tsexp.c: New.
- Copyright 2001, 2002, 2003 Free Software Foundation, Inc.
+ Copyright 2001, 2002, 2003, 2008 Free Software Foundation, Inc.
This file is free software; as a special exception the author gives
unlimited permission to copy and/or distribute it, with or without
modifications, as long as this notice is preserved.
This file is distributed in the hope that it will be useful, but
WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
diff --git a/tests/Makefile.am b/tests/Makefile.am
index 21d5bd84..38901f66 100644
--- a/tests/Makefile.am
+++ b/tests/Makefile.am
@@ -1,48 +1,44 @@
# Copyright (C) 2001, 2002, 2003, 2005 Free Software Foundation, Inc.
#
# This file is part of Libgcrypt.
#
# Libgcrypt is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as
# published by the Free Software Foundation; either version 2.1 of
# the License, or (at your option) any later version.
#
# Libgcrypt is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
## Process this file with automake to produce Makefile.in
TESTS = version t-mpi-bit prime register ac ac-schemes ac-data basic \
mpitests tsexp keygen pubkey hmac keygrip
# random.c uses fork() thus a test for W32 does not make any sense.
if !HAVE_W32_SYSTEM
TESTS += random
endif
# The last test to run.
TESTS += benchmark
# Need to include ../src in addition to top_srcdir because gcrypt.h is
# a built header.
AM_CPPFLAGS = -I../src -I$(top_srcdir)/src
AM_CFLAGS = $(GPG_ERROR_CFLAGS)
LDADD = ../src/libgcrypt.la $(DL_LIBS)
EXTRA_PROGRAMS = testapi pkbench
-noinst_PROGRAMS = $(TESTS) fipsrngdrv
+noinst_PROGRAMS = $(TESTS) fipsdrv
-EXTRA_DIST = README rsa-16k.key
-
-# Note: There is a file cavs-driver.pl in the SVN but we do not
-# distribute it because we have no configure tests for Perl and thus
-# we can expect that people get it from the SVN instead.
+EXTRA_DIST = README rsa-16k.key cavs_tests.sh cavs_driver.pl
diff --git a/tests/benchmark.c b/tests/benchmark.c
index 452bef91..a7a0b413 100644
--- a/tests/benchmark.c
+++ b/tests/benchmark.c
@@ -1,1139 +1,1141 @@
/* benchmark.c - for libgcrypt
* Copyright (C) 2002, 2004, 2005, 2006, 2008 Free Software Foundation, Inc.
*
* This file is part of Libgcrypt.
*
* Libgcrypt is free software; you can redistribute it and/or modify
* it under the terms of the GNU Lesser general Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* Libgcrypt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <stdarg.h>
#ifdef _WIN32
#include <windows.h>
#else
#include <sys/times.h>
#endif
#include <gcrypt.h>
#define PGM "benchmark"
static int verbose;
/* Do encryption tests with large buffers. */
static int large_buffers;
/* Number of cipher repetitions. */
static int cipher_repetitions;
static const char sample_private_dsa_key_1024[] =
"(private-key\n"
" (dsa\n"
" (p #00A126202D592214C5A8F6016E2C3F4256052ACB1CB17D88E64B1293FAF08F5E4685"
"03E6F68366B326A56284370EB2103E92D8346A163E44A08FDC422AC8E9E44268557A"
"853539A6AF39353A59CE5E78FD98B57D0F3E3A7EBC8A256AC9A775BA59689F3004BF"
"C3035730C4C0C51626C5D7F5852637EC589BB29DAB46C161572E4B#)\n"
" (q #00DEB5A296421887179ECA1762884DE2AF8185AFC5#)\n"
" (g #3958B34AE7747194ECBD312F8FEE8CBE3918E94DF9FD11E2912E56318F33BDC38622"
"B18DDFF393074BCA8BAACF50DF27AEE529F3E8AEECE55C398DAB3A5E04C2EA142312"
"FACA2FE7F0A88884F8DAC3979EE67598F9A383B2A2325F035C796F352A5C3CDF2CB3"
"85AD24EC52A6E55247E1BB37D260F79E617D2A4446415B6AD79A#)\n"
" (y #519E9FE9AB0545A6724E74603B7B04E48DC1437E0284A11EA605A7BA8AB1CF354FD4"
"ECC93880AC293391C69B558AD84E7AAFA88F11D028CF3A378F241D6B056A90C588F6"
"66F68D27262B4DA84657D15057D371BCEC1F6504032507D5B881E45FC93A1B973155"
"D91C57219D090C3ACD75E7C2B9F1176A208AC03D6C12AC28A271#)\n"
" (x #4186F8A58C5DF46C5BCFC7006BEEBF05E93C0CA7#)\n"
"))\n";
static const char sample_public_dsa_key_1024[] =
"(public-key\n"
" (dsa\n"
" (p #00A126202D592214C5A8F6016E2C3F4256052ACB1CB17D88E64B1293FAF08F5E4685"
"03E6F68366B326A56284370EB2103E92D8346A163E44A08FDC422AC8E9E44268557A"
"853539A6AF39353A59CE5E78FD98B57D0F3E3A7EBC8A256AC9A775BA59689F3004BF"
"C3035730C4C0C51626C5D7F5852637EC589BB29DAB46C161572E4B#)\n"
" (q #00DEB5A296421887179ECA1762884DE2AF8185AFC5#)\n"
" (g #3958B34AE7747194ECBD312F8FEE8CBE3918E94DF9FD11E2912E56318F33BDC38622"
"B18DDFF393074BCA8BAACF50DF27AEE529F3E8AEECE55C398DAB3A5E04C2EA142312"
"FACA2FE7F0A88884F8DAC3979EE67598F9A383B2A2325F035C796F352A5C3CDF2CB3"
"85AD24EC52A6E55247E1BB37D260F79E617D2A4446415B6AD79A#)\n"
" (y #519E9FE9AB0545A6724E74603B7B04E48DC1437E0284A11EA605A7BA8AB1CF354FD4"
"ECC93880AC293391C69B558AD84E7AAFA88F11D028CF3A378F241D6B056A90C588F6"
"66F68D27262B4DA84657D15057D371BCEC1F6504032507D5B881E45FC93A1B973155"
"D91C57219D090C3ACD75E7C2B9F1176A208AC03D6C12AC28A271#)\n"
"))\n";
static const char sample_private_dsa_key_2048[] =
"(private-key\n"
" (dsa\n"
" (p #00B54636673962B64F7DC23C71ACEF6E7331796F607560B194DFCC0CA370E858A365"
"A413152FB6EB8C664BD171AC316FE5B381CD084D07377571599880A068EF1382D85C"
"308B4E9DEAC12D66DE5C4A826EBEB5ED94A62E7301E18927E890589A2F230272A150"
"C118BC3DC2965AE0D05BE4F65C6137B2BA7EDABB192C3070D202C10AA3F534574970"
"71454DB8A73DDB6511A5BA98EF1450FD90DE5BAAFC9FD3AC22EBEA612DD075BB7405"
"D56866D125E33982C046808F7CEBA8E5C0B9F19A6FE451461660A1CBA9EF68891179"
"0256A573D3B8F35A5C7A0C6C31F2DB90E25A26845252AD9E485EF2D339E7B5890CD4"
"2F9C9F315ED409171EC35CA04CC06B275577B3#)\n"
" (q #00DA67989167FDAC4AE3DF9247A716859A30C0CF9C5A6DBA01EABA3481#)\n"
" (g #48E35DA584A089D05142AA63603FDB00D131B07A0781E2D5A8F9614D2B33D3E40A78"
"98A9E10CDBB612CF093F95A3E10D09566726F2C12823836B2D9CD974BB695665F3B3"
"5D219A9724B87F380BD5207EDA0AE38C79E8F18122C3F76E4CEB0ABED3250914987F"
"B30D4B9E19C04C28A5D4F45560AF586F6A1B41751EAD90AE7F044F4E2A4A50C1F508"
"4FC202463F478F678B9A19392F0D2961C5391C546EF365368BB46410C9C1CEE96E9F"
"0C953570C2ED06328B11C90E86E57CAA7FA5ABAA278E22A4C8C08E16EE59F484EC44"
"2CF55535BAA2C6BEA8833A555372BEFE1E665D3C7DAEF58061D5136331EF4EB61BC3"
"6EE4425A553AF8885FEA15A88135BE133520#)\n"
" (y #66E0D1A69D663466F8FEF2B7C0878DAC93C36A2FB2C05E0306A53B926021D4B92A1C"
"2FA6860061E88E78CBBBA49B0E12700F07DBF86F72CEB2927EDAC0C7E3969C3A47BB"
"4E0AE93D8BB3313E93CC7A72DFEEE442EFBC81B3B2AEC9D8DCBE21220FB760201D79"
"328C41C773866587A44B6954767D022A88072900E964089D9B17133603056C985C4F"
"8A0B648F297F8D2C3CB43E4371DC6002B5B12CCC085BDB2CFC5074A0587566187EE3"
"E11A2A459BD94726248BB8D6CC62938E11E284C2C183576FBB51749EB238C4360923"
"79C08CE1C8CD77EB57404CE9B4744395ACF721487450BADE3220576F2F816248B0A7"
"14A264330AECCB24DE2A1107847B23490897#)\n"
" (x #477BD14676E22563C5ABA68025CEBA2A48D485F5B2D4AD4C0EBBD6D0#)\n"
"))\n";
static const char sample_public_dsa_key_2048[] =
"(public-key\n"
" (dsa\n"
" (p #00B54636673962B64F7DC23C71ACEF6E7331796F607560B194DFCC0CA370E858A365"
"A413152FB6EB8C664BD171AC316FE5B381CD084D07377571599880A068EF1382D85C"
"308B4E9DEAC12D66DE5C4A826EBEB5ED94A62E7301E18927E890589A2F230272A150"
"C118BC3DC2965AE0D05BE4F65C6137B2BA7EDABB192C3070D202C10AA3F534574970"
"71454DB8A73DDB6511A5BA98EF1450FD90DE5BAAFC9FD3AC22EBEA612DD075BB7405"
"D56866D125E33982C046808F7CEBA8E5C0B9F19A6FE451461660A1CBA9EF68891179"
"0256A573D3B8F35A5C7A0C6C31F2DB90E25A26845252AD9E485EF2D339E7B5890CD4"
"2F9C9F315ED409171EC35CA04CC06B275577B3#)\n"
" (q #00DA67989167FDAC4AE3DF9247A716859A30C0CF9C5A6DBA01EABA3481#)\n"
" (g #48E35DA584A089D05142AA63603FDB00D131B07A0781E2D5A8F9614D2B33D3E40A78"
"98A9E10CDBB612CF093F95A3E10D09566726F2C12823836B2D9CD974BB695665F3B3"
"5D219A9724B87F380BD5207EDA0AE38C79E8F18122C3F76E4CEB0ABED3250914987F"
"B30D4B9E19C04C28A5D4F45560AF586F6A1B41751EAD90AE7F044F4E2A4A50C1F508"
"4FC202463F478F678B9A19392F0D2961C5391C546EF365368BB46410C9C1CEE96E9F"
"0C953570C2ED06328B11C90E86E57CAA7FA5ABAA278E22A4C8C08E16EE59F484EC44"
"2CF55535BAA2C6BEA8833A555372BEFE1E665D3C7DAEF58061D5136331EF4EB61BC3"
"6EE4425A553AF8885FEA15A88135BE133520#)\n"
" (y #66E0D1A69D663466F8FEF2B7C0878DAC93C36A2FB2C05E0306A53B926021D4B92A1C"
"2FA6860061E88E78CBBBA49B0E12700F07DBF86F72CEB2927EDAC0C7E3969C3A47BB"
"4E0AE93D8BB3313E93CC7A72DFEEE442EFBC81B3B2AEC9D8DCBE21220FB760201D79"
"328C41C773866587A44B6954767D022A88072900E964089D9B17133603056C985C4F"
"8A0B648F297F8D2C3CB43E4371DC6002B5B12CCC085BDB2CFC5074A0587566187EE3"
"E11A2A459BD94726248BB8D6CC62938E11E284C2C183576FBB51749EB238C4360923"
"79C08CE1C8CD77EB57404CE9B4744395ACF721487450BADE3220576F2F816248B0A7"
"14A264330AECCB24DE2A1107847B23490897#)\n"
"))\n";
static const char sample_private_dsa_key_3072[] =
"(private-key\n"
" (dsa\n"
" (p #00BA73E148AEA5E8B64878AF5BE712B8302B9671C5F3EEB7722A9D0D9868D048C938"
"877C91C335C7819292E69C7D34264F1578E32EC2DA8408DF75D0EB76E0D3030B84B5"
"62D8EF93AB53BAB6B8A5DE464F5CA87AEA43BDCF0FB0B7815AA3114CFC84FD916A83"
"B3D5FD78390189332232E9D037D215313FD002FF46C048B66703F87FAE092AAA0988"
"AC745336EBE672A01DEDBD52395783579B67CF3AE1D6F1602CCCB12154FA0E00AE46"
"0D9B289CF709194625BCB919B11038DEFC50ADBBA20C3F320078E4E9529B4F6848E2"
"AB5E6278DB961FE226F2EEBD201E071C48C5BEF98B4D9BEE42C1C7102D893EBF8902"
"D7A91266340AFD6CE1D09E52282FFF5B97EAFA3886A3FCF84FF76D1E06538D0D8E60"
"B3332145785E07D29A5965382DE3470D1D888447FA9C00A2373378FC3FA7B9F7D17E"
"95A6A5AE1397BE46D976EF2C96E89913AC4A09351CA661BF6F67E30407DA846946C7"
"62D9BAA6B77825097D3E7B886456BB32E3E74516BF3FD93D71B257AA8F723E01CE33"
"8015353D3778B02B892AF7#)\n"
" (q #00BFF3F3CC18FA018A5B8155A8695E1E4939660D5E4759322C39D50F3B93E5F68B#)\n"
" (g #6CCFD8219F5FCE8EF2BEF3262929787140847E38674B1EF8DB20255E212CB6330EC4"
"DFE8A26AB7ECC5760DEB9BBF59A2B2821D510F1868172222867558B8D204E889C474"
"7CA30FBF9D8CF41AE5D5BD845174641101593849FF333E6C93A6550931B2B9D56B98"
"9CAB01729D9D736FA6D24A74D2DDE1E9E648D141473E443DD6BBF0B3CAB64F9FE4FC"
"134B2EB57437789F75C744DF1FA67FA8A64603E5441BC7ECE29E00BDF262BDC81E8C"
"7330A18A412DE38E7546D342B89A0AF675A89E6BEF00540EB107A2FE74EA402B0D89"
"F5C02918DEEEAF8B8737AC866B09B50810AB8D8668834A1B9E1E53866E2B0A926FAB"
"120A0CDE5B3715FFFE6ACD1AB73588DCC1EC4CE9392FE57F8D1D35811200CB07A0E6"
"374E2C4B0AEB7E3D077B8545C0E438DCC0F1AE81E186930E99EBC5B91B77E92803E0"
"21602887851A4FFDB3A7896AC655A0901218C121C5CBB0931E7D5EAC243F37711B5F"
"D5A62B1B38A83F03D8F6703D8B98DF367FC8A76990335F62173A5391836F0F2413EC"
"4997AF9EB55C6660B01A#)\n"
" (y #2320B22434C5DB832B4EC267CC52E78DD5CCFA911E8F0804E7E7F32B186B2D4167AE"
"4AA6869822E76400492D6A193B0535322C72B0B7AA4A87E33044FDC84BE24C64A053"
"A37655EE9EABDCDC1FDF63F3F1C677CEB41595DF7DEFE9178D85A3D621B4E4775492"
"8C0A58D2458D06F9562E4DE2FE6129A64063A99E88E54485B97484A28188C4D33F15"
"DDC903B6CEA0135E3E3D27B4EA39319696305CE93D7BA7BE00367DBE3AAF43491E71"
"CBF254744A5567F5D70090D6139E0C990239627B3A1C5B20B6F9F6374B8D8D8A8997"
"437265BE1E3B4810D4B09254400DE287A0DFFBAEF339E48D422B1D41A37E642BC026"
"73314701C8FA9792845C129351A87A945A03E6C895860E51D6FB8B7340A94D1A8A7B"
"FA85AC83B4B14E73AB86CB96C236C8BFB0978B61B2367A7FE4F7891070F56C78D5DD"
"F5576BFE5BE4F333A4E2664E79528B3294907AADD63F4F2E7AA8147B928D8CD69765"
"3DB98C4297CB678046ED55C0DBE60BF7142C594603E4D705DC3D17270F9F086EC561"
"2703D518D8D49FF0EBE6#)\n"
" (x #00A9FFFC88E67D6F7B810E291C050BAFEA7FC4A75E8D2F16CFED3416FD77607232#)\n"
"))\n";
static const char sample_public_dsa_key_3072[] =
"(public-key\n"
" (dsa\n"
" (p #00BA73E148AEA5E8B64878AF5BE712B8302B9671C5F3EEB7722A9D0D9868D048C938"
"877C91C335C7819292E69C7D34264F1578E32EC2DA8408DF75D0EB76E0D3030B84B5"
"62D8EF93AB53BAB6B8A5DE464F5CA87AEA43BDCF0FB0B7815AA3114CFC84FD916A83"
"B3D5FD78390189332232E9D037D215313FD002FF46C048B66703F87FAE092AAA0988"
"AC745336EBE672A01DEDBD52395783579B67CF3AE1D6F1602CCCB12154FA0E00AE46"
"0D9B289CF709194625BCB919B11038DEFC50ADBBA20C3F320078E4E9529B4F6848E2"
"AB5E6278DB961FE226F2EEBD201E071C48C5BEF98B4D9BEE42C1C7102D893EBF8902"
"D7A91266340AFD6CE1D09E52282FFF5B97EAFA3886A3FCF84FF76D1E06538D0D8E60"
"B3332145785E07D29A5965382DE3470D1D888447FA9C00A2373378FC3FA7B9F7D17E"
"95A6A5AE1397BE46D976EF2C96E89913AC4A09351CA661BF6F67E30407DA846946C7"
"62D9BAA6B77825097D3E7B886456BB32E3E74516BF3FD93D71B257AA8F723E01CE33"
"8015353D3778B02B892AF7#)\n"
" (q #00BFF3F3CC18FA018A5B8155A8695E1E4939660D5E4759322C39D50F3B93E5F68B#)\n"
" (g #6CCFD8219F5FCE8EF2BEF3262929787140847E38674B1EF8DB20255E212CB6330EC4"
"DFE8A26AB7ECC5760DEB9BBF59A2B2821D510F1868172222867558B8D204E889C474"
"7CA30FBF9D8CF41AE5D5BD845174641101593849FF333E6C93A6550931B2B9D56B98"
"9CAB01729D9D736FA6D24A74D2DDE1E9E648D141473E443DD6BBF0B3CAB64F9FE4FC"
"134B2EB57437789F75C744DF1FA67FA8A64603E5441BC7ECE29E00BDF262BDC81E8C"
"7330A18A412DE38E7546D342B89A0AF675A89E6BEF00540EB107A2FE74EA402B0D89"
"F5C02918DEEEAF8B8737AC866B09B50810AB8D8668834A1B9E1E53866E2B0A926FAB"
"120A0CDE5B3715FFFE6ACD1AB73588DCC1EC4CE9392FE57F8D1D35811200CB07A0E6"
"374E2C4B0AEB7E3D077B8545C0E438DCC0F1AE81E186930E99EBC5B91B77E92803E0"
"21602887851A4FFDB3A7896AC655A0901218C121C5CBB0931E7D5EAC243F37711B5F"
"D5A62B1B38A83F03D8F6703D8B98DF367FC8A76990335F62173A5391836F0F2413EC"
"4997AF9EB55C6660B01A#)\n"
" (y #2320B22434C5DB832B4EC267CC52E78DD5CCFA911E8F0804E7E7F32B186B2D4167AE"
"4AA6869822E76400492D6A193B0535322C72B0B7AA4A87E33044FDC84BE24C64A053"
"A37655EE9EABDCDC1FDF63F3F1C677CEB41595DF7DEFE9178D85A3D621B4E4775492"
"8C0A58D2458D06F9562E4DE2FE6129A64063A99E88E54485B97484A28188C4D33F15"
"DDC903B6CEA0135E3E3D27B4EA39319696305CE93D7BA7BE00367DBE3AAF43491E71"
"CBF254744A5567F5D70090D6139E0C990239627B3A1C5B20B6F9F6374B8D8D8A8997"
"437265BE1E3B4810D4B09254400DE287A0DFFBAEF339E48D422B1D41A37E642BC026"
"73314701C8FA9792845C129351A87A945A03E6C895860E51D6FB8B7340A94D1A8A7B"
"FA85AC83B4B14E73AB86CB96C236C8BFB0978B61B2367A7FE4F7891070F56C78D5DD"
"F5576BFE5BE4F333A4E2664E79528B3294907AADD63F4F2E7AA8147B928D8CD69765"
"3DB98C4297CB678046ED55C0DBE60BF7142C594603E4D705DC3D17270F9F086EC561"
"2703D518D8D49FF0EBE6#)\n"
"))\n";
#define DIM(v) (sizeof(v)/sizeof((v)[0]))
#define DIMof(type,member) DIM(((type *)0)->member)
#define BUG() do {fprintf ( stderr, "Ooops at %s:%d\n", __FILE__ , __LINE__ );\
exit(2);} while(0)
/* Helper for the start and stop timer. */
#ifdef _WIN32
struct {
FILETIME creation_time, exit_time, kernel_time, user_time;
} started_at, stopped_at;
#else
static clock_t started_at, stopped_at;
#endif
static void
die (const char *format, ...)
{
va_list arg_ptr ;
va_start( arg_ptr, format ) ;
putchar ('\n');
fputs ( PGM ": ", stderr);
vfprintf (stderr, format, arg_ptr );
va_end(arg_ptr);
exit (1);
}
static void
show_sexp (const char *prefix, gcry_sexp_t a)
{
char *buf;
size_t size;
fputs (prefix, stderr);
size = gcry_sexp_sprint (a, GCRYSEXP_FMT_ADVANCED, NULL, 0);
buf = malloc (size);
if (!buf)
die ("out of core\n");
gcry_sexp_sprint (a, GCRYSEXP_FMT_ADVANCED, buf, size);
fprintf (stderr, "%.*s", (int)size, buf);
}
static void
start_timer (void)
{
#ifdef _WIN32
GetProcessTimes (GetCurrentProcess (),
&started_at.creation_time, &started_at.exit_time,
&started_at.kernel_time, &started_at.user_time);
stopped_at = started_at;
#else
struct tms tmp;
times (&tmp);
started_at = stopped_at = tmp.tms_utime;
#endif
}
static void
stop_timer (void)
{
#ifdef _WIN32
GetProcessTimes (GetCurrentProcess (),
&stopped_at.creation_time, &stopped_at.exit_time,
&stopped_at.kernel_time, &stopped_at.user_time);
#else
struct tms tmp;
times (&tmp);
stopped_at = tmp.tms_utime;
#endif
}
static const char *
elapsed_time (void)
{
static char buf[50];
#if _WIN32
unsigned long long t1, t2, t;
t1 = (((unsigned long long)started_at.kernel_time.dwHighDateTime << 32)
+ started_at.kernel_time.dwLowDateTime);
t1 += (((unsigned long long)started_at.user_time.dwHighDateTime << 32)
+ started_at.user_time.dwLowDateTime);
t2 = (((unsigned long long)stopped_at.kernel_time.dwHighDateTime << 32)
+ stopped_at.kernel_time.dwLowDateTime);
t2 += (((unsigned long long)stopped_at.user_time.dwHighDateTime << 32)
+ stopped_at.user_time.dwLowDateTime);
t = (t2 - t1)/10000;
snprintf (buf, sizeof buf, "%5.0fms", (double)t );
#else
snprintf (buf, sizeof buf, "%5.0fms",
(((double) (stopped_at - started_at))/CLOCKS_PER_SEC)*10000000);
#endif
return buf;
}
static void
random_bench (int very_strong)
{
char buf[128];
int i;
printf ("%-10s", "random");
if (!very_strong)
{
start_timer ();
for (i=0; i < 100; i++)
gcry_randomize (buf, sizeof buf, GCRY_STRONG_RANDOM);
stop_timer ();
printf (" %s", elapsed_time ());
}
start_timer ();
for (i=0; i < 100; i++)
gcry_randomize (buf, 8,
very_strong? GCRY_VERY_STRONG_RANDOM:GCRY_STRONG_RANDOM);
stop_timer ();
printf (" %s", elapsed_time ());
putchar ('\n');
if (verbose)
gcry_control (GCRYCTL_DUMP_RANDOM_STATS);
}
static void
md_bench ( const char *algoname )
{
int algo;
gcry_md_hd_t hd;
int i;
char buf[1000];
gcry_error_t err = GPG_ERR_NO_ERROR;
if (!algoname)
{
for (i=1; i < 400; i++)
if ( !gcry_md_test_algo (i) )
md_bench (gcry_md_algo_name (i));
return;
}
algo = gcry_md_map_name (algoname);
if (!algo)
{
fprintf (stderr, PGM ": invalid hash algorithm `%s'\n", algoname);
exit (1);
}
err = gcry_md_open (&hd, algo, 0);
if (err)
{
fprintf (stderr, PGM ": error opening hash algorithm `%s'\n", algoname);
exit (1);
}
for (i=0; i < sizeof buf; i++)
buf[i] = i;
printf ("%-12s", gcry_md_algo_name (algo));
start_timer ();
for (i=0; i < 1000; i++)
gcry_md_write (hd, buf, sizeof buf);
gcry_md_final (hd);
stop_timer ();
printf (" %s", elapsed_time ());
gcry_md_reset (hd);
start_timer ();
for (i=0; i < 10000; i++)
gcry_md_write (hd, buf, sizeof buf/10);
gcry_md_final (hd);
stop_timer ();
printf (" %s", elapsed_time ());
gcry_md_reset (hd);
start_timer ();
for (i=0; i < 1000000; i++)
gcry_md_write (hd, "", 1);
gcry_md_final (hd);
stop_timer ();
printf (" %s", elapsed_time ());
gcry_md_close (hd);
putchar ('\n');
}
static void
cipher_bench ( const char *algoname )
{
static int header_printed;
int algo;
gcry_cipher_hd_t hd;
int i;
int keylen, blklen;
char key[128];
char *outbuf, *buf;
size_t allocated_buflen, buflen;
int repetitions;
static struct { int mode; const char *name; int blocked; } modes[] = {
{ GCRY_CIPHER_MODE_ECB, "ECB", 1 },
{ GCRY_CIPHER_MODE_CBC, "CBC", 1 },
{ GCRY_CIPHER_MODE_CFB, "CFB", 0 },
{ GCRY_CIPHER_MODE_OFB, "OFB", 0 },
{ GCRY_CIPHER_MODE_CTR, "CTR", 0 },
{ GCRY_CIPHER_MODE_STREAM, "STREAM", 0 },
{0}
};
int modeidx;
gcry_error_t err = GPG_ERR_NO_ERROR;
if (!algoname)
{
for (i=1; i < 400; i++)
if ( !gcry_cipher_test_algo (i) )
cipher_bench (gcry_cipher_algo_name (i));
return;
}
if (large_buffers)
{
allocated_buflen = 1024 * 100;
repetitions = 10;
}
else
{
allocated_buflen = 1024;
repetitions = 1000;
}
repetitions *= cipher_repetitions;
buf = gcry_xmalloc (allocated_buflen);
outbuf = gcry_xmalloc (allocated_buflen);
if (!header_printed)
{
if (cipher_repetitions != 1)
printf ("Running each test %d times.\n", cipher_repetitions);
printf ("%-12s", "");
for (modeidx=0; modes[modeidx].mode; modeidx++)
printf (" %-15s", modes[modeidx].name );
putchar ('\n');
printf ("%-12s", "");
for (modeidx=0; modes[modeidx].mode; modeidx++)
printf (" ---------------" );
putchar ('\n');
header_printed = 1;
}
algo = gcry_cipher_map_name (algoname);
if (!algo)
{
fprintf (stderr, PGM ": invalid cipher algorithm `%s'\n", algoname);
exit (1);
}
keylen = gcry_cipher_get_algo_keylen (algo);
if (!keylen)
{
fprintf (stderr, PGM ": failed to get key length for algorithm `%s'\n",
algoname);
exit (1);
}
if ( keylen > sizeof key )
{
fprintf (stderr, PGM ": algo %d, keylength problem (%d)\n",
algo, keylen );
exit (1);
}
for (i=0; i < keylen; i++)
key[i] = i + (clock () & 0xff);
blklen = gcry_cipher_get_algo_blklen (algo);
if (!blklen)
{
fprintf (stderr, PGM ": failed to get block length for algorithm `%s'\n",
algoname);
exit (1);
}
printf ("%-12s", gcry_cipher_algo_name (algo));
fflush (stdout);
for (modeidx=0; modes[modeidx].mode; modeidx++)
{
if ((blklen > 1 && modes[modeidx].mode == GCRY_CIPHER_MODE_STREAM)
| (blklen == 1 && modes[modeidx].mode != GCRY_CIPHER_MODE_STREAM))
{
printf (" " );
continue;
}
for (i=0; i < sizeof buf; i++)
buf[i] = i;
err = gcry_cipher_open (&hd, algo, modes[modeidx].mode, 0);
if (err)
{
fprintf (stderr, PGM ": error opening cipher `%s'\n", algoname);
exit (1);
}
err = gcry_cipher_setkey (hd, key, keylen);
if (err)
{
fprintf (stderr, "gcry_cipher_setkey failed: %s\n",
gpg_strerror (err));
gcry_cipher_close (hd);
exit (1);
}
buflen = allocated_buflen;
if (modes[modeidx].blocked)
buflen = (buflen / blklen) * blklen;
start_timer ();
for (i=err=0; !err && i < repetitions; i++)
err = gcry_cipher_encrypt ( hd, outbuf, buflen, buf, buflen);
stop_timer ();
printf (" %s", elapsed_time ());
fflush (stdout);
gcry_cipher_close (hd);
if (err)
{
fprintf (stderr, "gcry_cipher_encrypt failed: %s\n",
gpg_strerror (err) );
exit (1);
}
err = gcry_cipher_open (&hd, algo, modes[modeidx].mode, 0);
if (err)
{
fprintf (stderr, PGM ": error opening cipher `%s'/n", algoname);
exit (1);
}
err = gcry_cipher_setkey (hd, key, keylen);
if (err)
{
fprintf (stderr, "gcry_cipher_setkey failed: %s\n",
gpg_strerror (err));
gcry_cipher_close (hd);
exit (1);
}
start_timer ();
for (i=err=0; !err && i < repetitions; i++)
err = gcry_cipher_decrypt ( hd, outbuf, buflen, buf, buflen);
stop_timer ();
printf (" %s", elapsed_time ());
fflush (stdout);
gcry_cipher_close (hd);
if (err)
{
fprintf (stderr, "gcry_cipher_decrypt failed: %s\n",
gpg_strerror (err) );
exit (1);
}
}
putchar ('\n');
gcry_free (buf);
gcry_free (outbuf);
}
static void
rsa_bench (int iterations, int print_header, int no_blinding)
{
gpg_error_t err;
int p_sizes[] = { 1024, 2048, 3072, 4096 };
int testno;
if (print_header)
printf ("Algorithm generate %4d*sign %4d*verify\n"
"------------------------------------------------\n",
iterations, iterations );
for (testno=0; testno < DIM (p_sizes); testno++)
{
gcry_sexp_t key_spec, key_pair, pub_key, sec_key;
gcry_mpi_t x;
gcry_sexp_t data;
gcry_sexp_t sig = NULL;
int count;
printf ("RSA %3d bit ", p_sizes[testno]);
fflush (stdout);
err = gcry_sexp_build (&key_spec, NULL,
gcry_control (GCRYCTL_FIPS_MODE_P, 0)
? "(genkey (RSA (nbits %d)))"
: "(genkey (RSA (nbits %d)(transient-key)))",
p_sizes[testno]);
if (err)
die ("creating S-expression failed: %s\n", gcry_strerror (err));
start_timer ();
err = gcry_pk_genkey (&key_pair, key_spec);
if (err)
die ("creating %d bit RSA key failed: %s\n",
p_sizes[testno], gcry_strerror (err));
pub_key = gcry_sexp_find_token (key_pair, "public-key", 0);
if (! pub_key)
die ("public part missing in key\n");
sec_key = gcry_sexp_find_token (key_pair, "private-key", 0);
if (! sec_key)
die ("private part missing in key\n");
gcry_sexp_release (key_pair);
gcry_sexp_release (key_spec);
stop_timer ();
printf (" %s", elapsed_time ());
fflush (stdout);
x = gcry_mpi_new (p_sizes[testno]);
gcry_mpi_randomize (x, p_sizes[testno]-8, GCRY_WEAK_RANDOM);
err = gcry_sexp_build (&data, NULL,
"(data (flags raw) (value %m))", x);
gcry_mpi_release (x);
if (err)
die ("converting data failed: %s\n", gcry_strerror (err));
start_timer ();
for (count=0; count < iterations; count++)
{
gcry_sexp_release (sig);
err = gcry_pk_sign (&sig, data, sec_key);
if (err)
die ("signing failed (%d): %s\n", count, gpg_strerror (err));
}
stop_timer ();
printf (" %s", elapsed_time ());
fflush (stdout);
start_timer ();
for (count=0; count < iterations; count++)
{
err = gcry_pk_verify (sig, data, pub_key);
if (err)
{
putchar ('\n');
show_sexp ("seckey:\n", sec_key);
show_sexp ("data:\n", data);
show_sexp ("sig:\n", sig);
die ("verify failed (%d): %s\n", count, gpg_strerror (err));
}
}
stop_timer ();
printf (" %s", elapsed_time ());
if (no_blinding)
{
fflush (stdout);
x = gcry_mpi_new (p_sizes[testno]);
gcry_mpi_randomize (x, p_sizes[testno]-8, GCRY_WEAK_RANDOM);
err = gcry_sexp_build (&data, NULL,
"(data (flags no-blinding) (value %m))", x);
gcry_mpi_release (x);
if (err)
die ("converting data failed: %s\n", gcry_strerror (err));
start_timer ();
for (count=0; count < iterations; count++)
{
gcry_sexp_release (sig);
err = gcry_pk_sign (&sig, data, sec_key);
if (err)
die ("signing failed (%d): %s\n", count, gpg_strerror (err));
}
stop_timer ();
printf (" %s", elapsed_time ());
fflush (stdout);
}
putchar ('\n');
fflush (stdout);
gcry_sexp_release (sig);
gcry_sexp_release (data);
gcry_sexp_release (sec_key);
gcry_sexp_release (pub_key);
}
}
static void
dsa_bench (int iterations, int print_header)
{
gpg_error_t err;
gcry_sexp_t pub_key[3], sec_key[3];
int p_sizes[3] = { 1024, 2048, 3072 };
int q_sizes[3] = { 160, 224, 256 };
gcry_sexp_t data;
gcry_sexp_t sig;
int i, j;
err = gcry_sexp_sscan (pub_key+0, NULL, sample_public_dsa_key_1024,
strlen (sample_public_dsa_key_1024));
if (!err)
err = gcry_sexp_sscan (sec_key+0, NULL, sample_private_dsa_key_1024,
strlen (sample_private_dsa_key_1024));
if (!err)
err = gcry_sexp_sscan (pub_key+1, NULL, sample_public_dsa_key_2048,
strlen (sample_public_dsa_key_2048));
if (!err)
err = gcry_sexp_sscan (sec_key+1, NULL, sample_private_dsa_key_2048,
strlen (sample_private_dsa_key_2048));
if (!err)
err = gcry_sexp_sscan (pub_key+2, NULL, sample_public_dsa_key_3072,
strlen (sample_public_dsa_key_3072));
if (!err)
err = gcry_sexp_sscan (sec_key+2, NULL, sample_private_dsa_key_3072,
strlen (sample_private_dsa_key_3072));
if (err)
{
fprintf (stderr, PGM ": converting sample keys failed: %s\n",
gcry_strerror (err));
exit (1);
}
if (print_header)
printf ("Algorithm generate %4d*sign %4d*verify\n"
"------------------------------------------------\n",
iterations, iterations );
for (i=0; i < DIM (q_sizes); i++)
{
gcry_mpi_t x;
x = gcry_mpi_new (q_sizes[i]);
gcry_mpi_randomize (x, q_sizes[i], GCRY_WEAK_RANDOM);
err = gcry_sexp_build (&data, NULL, "(data (flags raw) (value %m))", x);
gcry_mpi_release (x);
if (err)
{
fprintf (stderr, PGM ": converting data failed: %s\n",
gcry_strerror (err));
exit (1);
}
printf ("DSA %d/%d -", p_sizes[i], q_sizes[i]);
fflush (stdout);
start_timer ();
for (j=0; j < iterations; j++)
{
err = gcry_pk_sign (&sig, data, sec_key[i]);
if (err)
{
putchar ('\n');
fprintf (stderr, PGM ": signing failed: %s\n",
gpg_strerror (err));
exit (1);
}
}
stop_timer ();
printf (" %s", elapsed_time ());
fflush (stdout);
start_timer ();
for (j=0; j < iterations; j++)
{
err = gcry_pk_verify (sig, data, pub_key[i]);
if (err)
{
putchar ('\n');
fprintf (stderr, PGM ": verify failed: %s\n",
gpg_strerror (err));
exit (1);
}
}
stop_timer ();
printf (" %s\n", elapsed_time ());
fflush (stdout);
gcry_sexp_release (sig);
gcry_sexp_release (data);
}
for (i=0; i < DIM (q_sizes); i++)
{
gcry_sexp_release (sec_key[i]);
gcry_sexp_release (pub_key[i]);
}
}
static void
ecc_bench (int iterations, int print_header)
{
#if USE_ECC
gpg_error_t err;
int p_sizes[] = { 192, 224, 256, 384, 521 };
int testno;
if (print_header)
printf ("Algorithm generate %4d*sign %4d*verify\n"
"------------------------------------------------\n",
iterations, iterations );
for (testno=0; testno < DIM (p_sizes); testno++)
{
gcry_sexp_t key_spec, key_pair, pub_key, sec_key;
gcry_mpi_t x;
gcry_sexp_t data;
gcry_sexp_t sig = NULL;
int count;
printf ("ECDSA %3d bit ", p_sizes[testno]);
fflush (stdout);
err = gcry_sexp_build (&key_spec, NULL,
"(genkey (ECDSA (nbits %d)))", p_sizes[testno]);
if (err)
die ("creating S-expression failed: %s\n", gcry_strerror (err));
start_timer ();
err = gcry_pk_genkey (&key_pair, key_spec);
if (err)
die ("creating %d bit ECC key failed: %s\n",
p_sizes[testno], gcry_strerror (err));
pub_key = gcry_sexp_find_token (key_pair, "public-key", 0);
if (! pub_key)
die ("public part missing in key\n");
sec_key = gcry_sexp_find_token (key_pair, "private-key", 0);
if (! sec_key)
die ("private part missing in key\n");
gcry_sexp_release (key_pair);
gcry_sexp_release (key_spec);
stop_timer ();
printf (" %s", elapsed_time ());
fflush (stdout);
x = gcry_mpi_new (p_sizes[testno]);
gcry_mpi_randomize (x, p_sizes[testno], GCRY_WEAK_RANDOM);
err = gcry_sexp_build (&data, NULL, "(data (flags raw) (value %m))", x);
gcry_mpi_release (x);
if (err)
die ("converting data failed: %s\n", gcry_strerror (err));
start_timer ();
for (count=0; count < iterations; count++)
{
gcry_sexp_release (sig);
err = gcry_pk_sign (&sig, data, sec_key);
if (err)
die ("signing failed: %s\n", gpg_strerror (err));
}
stop_timer ();
printf (" %s", elapsed_time ());
fflush (stdout);
start_timer ();
for (count=0; count < iterations; count++)
{
err = gcry_pk_verify (sig, data, pub_key);
if (err)
{
putchar ('\n');
show_sexp ("seckey:\n", sec_key);
show_sexp ("data:\n", data);
show_sexp ("sig:\n", sig);
die ("verify failed: %s\n", gpg_strerror (err));
}
}
stop_timer ();
printf (" %s\n", elapsed_time ());
fflush (stdout);
gcry_sexp_release (sig);
gcry_sexp_release (data);
gcry_sexp_release (sec_key);
gcry_sexp_release (pub_key);
}
#endif /*USE_ECC*/
}
static void
do_powm ( const char *n_str, const char *e_str, const char *m_str)
{
gcry_mpi_t e, n, msg, cip;
gcry_error_t err;
int i;
err = gcry_mpi_scan (&n, GCRYMPI_FMT_HEX, n_str, 0, 0);
if (err) BUG ();
err = gcry_mpi_scan (&e, GCRYMPI_FMT_HEX, e_str, 0, 0);
if (err) BUG ();
err = gcry_mpi_scan (&msg, GCRYMPI_FMT_HEX, m_str, 0, 0);
if (err) BUG ();
cip = gcry_mpi_new (0);
start_timer ();
for (i=0; i < 1000; i++)
gcry_mpi_powm (cip, msg, e, n);
stop_timer ();
printf (" %s", elapsed_time ()); fflush (stdout);
/* { */
/* char *buf; */
/* if (gcry_mpi_aprint (GCRYMPI_FMT_HEX, (void**)&buf, NULL, cip)) */
/* BUG (); */
/* printf ("result: %s\n", buf); */
/* gcry_free (buf); */
/* } */
gcry_mpi_release (cip);
gcry_mpi_release (msg);
gcry_mpi_release (n);
gcry_mpi_release (e);
}
static void
mpi_bench (void)
{
printf ("%-10s", "powm"); fflush (stdout);
do_powm (
"20A94417D4D5EF2B2DA99165C7DC87DADB3979B72961AF90D09D59BA24CB9A10166FDCCC9C659F2B9626EC23F3FA425F564A072BA941B03FA81767CC289E4",
"29",
"B870187A323F1ECD5B8A0B4249507335A1C4CE8394F38FD76B08C78A42C58F6EA136ACF90DFE8603697B1694A3D81114D6117AC1811979C51C4DD013D52F8"
);
do_powm (
"20A94417D4D5EF2B2DA99165C7DC87DADB3979B72961AF90D09D59BA24CB9A10166FDCCC9C659F2B9626EC23F3FA425F564A072BA941B03FA81767CC289E41071F0246879A442658FBD18C1771571E7073EEEB2160BA0CBFB3404D627069A6CFBD53867AD2D9D40231648000787B5C84176B4336144644AE71A403CA40716",
"29",
"B870187A323F1ECD5B8A0B4249507335A1C4CE8394F38FD76B08C78A42C58F6EA136ACF90DFE8603697B1694A3D81114D6117AC1811979C51C4DD013D52F8FC4EE4BB446B83E48ABED7DB81CBF5E81DE4759E8D68AC985846D999F96B0D8A80E5C69D272C766AB8A23B40D50A4FA889FBC2BD2624222D8EB297F4BAEF8593847"
);
do_powm (
"20A94417D4D5EF2B2DA99165C7DC87DADB3979B72961AF90D09D59BA24CB9A10166FDCCC9C659F2B9626EC23F3FA425F564A072BA941B03FA81767CC289E41071F0246879A442658FBD18C1771571E7073EEEB2160BA0CBFB3404D627069A6CFBD53867AD2D9D40231648000787B5C84176B4336144644AE71A403CA4071620A94417D4D5EF2B2DA99165C7DC87DADB3979B72961AF90D09D59BA24CB9A10166FDCCC9C659F2B9626EC23F3FA425F564A072BA941B03FA81767CC289E41071F0246879A442658FBD18C1771571E7073EEEB2160BA0CBFB3404D627069A6CFBD53867AD2D9D40231648000787B5C84176B4336144644AE71A403CA40716",
"29",
"B870187A323F1ECD5B8A0B4249507335A1C4CE8394F38FD76B08C78A42C58F6EA136ACF90DFE8603697B1694A3D81114D6117AC1811979C51C4DD013D52F8FC4EE4BB446B83E48ABED7DB81CBF5E81DE4759E8D68AC985846D999F96B0D8A80E5C69D272C766AB8A23B40D50A4FA889FBC2BD2624222D8EB297F4BAEF8593847B870187A323F1ECD5B8A0B4249507335A1C4CE8394F38FD76B08C78A42C58F6EA136ACF90DFE8603697B1694A3D81114D6117AC1811979C51C4DD013D52F8FC4EE4BB446B83E48ABED7DB81CBF5E81DE4759E8D68AC985846D999F96B0D8A80E5C69D272C766AB8A23B40D50A4FA889FBC2BD2624222D8EB297F4BAEF8593847"
);
putchar ('\n');
}
int
main( int argc, char **argv )
{
int last_argc = -1;
int no_blinding = 0;
int use_random_daemon = 0;
if (argc)
{ argc--; argv++; }
while (argc && last_argc != argc )
{
last_argc = argc;
if (!strcmp (*argv, "--"))
{
argc--; argv++;
break;
}
else if (!strcmp (*argv, "--help"))
{
fputs ("usage: benchmark "
"[md|cipher|random|mpi|rsa|dsa|ecc [algonames]]\n",
stdout);
exit (0);
}
else if (!strcmp (*argv, "--verbose"))
{
verbose++;
argc--; argv++;
}
else if (!strcmp (*argv, "--use-random-daemon"))
{
use_random_daemon = 1;
argc--; argv++;
}
else if (!strcmp (*argv, "--no-blinding"))
{
no_blinding = 1;
argc--; argv++;
}
else if (!strcmp (*argv, "--large-buffers"))
{
large_buffers = 1;
argc--; argv++;
}
else if (!strcmp (*argv, "--cipher-repetition"))
{
argc--; argv++;
if (argc)
{
cipher_repetitions = atoi(*argv);
argc--; argv++;
}
}
else if (!strcmp (*argv, "--fips"))
{
argc--; argv++;
/* This command needs to be called before gcry_check_version. */
gcry_control (GCRYCTL_FORCE_FIPS_MODE, 0);
}
}
gcry_control (GCRYCTL_SET_VERBOSITY, (int)verbose);
if (!gcry_check_version (GCRYPT_VERSION))
{
fprintf (stderr, PGM ": version mismatch\n");
exit (1);
}
- gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
+
+ if (!gcry_fips_mode_active ())
+ gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
if (use_random_daemon)
gcry_control (GCRYCTL_USE_RANDOM_DAEMON, 1);
gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
if (cipher_repetitions < 1)
cipher_repetitions = 1;
if ( !argc )
{
gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
md_bench (NULL);
putchar ('\n');
cipher_bench (NULL);
putchar ('\n');
rsa_bench (100, 1, no_blinding);
dsa_bench (100, 0);
ecc_bench (100, 0);
putchar ('\n');
mpi_bench ();
putchar ('\n');
random_bench (0);
}
else if ( !strcmp (*argv, "random") || !strcmp (*argv, "strongrandom"))
{
if (argc == 1)
random_bench ((**argv == 's'));
else if (argc == 2)
{
gcry_control (GCRYCTL_SET_RANDOM_SEED_FILE, argv[1]);
random_bench ((**argv == 's'));
gcry_control (GCRYCTL_UPDATE_RANDOM_SEED_FILE);
}
else
fputs ("usage: benchmark [strong]random [seedfile]\n", stdout);
}
else if ( !strcmp (*argv, "md"))
{
if (argc == 1)
md_bench (NULL);
else
for (argc--, argv++; argc; argc--, argv++)
md_bench ( *argv );
}
else if ( !strcmp (*argv, "cipher"))
{
if (argc == 1)
cipher_bench (NULL);
else
for (argc--, argv++; argc; argc--, argv++)
cipher_bench ( *argv );
}
else if ( !strcmp (*argv, "mpi"))
{
mpi_bench ();
}
else if ( !strcmp (*argv, "rsa"))
{
gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
rsa_bench (100, 1, no_blinding);
}
else if ( !strcmp (*argv, "dsa"))
{
gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
dsa_bench (100, 1);
}
else if ( !strcmp (*argv, "ecc"))
{
gcry_control (GCRYCTL_ENABLE_QUICK_RANDOM, 0);
ecc_bench (100, 1);
}
else
{
fprintf (stderr, PGM ": bad arguments\n");
return 1;
}
return 0;
}
diff --git a/tests/cavs_driver.pl b/tests/cavs_driver.pl
old mode 100644
new mode 100755
index 55c238f6..c4ab0a8b
--- a/tests/cavs_driver.pl
+++ b/tests/cavs_driver.pl
@@ -1,1600 +1,1687 @@
#!/usr/bin/env perl
#
-# $Id: cavs_driver.pl 1236 2008-09-17 13:00:06Z smueller $
+# Id: cavs_driver.pl 1236 2008-09-17 13:00:06Z smueller
#
# CAVS test driver (based on the OpenSSL driver)
# Written by: Stephan Mテシller <sm@atsec.com>
# Copyright (c) atsec information security corporation
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# NO WARRANTY
#
# BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
# FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
# OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
# PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
# OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
# MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
# TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
# PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
# REPAIR OR CORRECTION.
#
# IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
# WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
# REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
# INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
# OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
# TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
# YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
# PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGES.
#
#
# test execution instruction:
# 1. get the request files from the lab
# 2. call each request file from 1. with this program:
# $0 <FILE>.rep
# 3. send the resulting file <FILE>.rsp to the lab
#
#
# Test should be easily adoptable to other implementations
# See the first functions for this task
#
# Following tests are covered (others may also be covered
# but have not been tested)
#
# AES
# [CBC|CFB128|ECB|OFB]GFSbox[128|192|256]
# [CBC|CFB128|ECB|OFB]MCT[128|192|256]
# [CBC|CFB128|ECB|OFB]VarKey[128|192|256]
# [CBC|CFB128|ECB|OFB]KeySbox[128|192|256]
# [CBC|CFB128|ECB|OFB]MMT[128|192|256]
# [CBC|CFB128|ECB|OFB]VarTxt[128|192|256]
#
# RSA
# SigGen[15|RSA]
# SigVer15
# (SigVerRSA is not applicable for OpenSSL as X9.31 padding
# is not done through openssl dgst)
#
# SHA
# SHA[1|224|256|384|512]ShortMsg
# SHA[1|224|256|384|512]LongMsg
# SHA[1|224|256|384|512]Monte
#
# HMAC (SHA - caveat: we only support hash output equal to the block size of
# of the hash - we do not support truncation of the hash; to support
# that, we first need to decipher the HMAC.req file - see hmac_kat() )
# HMAC
#
# TDES
# T[CBC|CFB??|ECB|OFB]Monte[1|2|3]
# T[CBC|CFB??|ECB|OFB]permop
# T[CBC|CFB??|ECB|OFB]MMT[1|2|3]
# T[CBC|CFB??|ECB|OFB]subtab
# T[CBC|CFB??|ECB|OFB]varkey
# T[CBC|CFB??|ECB|OFB]invperm
# T[CBC|CFB??|ECB|OFB]vartext
#
# ANSI X9.31 RNG
# ANSI931_AES128MCT
# ANSI931_AES128VST
#
# RC4 (atsec developed tests)
# RC4KeyBD
# RC4MCT
# RC4PltBD
# RC4REGT
#
use strict;
use warnings;
use IPC::Open2;
use Getopt::Std;
use MIME::Base64;
# Contains the command line options
my %opt;
#################################################################
##### Central interface functions to the external ciphers #######
#################################################################
# Only these interface routines should be changed in case of
# porting to a new cipher library
#
# For porting to a new library, create implementation of these functions
# and then add pointers to the respective implementation of each
# function to the given variables.
# common encryption/decryption routine
# $1 key in hex form (please note for 3DES: even when ede3 for three
# independent ciphers is given with the cipher specification, we hand in
# either one key for k1 = k2 = k3, two keys which are concatinated for
# k1 = k3, k2 independent, or three keys which are concatinated for
# k1, k2, k3 independent)
# $2 iv in hex form
# $3 cipher - the cipher string is defined as specified in the openssl
# enc(1ssl) specification for the option "-ciphername"
# (e.g. aes-128-cbc or des-ede3-cbc)
# $4 encrypt=1/decrypt=0
# $5 de/encrypted data in hex form
# return en/decrypted data in hex form
my $encdec;
# Sign a message with RSA
# $1: data to be signed in hex form
# $2: Hash algo
# $3: Key file in PEM format with the private key
# return: digest in hex format
my $rsa_sign;
# Verify a message with RSA
# $1: data to be verified in hex form
# $2: hash algo
# $3: file holding the public RSA key in PEM format
# $4: file holding the signature in binary form
# return: 1 == verfied / 0 == not verified
my $rsa_verify;
# generate a new private RSA key with the following properties:
# exponent is 65537
# PEM format
# $1 key size in bit
# $2 keyfile name
# return: nothing, but file created
my $gen_rsakey;
# Creating a hash
# $1: Plaintext in hex form
# $2: hash type in the form documented in openssl's dgst(1ssl) - e.g.
# sha1, sha224, sha256, sha384, sha512
# return: hash in hex form
my $hash;
# supplying the call to the external cipher implementation
# that is being used to keep STDIN and STDOUT open
# to maintain the state of the block chaining
# $1: cipher
# $2: 1=encryption, 0=decryption
# $3: buffersize needed for openssl
# $4: encryption key in binary form
# $5: IV in binary form
# return: command line to execute the application
my $state_cipher;
# supplying the call to the external cipher implementation
# that is being used to keep STDIN and STDOUT open
# to maintain the state of the RNG with its seed
#
# input holds seed values
# $1: cipher key in hex format
# $2: DT value in hex format
# $3: V value in hex format
#
# return: command line to execute the application
#
# the application is expected to deliver random values on STDOUT - the script
# reads 128 bits repeatedly where the state of the RNG must be retained
# between the reads. The output of the RNG on STDOUT is assumed to be binary.
my $state_rng;
# Generate an HMAC based on SHAx
# $1: Key to be used for the HMAC in hex format
# $2: length of the hash to be calculated in bits
# $3: Message for which the HMAC shall be calculated in hex format
# $4: hash type (1 - SHA1, 224 - SHA224, and so on)
# return: calculated HMAC in hex format
my $hmac;
################################################################
##### OpenSSL interface functions
################################################################
sub openssl_encdec($$$$$) {
my $key=shift;
my $iv=shift;
my $cipher=shift;
my $enc = (shift) ? "-e" : "-d";
my $data=shift;
$data=hex2bin($data);
my $program="openssl enc -$cipher -nopad -nosalt -K $key $enc -iv $iv";
$program = "rc4 -k $key" if $opt{'R'}; #for ARCFOUR, no IV must be given
$data=pipe_through_program($data,$program);
return bin2hex($data);
}
sub openssl_rsa_sign($$$) {
my $data = shift;
my $cipher = shift;
my $keyfile = shift;
$data=hex2bin($data);
die "ARCFOUR not available for RSA" if $opt{'R'};
$data=pipe_through_program($data,
"openssl dgst -$cipher -binary -sign $keyfile");
return bin2hex($data);
}
sub openssl_rsa_verify($$$$) {
my $data = shift;
my $cipher = shift;
my $keyfile = shift;
my $sigfile = shift;
$data = hex2bin($data);
die "ARCFOUR not available for RSA" if $opt{'R'};
$data = pipe_through_program($data,
"openssl dgst -$cipher -binary -verify $keyfile -signature $sigfile");
# Parse through the OpenSSL output information
return ($data =~ /OK/);
}
sub openssl_gen_rsakey($$) {
my $keylen = shift;
my $file = shift;
die "ARCFOUR not available for RSA" if $opt{'R'};
# generating of a key with exponent 0x10001
my @args = ("openssl", "genrsa", "-F4", "-out", "$file", "$keylen");
system(@args) == 0
or die "system @args failed: $?";
die "system @args failed: file $file not created" if (! -f $file);
}
sub openssl_hash($$) {
my $pt = shift;
my $cipher = shift;
die "ARCFOUR not available for hashes" if $opt{'R'};
my $hash = hex2bin($pt);
#bin2hex not needed as the '-hex' already converts it
return pipe_through_program($hash, "openssl dgst -$cipher -hex");
}
sub openssl_state_cipher($$$$$) {
my $cipher = shift;
my $encdec = shift;
my $bufsize = shift;
my $key = shift;
my $iv = shift;
my $enc = $encdec ? "-e": "-d";
my $out = "openssl enc -'$cipher' $enc -nopad -nosalt -bufsize $bufsize -K ".bin2hex($key)." -iv ".bin2hex($iv);
#for ARCFOUR, no IV must be given
$out = "rc4 -k " . bin2hex($key) if $opt{'R'};
return $out;
}
###### End of OpenSSL interface implementation ############
###########################################################
###### libgcrypt implementation
###########################################################
+sub libgcrypt_encdec($$$$$) {
+ my $key=shift;
+ my $iv=shift;
+ my $cipher=shift;
+ my $enc = (shift) ? "encrypt" : "decrypt";
+ my $data=shift;
+
+ my $program="fipsdrv --no-fips --key $key --iv $iv --algo $cipher $enc";
+
+ return pipe_through_program($data,$program);
+}
+
+
+sub libgcrypt_rsa_sign($$$) {
+ my $data = shift;
+ my $hashalgo = shift;
+ my $keyfile = shift;
+
+ die "ARCFOUR not available for RSA" if $opt{'R'};
+ return pipe_through_program($data,
+ "fipsdrv --verbose --algo $hashalgo --key $keyfile rsa-sign");
+}
+
+
+sub libgcrypt_rsa_verify($$$$) {
+ my $data = shift;
+ my $cipher = shift;
+ my $keyfile = shift;
+ my $sigfile = shift;
+
+ $data = hex2bin($data);
+ die "ARCFOUR not available for RSA" if $opt{'R'};
+ $data = pipe_through_program($data,
+ "fipsdrv --key $keyfile rsa-verify");
+
+ # Parse through the OpenSSL output information
+ return ($data =~ /OK/);
+}
+
+
+sub libgcrypt_gen_rsakey($$) {
+ my $keylen = shift;
+ my $file = shift;
+
+ die "ARCFOUR not available for RSA" if $opt{'R'};
+ my @args = ("fipsdrv --keysize $keylen rsa-gen > $file");
+ system(@args) == 0
+ or die "system @args failed: $?";
+ die "system @args failed: file $file not created" if (! -f $file);
+}
+
+
+sub libgcrypt_hash($$) {
+ my $pt = shift;
+ my $hashalgo = shift;
+
+ my $program = "fipsdrv --no-fips --algo $hashalgo digest";
+ die "ARCFOUR not available for hashes" if $opt{'R'};
+
+ return pipe_through_program($pt, $program);
+}
+
+
+sub libgcrypt_state_cipher($$$$$) {
+ my $cipher = shift;
+ my $enc = (shift) ? "encrypt": "decrypt";
+ my $bufsize = shift;
+ my $key = shift;
+ my $iv = shift;
+
+ my $program="fipsdrv --no-fips --binary --key ".bin2hex($key)." --iv ".bin2hex($iv)." --algo '$cipher' --chunk '$bufsize' $enc";
+ return $program;
+}
+
+
sub libgcrypt_state_rng($$$) {
my $key = shift;
my $dt = shift;
my $v = shift;
- return "fipsrngdrv --binary --loop $key $v $dt";
+ return "fipsdrv --binary --progress --loop --key $key --iv $v --dt $dt random";
}
sub libgcrypt_hmac($$$$) {
my $key = shift;
my $maclen = shift;
my $msg = shift;
my $hashtype = shift;
- die "libgcrypt HMAC test not yet implemented: key $key, maclen $maclen, msg $msg, hashtype $hashtype";
-
+ my $program = "fipsdrv --no-fips --key $key --algo $hashtype hmac-sha";
+ return pipe_through_program($msg, $program);
}
######### End of libgcrypt implementation ################
##### No other interface functions below this point ######
##########################################################
##########################################################
# General helper routines
# Executing a program by feeding STDIN and retrieving
# STDOUT
# $1: data string to be piped to the app on STDIN
# rest: program and args
# returns: STDOUT of program as string
sub pipe_through_program($@) {
my $in = shift;
my @args = @_;
my ($CO, $CI);
my $pid = open2($CO, $CI, @args);
my $out = "";
my $len = length($in);
my $first = 1;
while (1) {
my $rin = "";
my $win = "";
# Output of prog is FD that we read
vec($rin,fileno($CO),1) = 1;
# Input of prog is FD that we write
# check for $first is needed because we can have NULL input
# that is to be written to the app
if ( $len > 0 || $first) {
(vec($win,fileno($CI),1) = 1);
$first=0;
}
# Let us wait for 100ms
my $nfound = select(my $rout=$rin, my $wout=$win, undef, 0.1);
if ( $wout ) {
my $written = syswrite($CI, $in, $len);
die "broken pipe" if !defined $written;
$len -= $written;
substr($in, 0, $written) = "";
if ($len <= 0) {
close $CI or die "broken pipe: $!";
}
}
if ( $rout ) {
my $tmp_out = "";
my $bytes_read = sysread($CO, $tmp_out, 4096);
$out .= $tmp_out;
last if ($bytes_read == 0);
}
}
close $CO or die "broken pipe: $!";
waitpid $pid, 0;
return $out;
}
#
# convert ASCII hex to binary input
# $1 ASCII hex
# return binary representation
sub hex2bin($) {
my $in = shift;
my $len = length($in);
$len = 0 if ($in eq "00");
return pack("H$len", "$in");
}
#
# convert binary input to ASCII hex
# $1 binary value
# return ASCII hex representation
sub bin2hex($) {
my $in = shift;
my $len = length($in)*2;
return unpack("H$len", "$in");
}
# $1: binary byte (character)
# returns: binary byte with odd parity using low bit as parity bit
sub odd_par($) {
my $in = ord(shift);
my $odd_count=0;
for(my $i=1; $i<8; $i++) {
$odd_count++ if ($in & (1<<$i));
}
my $out = $in;
if ($odd_count & 1) { # check if parity is already odd
$out &= ~1; # clear the low bit
} else {
$out |= 1; # set the low bit
}
return chr($out);
}
# DES keys uses only the 7 high bits of a byte, the 8th low bit
# is the parity bit
# as the new key is calculated from oldkey XOR cipher in the MCT test,
# the parity is not really checked and needs to be set to match
# expectation (OpenSSL does not really care, but the FIPS
# test result is expected that the key has the appropriate parity)
# $1: arbitrary binary string
# returns: string with odd parity set in low bit of each byte
sub fix_key_parity($) {
my $in = shift;
my $out = "";
for (my $i = 0; $i < length($in); $i++) {
$out .= odd_par(substr($in, $i, 1));
}
return $out;
}
####################################################
# Encrypt/Decrypt routines
# encryption
# $1 key in hex form
# $2 iv in hex form
# $3 cipher
# $4 data in hex form
# return encrypted data
sub encrypt($$$$) {
my $key=shift;
my $iv=shift;
my $cipher=shift;
my $data=shift;
return &$encdec($key, $iv, $cipher, 1, $data);
}
# decryption
# $1 key in hex form
# $2 iv in hex form
# $3 cipher
# $4 data in hex form
# return encrypted data
sub decrypt($$$$) {
my $key=shift;
my $iv=shift;
my $cipher=shift;
my $data=shift;
return &$encdec($key, $iv, $cipher, 0, $data);
}
####################################################
# DER/PEM utility functions
# Cf. http://www.columbia.edu/~ariel/ssleay/layman.html
# Convert unsigned integer to base256 bigint bytes
# $1 integer
# returns base256 octet string
sub int_base256_unsigned($) {
my $n = shift;
my $out = chr($n & 255);
while ($n>>=8) {
$out = chr($n & 255) . $out;
}
return $out;
}
# Convert signed integer to base256 bigint bytes
# $1 integer
# returns base256 octet string
sub int_base256_signed($) {
my $n = shift;
my $negative = ($n < 0);
if ($negative) {
$n = -$n-1;
}
my $out = int_base256_unsigned($n);
if (ord(substr($out, 0, 1)) & 128) {
# it's supposed to be positive but has sign bit set,
# add a leading zero
$out = chr(0) . $out;
}
if ($negative) {
my $neg = chr(255) x length($out);
$out ^= $neg;
}
return $out;
}
# Length header for specified DER object length
# $1 length as integer
# return octet encoding for length
sub der_len($) {
my $len = shift;
if ($len <= 127) {
return chr($len);
} else {
my $blen = int_base256_unsigned($len);
return chr(128 | length($blen)) . $blen;
}
}
# Prepend length header to object
# $1 object as octet sequence
# return length header for object followed by object as octets
sub der_len_obj($) {
my $x = shift;
return der_len(length($x)) . $x;
}
# DER sequence
# $* objects
# returns DER sequence consisting of the objects passed as arguments
sub der_seq {
my $seq = join("", @_);
return chr(0x30) . der_len_obj($seq);
}
# DER bitstring
# $1 input octets (must be full octets, fractional octets not supported)
# returns input encapsulated as bitstring
sub der_bitstring($) {
my $x = shift;
$x = chr(0) . $x;
return chr(0x03) . der_len_obj($x);
}
# base-128-encoded integer, used for object numbers.
# $1 integer
# returns octet sequence
sub der_base128($) {
my $n = shift;
my $out = chr($n & 127);
while ($n>>=7) {
$out = chr(128 | ($n & 127)) . $out;
}
return $out;
}
# Generating the PEM certificate string
# (base-64-encoded DER string)
# $1 DER string
# returns octet sequence
sub pem_cert($) {
my $n = shift;
my $out = "-----BEGIN PUBLIC KEY-----\n";
$out .= encode_base64($n);
$out .= "-----END PUBLIC KEY-----\n";
return $out;
}
# DER object identifier
# $* sequence of id numbers
# returns octets
sub der_objectid {
my $v1 = shift;
my $v2 = shift;
my $out = chr(40*$v1 + $v2) . join("", map { der_base128($_) } @_);
return chr(0x06) . der_len_obj($out);
}
# DER signed integer
# $1 number as octet string (base 256 representation, high byte first)
# returns number in DER integer encoding
sub der_bigint($) {
my $x = shift;
return chr(0x02) . der_len_obj($x);
}
# DER positive integer with leading zeroes stripped
# $1 number as octet string (base 256 representation, high byte first)
# returns number in DER integer encoding
sub der_pos_bigint($) {
my $x = shift;
# strip leading zero digits
$x =~ s/^[\0]+//;
# need to prepend a zero if high bit set, since it would otherwise be
# interpreted as a negative number. Also needed for number 0.
if (!length($x) || ord(substr($x, 0, 1)) >= 128) {
$x = chr(0) . $x;
}
return der_bigint($x);
}
# $1 number as signed integer
# returns number as signed DER integer encoding
sub der_int($) {
my $n = shift;
return der_bigint(int_base256_signed($n));
}
# the NULL object constant
sub der_null() {
return chr(0x05) . chr(0x00);
}
# Unit test helper
# $1 calculated result
# $2 expected result
# no return value, dies if results differ, showing caller's line number
sub der_test($$) {
my $actual = bin2hex(shift);
my $expected = shift;
my @caller = caller;
$actual eq $expected or die "Error:line $caller[2]:assertion failed: "
."$actual != $expected\n";
}
# Unit testing for the DER encoding functions
# Examples from http://www.columbia.edu/~ariel/ssleay/layman.html
# No input, no output. Dies if unit tests fail.
sub der_unit_test {
## uncomment these if you want to test the test framework
#print STDERR "Unit test running\n";
#der_test chr(0), "42";
der_test der_null, "0500";
# length bytes
der_test der_len(1), "01";
der_test der_len(127), "7f";
der_test der_len(128), "8180";
der_test der_len(256), "820100";
der_test der_len(65536), "83010000";
# bigint
der_test der_bigint(chr(0)), "020100";
der_test der_bigint(chr(128)), "020180"; # -128
der_test der_pos_bigint(chr(128)), "02020080"; # +128
der_test der_pos_bigint(chr(0).chr(0).chr(1)), "020101";
der_test der_pos_bigint(chr(0)), "020100";
# integers (tests base256 conversion)
der_test der_int( 0), "020100";
der_test der_int( 127), "02017f";
der_test der_int( 128), "02020080";
der_test der_int( 256), "02020100";
der_test der_int( -1), "0201ff";
der_test der_int( -128), "020180";
der_test der_int( -129), "0202ff7f";
der_test der_int(-65536), "0203ff0000";
der_test der_int(-65537), "0203feffff";
# object encoding, "RSA Security"
der_test der_base128(840), "8648";
der_test der_objectid(1, 2, 840, 113549), "06062a864886f70d";
# Combinations
der_test der_bitstring("ABCD"), "03050041424344";
der_test der_bitstring(der_null), "0303000500";
der_test der_seq(der_int(0), der_null), "30050201000500";
# The big picture
der_test der_seq(der_seq(der_objectid(1, 2, 840, 113549), der_null),
der_bitstring(der_seq(der_pos_bigint(chr(5)),
der_pos_bigint(chr(3))))),
"3017300a06062a864886f70d05000309003006020105020103";
}
####################################################
# OpenSSL missing functionality workarounds
## Format of an RSA public key:
# 0:d=0 hl=3 l= 159 cons: SEQUENCE
# 3:d=1 hl=2 l= 13 cons: SEQUENCE
# 5:d=2 hl=2 l= 9 prim: OBJECT :rsaEncryption
# 16:d=2 hl=2 l= 0 prim: NULL
# 18:d=1 hl=3 l= 141 prim: BIT STRING
# [ sequence: INTEGER (n), INTEGER (e) ]
# generate RSA pub key in PEM format
# $1: filename where PEM key is to be stored
# $2: n of the RSA key in hex
# $3: e of the RSA key in hex
# return: nothing, but file created
sub gen_pubrsakey($$$) {
my $filename=shift;
my $n = shift;
my $e = shift;
# make sure the DER encoder works ;-)
der_unit_test();
# generate DER encoding of the public key
my $rsaEncryption = der_objectid(1, 2, 840, 113549, 1, 1, 1);
my $der = der_seq(der_seq($rsaEncryption, der_null),
der_bitstring(der_seq(der_pos_bigint(hex2bin($n)),
der_pos_bigint(hex2bin($e)))));
open(FH, ">", $filename) or die;
print FH pem_cert($der);
close FH;
}
# generate RSA pub key in PEM format
#
# This implementation uses "openssl asn1parse -genconf" which was added
# in openssl 0.9.8. It is not available in older openssl versions.
#
# $1: filename where PEM key is to be stored
# $2: n of the RSA key in hex
# $3: e of the RSA key in hex
# return: nothing, but file created
sub gen_pubrsakey_using_openssl($$$) {
my $filename=shift;
my $n = shift;
my $e = shift;
my $asn1 = "asn1=SEQUENCE:pubkeyinfo
[pubkeyinfo]
algorithm=SEQUENCE:rsa_alg
pubkey=BITWRAP,SEQUENCE:rsapubkey
[rsa_alg]
algorithm=OID:rsaEncryption
parameter=NULL
[rsapubkey]
n=INTEGER:0x$n
e=INTEGER:0x$e";
open(FH, ">$filename.cnf") or die "Cannot create file $filename.cnf: $?";
print FH $asn1;
close FH;
my @args = ("openssl", "asn1parse", "-genconf", "$filename.cnf", "-noout", "-out", "$filename.der");
system(@args) == 0 or die "system @args failed: $?";
@args = ("openssl", "rsa", "-inform", "DER", "-in", "$filename.der",
"-outform", "PEM", "-pubin", "-pubout", "-out", "$filename");
system(@args) == 0 or die "system @args failed: $?";
die "RSA PEM formatted key file $filename was not created"
if (! -f $filename);
unlink("$filename.cnf");
unlink("$filename.der");
}
############################################
# Test cases
# This is the Known Answer Test
# $1: the string that we have to put in front of the key
# when printing the key
# $2: crypto key1 in hex form
# $3: crypto key2 in hex form (TDES, undef otherwise)
# $4: crypto key3 in hex form (TDES, undef otherwise)
# $5: IV in hex form
# $6: Plaintext (enc=1) or Ciphertext (enc=0) in hex form
# $7: cipher
# $8: encrypt=1/decrypt=0
# return: string formatted as expected by CAVS
sub kat($$$$$$$$) {
my $keytype = shift;
my $key1 = shift;
my $key2 = shift;
my $key3 = shift;
my $iv = shift;
my $pt = shift;
my $cipher = shift;
my $enc = shift;
my $out = "";
$out .= "$keytype = $key1\n";
# this is the concardination of the keys for 3DES
if (defined($key2)) {
$out .= "KEY2 = $key2\n";
$key1 = $key1 . $key2;
}
if (defined($key3)) {
$out .= "KEY3 = $key3\n";
$key1= $key1 . $key3;
}
$out .= "IV = $iv\n";
if ($enc) {
$out .= "PLAINTEXT = $pt\n";
$out .= "CIPHERTEXT = " . encrypt($key1, $iv, $cipher, $pt) . "\n";
} else {
$out .= "CIPHERTEXT = $pt\n";
$out .= "PLAINTEXT = " . decrypt($key1, $iv, $cipher, $pt) . "\n";
}
return $out;
}
# This is the Known Answer Test for Hashes
# $1: Plaintext in hex form
# $2: hash
# $3: hash length (undef if not applicable)
# return: string formatted as expected by CAVS
sub hash_kat($$$) {
my $pt = shift;
my $cipher = shift;
my $len = shift;
my $out = "";
$out .= "Len = $len\n" if (defined($len));
$out .= "Msg = $pt\n";
$out .= "MD = " . &$hash($pt, $cipher);
return $out;
}
# Known Answer Test for HMAC hash
# $1: key length in bytes
# $2: MAC length in bytes
# $3: key for HMAC in hex form
# $4: message to be hashed
# return: string formatted as expected by CAVS
sub hmac_kat($$$$) {
my $klen = shift;
my $tlen = shift;
my $key = shift;
my $msg = shift;
# XXX this is a hack - we need to decipher the HMAC REQ files in a more
# sane way
#
# This is a conversion table from the expected hash output size
# to the assumed hash type - we only define here the block size of
# the underlying hashes and do not allow any truncation
my %hashtype = (
20 => 1,
28 => 224,
32 => 256,
48 => 384,
64 => 512
);
die "Hash output size $tlen is not supported!"
if(!defined($hashtype{$tlen}));
my $out = "";
$out .= "Klen = $klen\n";
$out .= "Tlen = $tlen\n";
$out .= "Key = $key\n";
$out .= "Msg = $msg\n";
$out .= "Mac = " . &$hmac($key, $tlen, $msg, $hashtype{$tlen}) . "\n\n";
return $out;
}
# Cipher Monte Carlo Testing
# $1: the string that we have to put in front of the key
# when printing the key
# $2: crypto key1 in hex form
# $3: crypto key2 in hex form (TDES, undef otherwise)
# $4: crypto key3 in hex form (TDES, undef otherwise)
# $5: IV in hex form
# $6: Plaintext (enc=1) or Ciphertext (enc=0) in hex form
# $7: cipher
# $8: encrypt=1/decrypt=0
# return: string formatted as expected by CAVS
sub crypto_mct($$$$$$$$) {
my $keytype = shift;
my $key1 = hex2bin(shift);
my $key2 = shift;
my $key3 = shift;
my $iv = hex2bin(shift);
my $source_data = hex2bin(shift);
my $cipher = shift;
my $enc = shift;
my $out = "";
$key2 = hex2bin($key2) if (defined($key2));
$key3 = hex2bin($key3) if (defined($key3));
my $bufsize = length($source_data);
# for AES: outer loop 0-99, inner 0-999 based on FIPS compliance tests
# for RC4: outer loop 0-99, inner 0-999 based on atsec compliance tests
# for DES: outer loop 0-399, inner 0-9999 based on FIPS compliance tests
my $ciph = substr($cipher,0,3);
my $oloop=100;
my $iloop=1000;
if ($ciph =~ /des/) {$oloop=400;$iloop=10000;}
for (my $i=0; $i<$oloop; ++$i) {
$out .= "COUNT = $i\n";
if (defined($key2)) {
$out .= "$keytype = ". bin2hex($key1). "\n";
$out .= "KEY2 = ". bin2hex($key2). "\n";
$key1 = $key1 . $key2;
} else {
$out .= "$keytype = ". bin2hex($key1). "\n";
}
if(defined($key3)) {
$out .= "KEY3 = ". bin2hex($key3). "\n";
$key1 = $key1 . $key3;
}
my $keylen = length($key1);
$out .= "IV = ". bin2hex($iv). "\n";
if ($enc) {
$out .= "PLAINTEXT = ". bin2hex($source_data). "\n";
} else {
$out .= "CIPHERTEXT = ". bin2hex($source_data). "\n";
}
my ($CO, $CI);
my $cipher_imp = &$state_cipher($cipher, $enc, $bufsize, $key1, $iv);
my $pid = open2($CO, $CI, $cipher_imp);
my $calc_data = $iv; # CT[j]
my $old_calc_data; # CT[j-1]
my $old_old_calc_data; # CT[j-2]
for (my $j = 0; $j < $iloop; ++$j) {
$old_old_calc_data = $old_calc_data;
$old_calc_data = $calc_data;
# $calc_data = AES($key, $calc_data);
- #print STDERR "source_data=", bin2hex($source_data), "\n";
+ #print STDERR "source_data=", bin2hex($source_data), "\n";
syswrite $CI, $source_data or die;
my $len = sysread $CO, $calc_data, $bufsize;
- #print STDERR "len=$len, bufsize=$bufsize\n";
+ #print STDERR "len=$len, bufsize=$bufsize\n";
die if $len ne $bufsize;
- #print STDERR "calc_data=", bin2hex($calc_data), "\n";
+ #print STDERR "calc_data=", bin2hex($calc_data), "\n";
if ( (!$enc && $ciph =~ /des/) ||
$ciph =~ /rc4/ ) {
#TDES in decryption mode and RC4 have a special rule
$source_data = $calc_data;
} else {
$source_data = $old_calc_data;
}
}
close $CO;
close $CI;
waitpid $pid, 0;
if ($enc) {
$out .= "CIPHERTEXT = ". bin2hex($calc_data). "\n\n";
} else {
$out .= "PLAINTEXT = ". bin2hex($calc_data). "\n\n";
}
if ( $ciph =~ /aes/ ) {
$key1 ^= substr($old_calc_data . $calc_data, -$keylen);
#print STDERR bin2hex($key1)."\n";
} elsif ( $ciph =~ /des/ ) {
die "Wrong keylen $keylen" if ($keylen != 24);
# $nkey needed as $key holds the concatenation of the
# old key atm
my $nkey = fix_key_parity(substr($key1,0,8) ^ $calc_data);
#print STDERR "KEY1 = ". bin2hex($nkey)."\n";
if (substr($key1,0,8) ne substr($key1,8,8)) {
#print STDERR "KEY2 recalc: KEY1==KEY3, KEY2 indep. or all KEYs are indep.\n";
$key2 = fix_key_parity((substr($key1,8,8) ^ $old_calc_data));
} else {
#print STDERR "KEY2 recalc: KEY1==KEY2==KEY3\n";
$key2 = fix_key_parity((substr($key1,8,8) ^ $calc_data));
}
#print STDERR "KEY2 = ". bin2hex($key2)."\n";
if ( substr($key1,0,8) eq substr($key1,16)) {
#print STDERR "KEY3 recalc: KEY1==KEY2==KEY3 or KEY1==KEY3, KEY2 indep.\n";
$key3 = fix_key_parity((substr($key1,16) ^ $calc_data));
} else {
#print STDERR "KEY3 recalc: all KEYs are independent\n";
$key3 = fix_key_parity((substr($key1,16) ^ $old_old_calc_data));
}
#print STDERR "KEY3 = ". bin2hex($key3)."\n";
# reset the first key - concardination happens at
# beginning of loop
$key1=$nkey;
} elsif ($ciph =~ /rc4/ ) {
$key1 ^= substr($calc_data, 0, 16);
#print STDERR bin2hex($key1)."\n";
} else {
die "Test limitation: cipher '$cipher' not supported in Monte Carlo testing";
}
if (! $enc && $ciph =~ /des/ ) {
#TDES in decryption mode has a special rule
$iv = $old_calc_data;
$source_data = $calc_data;
} elsif ( $ciph =~ /rc4/ ) {
#No resetting of IV as the IV is all zero set initially (i.e. no IV)
$source_data = $calc_data;
} else {
$iv = $calc_data;
$source_data = $old_calc_data;
}
}
return $out;
}
# Hash Monte Carlo Testing
# $1: Plaintext in hex form
# $2: hash
# return: string formatted as expected by CAVS
sub hash_mct($$) {
my $pt = shift;
my $cipher = shift;
my $out = "";
$out .= "Seed = $pt\n\n";
for (my $j=0; $j<100; ++$j) {
$out .= "COUNT = $j\n";
my $md0=$pt;
my $md1=$pt;
my $md2=$pt;
for (my $i=0; $i<1000; ++$i) {
my $mi= $md0 . $md1 . $md2;
$md0=$md1;
$md1=$md2;
$md2 = &$hash($mi, $cipher);
$md2 =~ s/\n//;
}
$out .= "MD = $md2\n\n";
$pt=$md2;
}
return $out;
}
# RSA SigGen test
# $1: Message to be signed in hex form
# $2: Hash algorithm
# $3: file name with RSA key in PEM form
# return: string formatted as expected by CAVS
sub rsa_siggen($$$) {
my $data = shift;
my $cipher = shift;
my $keyfile = shift;
my $out = "";
$out .= "SHAAlg = $cipher\n";
$out .= "Msg = $data\n";
$out .= "S = " . &$rsa_sign($data, $cipher, $keyfile) . "\n";
return $out;
}
# RSA SigVer test
# $1: Message to be verified in hex form
# $2: Hash algoritm
# $3: Signature of message in hex form
# $4: n of the RSA key in hex in hex form
# $5: e of the RSA key in hex in hex form
# return: string formatted as expected by CAVS
sub rsa_sigver($$$$$) {
my $data = shift;
my $cipher = shift;
my $signature = shift;
my $n = shift;
my $e = shift;
my $out = "";
$out .= "SHAAlg = $cipher\n";
$out .= "e = $e\n";
$out .= "Msg = $data\n";
$out .= "S = $signature\n";
# XXX maybe a secure temp file name is better here
# but since it is not run on a security sensitive
# system, I hope that this is fine
my $keyfile = "rsa_sigver.tmp.$$";
gen_pubrsakey($keyfile, $n, $e);
my $sigfile = "$keyfile.sig";
open(FH, ">$sigfile") or die "Cannot create file $sigfile: $?";
print FH hex2bin($signature);
close FH;
$out .= "Result = " . (&$rsa_verify($data, $cipher, $keyfile, $sigfile) ? "P\n" : "F\n");
unlink($keyfile);
unlink($sigfile);
return $out;
}
# X9.31 RNG test
# $1 key for the AES cipher
# $2 DT value
# $3 V value
# $4 type ("VST", "MCT")
# return: string formatted as expected by CAVS
sub rngx931($$$$) {
my $key=shift;
my $dt=shift;
my $v=shift;
my $type=shift;
my $out = "Key = $key\n";
$out .= "DT = $dt\n";
$out .= "V = $v\n";
my $count = 1;
$count = 10000 if ($type eq "MCT");
my $rnd_val = "";
# we read 16 bytes from RNG
my $bufsize = 16;
my ($CO, $CI);
my $rng_imp = &$state_rng($key, $dt, $v);
my $pid = open2($CO, $CI, $rng_imp);
for (my $i = 0; $i < $count; ++$i) {
my $len = sysread $CO, $rnd_val, $bufsize;
#print STDERR "len=$len, bufsize=$bufsize\n";
die "len=$len != bufsize=$bufsize" if $len ne $bufsize;
#print STDERR "calc_data=", bin2hex($rnd_val), "\n";
}
close $CO;
close $CI;
waitpid $pid, 0;
$out .= "R = " . bin2hex($rnd_val) . "\n\n";
return $out;
}
##############################################################
# Parser of input file and generator of result file
#
sub usage() {
print STDERR "Usage:
-$0 [-R] <CAVS-test vector file>
-
--R execution of ARCFOUR instead of OpenSSL";
+$0 [-R] [-I name] <CAVS-test vector file>
+-R execution of ARCFOUR instead of OpenSSL
+-I NAME Use interface style NAME:
+ openssl OpenSSL (default)
+ libgcrypt Libgcrypt";
}
# Parser of CAVS test vector file
# $1: Test vector file
# $2: Output file for test results
# return: nothing
sub parse($$) {
my $infile = shift;
my $outfile = shift;
my $out = "";
# Do I need to generate the key?
my $rsa_keygen = 0;
# this is my cipher/hash type
my $cipher = "";
# Test type
# 1 - cipher known answer test
# 2 - cipher Monte Carlo test
# 3 - hash known answer test
# 4 - hash Monte Carlo test
# 5 - RSA signature generation
# 6 - RSA signature verification
my $tt = 0;
# Variables for tests
my $keytype = ""; # we can have "KEY", "KEYs", "KEY1"
my $key1 = "";
my $key2 = undef; #undef needed for allowing
my $key3 = undef; #the use of them as input variables
my $pt = "";
my $enc = 1;
my $iv = "";
my $len = undef; #see key2|3
my $n = "";
my $e = "";
my $signature = "";
my $rsa_keyfile = "";
my $dt = "";
my $v = "";
my $klen = "";
my $tlen = "";
my $mode = "";
open(IN, "<$infile");
while(<IN>) {
my $line = $_;
chomp($line);
$line =~ s/\r//;
my $keylen = "";
# Mode and type check
# consider the following parsed line
# '# AESVS MCT test data for CBC'
# '# TDES Multi block Message Test for CBC'
# '# INVERSE PERMUTATION - KAT for CBC'
# '# SUBSTITUTION TABLE - KAT for CBC'
# '# TDES Monte Carlo (Modes) Test for CBC'
# '# "SHA-1 Monte" information for "IBMRHEL5"'
# '# "SigVer PKCS#1 Ver 1.5" information for "IBMRHEL5"'
# '# "SigGen PKCS#1 Ver 1.5" information for "IBMRHEL5"'
# '#RC4VS MCT test data'
# avoid false positives from user specified 'for "PRODUCT"' strings
my $tmpline = $line;
$tmpline =~ s/ for ".*"//;
##### Extract cipher
# XXX there may be more - to be added
if ($tmpline =~ /^#.*(CBC|ECB|OFB|CFB|SHA-|SigGen|SigVer|RC4VS|ANSI X9\.31|Hash sizes tested)/) {
if ($tmpline =~ /CBC/) { $mode="cbc"; }
elsif ($tmpline =~ /ECB/) { $mode="ecb"; }
elsif ($tmpline =~ /OFB/) { $mode="ofb"; }
elsif ($tmpline =~ /CFB/) { $mode="cfb"; }
#we do not need mode as the cipher is already clear
elsif ($tmpline =~ /SHA-1/) { $cipher="sha1"; }
elsif ($tmpline =~ /SHA-224/) { $cipher="sha224"; }
elsif ($tmpline =~ /SHA-256/) { $cipher="sha256"; }
elsif ($tmpline =~ /SHA-384/) { $cipher="sha384"; }
elsif ($tmpline =~ /SHA-512/) { $cipher="sha512"; }
#we do not need mode as the cipher is already clear
elsif ($tmpline =~ /RC4VS/) { $cipher="rc4"; }
elsif ($tmpline =~ /SigGen|SigVer/) {
die "Error: X9.31 is not supported"
if ($tmpline =~ /X9/);
$cipher="sha1"; #place holder - might be overwritten later
}
# RSA Key Generation test
if ($tmpline =~ /SigGen/) {
$rsa_keygen = 1;
}
if ($tmpline =~ /^#.*AESVS/) {
# AES cipher (part of it)
$cipher="aes";
}
if ($tmpline =~ /^#.*(TDES|KAT)/) {
# TDES cipher (full definition)
# the FIPS-140 test generator tool does not produce
# machine readable output!
if ($mode eq "cbc") { $cipher="des-ede3-cbc"; }
if ($mode eq "ecb") { $cipher="des-ede3"; }
if ($mode eq "ofb") { $cipher="des-ede3-ofb"; }
if ($mode eq "cfb") { $cipher="des-ede3-cfb"; }
}
# check for RNG
if ($tmpline =~ /ANSI X9\.31/) {
# change the tmpline to add the type of the
# test which is ONLY visible from the file
# name :-(
if ($infile =~ /MCT\.req/) {
$tmpline .= " MCT";
} elsif ($infile =~ /VST\.req/) {
$tmpline .= " VST";
} else {
die "Unexpected cipher type with $infile";
}
}
##### Identify the test type
if ($tmpline =~ /Hash sizes tested/) {
$tt = 9;
die "Interface function hmac for HMAC testing not defined for tested library"
if (!defined($hmac));
} elsif ($tmpline =~ /ANSI X9\.31/ && $tmpline =~ /MCT/) {
$tt = 8;
die "Interface function state_rng for RNG MCT not defined for tested library"
if (!defined($state_rng));
} elsif ($tmpline =~ /ANSI X9\.31/ && $tmpline =~ /VST/) {
$tt = 7;
die "Interface function state_rng for RNG KAT not defined for tested library"
if (!defined($state_rng));
} elsif ($tmpline =~ /SigVer/ ) {
$tt = 6;
die "Interface function rsa_verify or gen_rsakey for RSA verification not defined for tested library"
if (!defined($rsa_verify) || !defined($gen_rsakey));
} elsif ($tmpline =~ /SigGen/ ) {
$tt = 5;
die "Interface function rsa_sign or gen_rsakey for RSA sign not defined for tested library"
if (!defined($rsa_sign) || !defined($gen_rsakey));
} elsif ($tmpline =~ /Monte|MCT|Carlo/ && $cipher eq "sha") {
$tt = 4;
die "Interface function hash for Hashing not defined for tested library"
if (!defined($hash));
} elsif ($tmpline =~ /Monte|MCT|Carlo/) {
$tt = 2;
die "Interface function state_cipher for Stateful Cipher operation defined for tested library"
if (!defined($state_cipher));
} elsif ($cipher eq "sha" && $tt!=5 && $tt!=6) {
$tt = 3;
die "Interface function hash for Hashing not defined for tested library"
if (!defined($hash));
} else {
$tt = 1;
die "Interface function encdec for Encryption/Decryption not defined for tested library"
if (!defined($encdec));
}
}
# This is needed as ARCFOUR does not operate with an IV
$iv = "00000000000000000000000000000000" if ($cipher eq "rc4"
&& $iv eq "" );
# we are now looking for the string
# '# Key Length : 256'
# found in AES
if ($tmpline =~ /^# Key Length.*?(128|192|256)/) {
if ($cipher eq "aes") {
$cipher="$cipher-$1-$mode";
} else {
die "Error: Key length $1 given for cipher $cipher which is unexpected";
}
}
# Get the test data
if ($line =~ /^(KEY|KEYs|KEY1|Key)\s*=\s*(.*)/) { # found in ciphers and RNG
die "KEY seen twice - input file crap" if ($key1 ne "");
$keytype=$1;
$key1=$2;
$key1 =~ s/\s//g; #replace potential white spaces
}
elsif ($line =~ /^KEY2\s*=\s*(.*)/) { # found in TDES
die "First key not set, but got already second key - input file crap" if ($key1 eq "");
die "KEY2 seen twice - input file crap" if (defined($key2));
$key2=$1;
$key2 =~ s/\s//g; #replace potential white spaces
}
elsif ($line =~ /^KEY3\s*=\s*(.*)/) { # found in TDES
die "Second key not set, but got already third key - input file crap" if ($key2 eq "");
die "KEY3 seen twice - input file crap" if (defined($key3));
$key3=$1;
$key3 =~ s/\s//g; #replace potential white spaces
}
elsif ($line =~ /^IV\s*=\s*(.*)/) { # found in ciphers
die "IV seen twice - input file crap" if ($iv ne "");
$iv=$1;
$iv =~ s/\s//g; #replace potential white spaces
}
elsif ($line =~ /^PLAINTEXT\s*=\s*(.*)/) { # found in ciphers
if ( $1 !~ /\?/ ) { #only use it if there is valid hex data
die "PLAINTEXT/CIPHERTEXT seen twice - input file crap" if ($pt ne "");
$pt=$1;
$pt =~ s/\s//g; #replace potential white spaces
$enc=1;
}
}
elsif ($line =~ /^CIPHERTEXT\s*=\s*(.*)/) { # found in ciphers
if ( $1 !~ /\?/ ) { #only use it if there is valid hex data
die "PLAINTEXT/CIPHERTEXT seen twice - input file crap" if ($pt ne "");
$pt=$1;
$pt =~ s/\s//g; #replace potential white spaces
$enc=0;
}
}
elsif ($line =~ /^Len\s*=\s*(.*)/) { # found in hashs
$len=$1;
}
elsif ($line =~ /^(Msg|Seed)\s*=\s*(.*)/) { # found in hashs
die "Msg/Seed seen twice - input file crap" if ($pt ne "");
$pt=$2;
}
elsif ($line =~ /^\[mod\s*=\s*(.*)\]$/) { # found in RSA requests
$out .= $line . "\n"; # print it
# generate the private key with given bit length now
# as we have the required key length in bit
if ($tt == 5) {
# XXX maybe a secure temp file name is better here
# but since it is not run on a security sensitive
# system, I hope that this is fine
$rsa_keyfile = "rsa_siggen.tmp.$$";
&$gen_rsakey($1, $rsa_keyfile);
my $modulus = pipe_through_program("", "openssl rsa -pubout -modulus -in $rsa_keyfile");
$modulus =~ s/Modulus=(.*?)\s(.|\s)*/$1/;
$out .= "\nn = $modulus\n";
$out .= "\ne = 10001\n"
}
}
elsif ($line =~ /^SHAAlg\s*=\s*(.*)/) { #found in RSA requests
$cipher=$1;
}
elsif($line =~ /^n\s*=\s*(.*)/) { # found in RSA requests
$out .= $line . "\n";
$n=$1;
}
elsif ($line =~ /^e\s*=\s*(.*)/) { # found in RSA requests
$e=$1;
}
elsif ($line =~ /^S\s*=\s*(.*)/) { # found in RSA requests
die "S seen twice - input file crap" if ($signature ne "");
$signature=$1;
}
elsif ($line =~ /^DT\s*=\s*(.*)/) { # X9.31 RNG requests
die "DT seen twice - check input file"
if ($dt ne "");
$dt=$1;
}
elsif ($line =~ /^V\s*=\s*(.*)/) { # X9.31 RNG requests
die "V seen twice - check input file"
if ($v ne "");
$v=$1;
}
elsif ($line =~ /^Klen\s*=\s*(.*)/) { # HMAC requests
die "Klen seen twice - check input file"
if ($klen ne "");
$klen=$1;
}
elsif ($line =~ /^Tlen\s*=\s*(.*)/) { # HMAC RNG requests
die "Tlen seen twice - check input file"
if ($tlen ne "");
$tlen=$1;
}
else {
$out .= $line . "\n";
}
# call tests if all input data is there
if ($tt == 1) {
if ($key1 ne "" && $iv ne "" && $pt ne "" && $cipher ne "") {
$out .= kat($keytype, $key1, $key2, $key3, $iv, $pt, $cipher, $enc);
$keytype = "";
$key1 = "";
$key2 = undef;
$key3 = undef;
$iv = "";
$pt = "";
}
}
elsif ($tt == 2) {
if ($key1 ne "" && $iv ne "" && $pt ne "" && $cipher ne "") {
$out .= crypto_mct($keytype, $key1, $key2, $key3, $iv, $pt, $cipher, $enc);
$keytype = "";
$key1 = "";
$key2 = undef;
$key3 = undef;
$iv = "";
$pt = "";
}
}
elsif ($tt == 3) {
if ($pt ne "" && $cipher ne "") {
$out .= hash_kat($pt, $cipher, $len);
$pt = "";
$len = undef;
}
}
elsif ($tt == 4) {
if ($pt ne "" && $cipher ne "") {
$out .= hash_mct($pt, $cipher);
$pt = "";
}
}
elsif ($tt == 5) {
if ($pt ne "" && $cipher ne "" && $rsa_keyfile ne "") {
$out .= rsa_siggen($pt, $cipher, $rsa_keyfile);
$pt = "";
}
}
elsif ($tt == 6) {
if ($pt ne "" && $cipher ne "" && $signature ne "" && $n ne "" && $e ne "") {
$out .= rsa_sigver($pt, $cipher, $signature, $n, $e);
$pt = "";
$signature = "";
}
}
elsif ($tt == 7 ) {
if ($key1 ne "" && $dt ne "" && $v ne "") {
$out .= rngx931($key1, $dt, $v, "VST");
$key1 = "";
$dt = "";
$v = "";
}
}
elsif ($tt == 8 ) {
if ($key1 ne "" && $dt ne "" && $v ne "") {
$out .= rngx931($key1, $dt, $v, "MCT");
$key1 = "";
$dt = "";
$v = "";
}
}
elsif ($tt == 9) {
if ($klen ne "" && $tlen ne "" && $key1 ne "" && $pt ne "") {
$out .= hmac_kat($klen, $tlen, $key1, $pt);
$key1 = "";
$tlen = "";
$klen = "";
$pt = "";
}
}
elsif ($tt > 0) {
die "Test case $tt not defined";
}
}
close IN;
$out =~ s/\n/\r\n/g; # make it a dos file
open(OUT, ">$outfile") or die "Cannot create output file $outfile: $?";
print OUT $out;
close OUT;
}
# Signalhandler
sub cleanup() {
unlink("rsa_siggen.tmp.$$");
unlink("rsa_sigver.tmp.$$");
unlink("rsa_sigver.tmp.$$.sig");
unlink("rsa_sigver.tmp.$$.der");
unlink("rsa_sigver.tmp.$$.cnf");
exit;
}
############################################################
#
# let us pretend to be C :-)
sub main() {
usage() unless @ARGV;
- getopts("R", \%opt) or die "bad option";
+ getopts("RI:", \%opt) or die "bad option";
##### Set library
- #print STDERR "Using OpenSSL interface functions\n";
- #$encdec = \&openssl_encdec;
- #$rsa_sign = \&openssl_rsa_sign;
- #$rsa_verify = \&openssl_rsa_verify;
- #$gen_rsakey = \&openssl_gen_rsakey;
- #$hash = \&openssl_hash;
- #$state_cipher = \&openssl_state_cipher;
-
- print STDERR "Using libgcrypt interface functions\n";
- $state_rng = \&libgcrypt_state_rng;
- $hmac = \&libgcrypt_hmac;
+ if ( ! defined $opt{'I'} || $opt{'I'} eq 'openssl' ) {
+ print STDERR "Using OpenSSL interface functions\n";
+ $encdec = \&openssl_encdec;
+ $rsa_sign = \&openssl_rsa_sign;
+ $rsa_verify = \&openssl_rsa_verify;
+ $gen_rsakey = \&openssl_gen_rsakey;
+ $hash = \&openssl_hash;
+ $state_cipher = \&openssl_state_cipher;
+ } elsif ( $opt{'I'} eq 'libgcrypt' ) {
+ print STDERR "Using libgcrypt interface functions\n";
+ $encdec = \&libgcrypt_encdec;
+ $rsa_sign = \&libgcrypt_rsa_sign;
+ $rsa_verify = \&libgcrypt_rsa_verify;
+ $gen_rsakey = \&libgcrypt_gen_rsakey;
+ $hash = \&libgcrypt_hash;
+ $state_cipher = \&libgcrypt_state_cipher;
+ $state_rng = \&libgcrypt_state_rng;
+ $hmac = \&libgcrypt_hmac;
+ } else {
+ die "Invalid interface option given";
+ }
my $infile=$ARGV[0];
die "Error: Test vector file $infile not found" if (! -f $infile);
my $outfile = $infile;
# let us add .rsp regardless whether we could strip .req
$outfile =~ s/\.req$//;
if ($opt{'R'}) {
$outfile .= ".rc4";
} else {
$outfile .= ".rsp";
}
if (-f $outfile) {
die "Output file $outfile could not be removed: $?"
unless unlink($outfile);
}
print STDERR "Performing tests from source file $infile with results stored in destination file $outfile\n";
#Signal handler
$SIG{HUP} = \&cleanup;
$SIG{INT} = \&cleanup;
$SIG{QUIT} = \&cleanup;
$SIG{TERM} = \&cleanup;
# Do the job
parse($infile, $outfile);
unlink("rsa_siggen.tmp.$$");
}
###########################################
# Call it
main();
1;
diff --git a/tests/cavs_tests.sh b/tests/cavs_tests.sh
new file mode 100755
index 00000000..6ba2b085
--- /dev/null
+++ b/tests/cavs_tests.sh
@@ -0,0 +1,125 @@
+#!/bin/sh
+# Run FIPS CAVS tests
+# Copyright 2008 Free Software Foundation, Inc.
+#
+# This file is free software; as a special exception the author gives
+# unlimited permission to copy and/or distribute it, with or without
+# modifications, as long as this notice is preserved.
+#
+# This file is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY, to the extent permitted by law; without even the
+# implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
+#
+# Instructions:
+#
+# 1. Cd to the libgcrypt/tests directory
+#
+# 2. Unpack the test vector tarball into subdirectory named "cavs".
+# An example directory layout after unpacking might be:
+# libgcrypt/tests/cavs/AES/req/CBCGFSbox128.req
+# libgcrypt/tests/cavs/AES/req/CFB128MCT128.req
+#
+# Note that below the "cavs" directory there should only be one
+# directory part named "req". Further avoid directory part
+# names "resp".
+#
+# 3. Run this script from the libgcrypt/tests directory:
+# ./cavs_tests.sh
+#
+# 4. Send the result file cavs/CAVS_results-*.zip to the testing lab.
+#
+
+# Stop script if something unexpected happens.
+set -e
+
+# A global flag to keep track of errors.
+errors_seen_file="$(pwd)/.#cavs_test.errors_seen.tmp"
+[ -f "$errors_seen_file" ] && rm "$errors_seen_file"
+continue_mode=no
+[ "$1" = "--continue" ] && continue_mode=yes
+
+
+# Function to run one test.
+# The argument is the request file name.
+function run_one_test () {
+ local reqfile="$1"
+ local rspfile
+ local tmprspfile
+ local respdir
+
+ tmprspfile=$(echo "$reqfile" | sed 's,.req$,.rsp,')
+ rspfile=$(echo "$tmprspfile" | sed 's,/req/,/resp/,' )
+ respdir=$(dirname "$rspfile")
+ [ -f "$tmprspfile" ] && rm "$tmprspfile"
+ [ -d "$respdir" ] || mkdir "$respdir"
+ [ -f "$rspfile" ] && rm "$rspfile"
+
+ if ./cavs_driver.pl -I libgcrypt "$reqfile"; then
+ echo "failed test: $reqfile" >&2
+ : >"$errors_seen_file"
+ elif [ -f "$tmprspfile" ]; then
+ mv "$tmprspfile" "$rspfile"
+ else
+ echo "failed test: $reqfile" >&2
+ : >"$errors_seen_file"
+ fi
+}
+
+
+
+# Save date and system architecure to construct the output archive name
+DATE=$(date +%Y%m%d)
+ARCH=$(arch || echo unknown)
+result_file="CAVS_results-$ARCH-$DATE.zip"
+
+for f in fipsdrv fipsrngdrv cavs_driver.pl; do
+ if [ ! -f "./$f" ]; then
+ echo "required program \"$f\" missing in current directory" >&2
+ exit 2
+ fi
+done
+if [ ! -d cavs ]; then
+ echo "required directory \"cavs\" missing below current directory" >&2
+ exit 2
+fi
+if [ ! zip -h >/dev/null 2>&1 ]; then
+ echo "required program \"zip\" is not installed on this system" >&2
+ exit 2
+fi
+
+# Set the PATH to this directory so that the perl script is able to
+# find the test drivers.
+PATH=.:$PATH
+
+# Check whether there are any stale response files
+find cavs -type f -name "*.rsp" | ( while read f ; do
+ echo "Stale response file: $f" >&2
+ any=yes
+done
+if [ "$any" = "yes" ]; then
+ echo "Stale response files found" >&2
+ if [ "$continue_mode" != "yes" ]; then
+ echo "use option --continue if that is not a problem" >&2
+ exit 1
+ fi
+fi
+) || exit 1
+
+
+# Find all test files and run the tests.
+find cavs -type f -name "*.req" | while read f ; do
+ echo "Running test file $f" >&2
+ run_one_test "$f"
+done
+
+if [ -f "$errors_seen_file" ]; then
+ rm "$errors_seen_file"
+ echo "Error enountered - not packing up response file" >&2
+ exit 1
+fi
+
+echo "Packing up all response files" >&2
+cd cavs
+find . -type f -name "*rsp" -print | zip -@ "$result_file"
+
+echo "Result file is: cavs/$result_file" >&2
diff --git a/tests/fipsdrv.c b/tests/fipsdrv.c
new file mode 100644
index 00000000..25018808
--- /dev/null
+++ b/tests/fipsdrv.c
@@ -0,0 +1,1458 @@
+/* fipsdrv.c - A driver to help with FIPS CAVS tests.
+ Copyright (C) 2008 Free Software Foundation, Inc.
+
+ This file is part of Libgcrypt.
+
+ Libgcrypt is free software; you can redistribute it and/or modify
+ it under the terms of the GNU Lesser General Public License as
+ published by the Free Software Foundation; either version 2.1 of
+ the License, or (at your option) any later version.
+
+ Libgcrypt is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+ GNU Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this program; if not, see <http://www.gnu.org/licenses/>.
+ */
+
+#ifdef HAVE_CONFIG_H
+#include <config.h>
+#endif
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <stdarg.h>
+#include <errno.h>
+#include <ctype.h>
+#ifndef HAVE_W32_SYSTEM
+# include <signal.h>
+#endif
+#include <assert.h>
+#include <unistd.h>
+
+#include <gcrypt.h>
+
+#define PGM "fipsdrv"
+
+#define my_isascii(c) (!((c) & 0x80))
+#define digitp(p) (*(p) >= '0' && *(p) <= '9')
+#define hexdigitp(a) (digitp (a) \
+ || (*(a) >= 'A' && *(a) <= 'F') \
+ || (*(a) >= 'a' && *(a) <= 'f'))
+#define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \
+ *(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10))
+#define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1))
+#define DIM(v) (sizeof(v)/sizeof((v)[0]))
+#define DIMof(type,member) DIM(((type *)0)->member)
+
+
+/* Verbose mode flag. */
+static int verbose;
+
+/* Binary input flag. */
+static int binary_input;
+
+/* Binary output flag. */
+static int binary_output;
+
+/* Base64 output flag. */
+static int base64_output;
+
+/* We need to know whetehr we are in loop_mode. */
+static int loop_mode;
+
+/* ASN.1 classes. */
+enum
+{
+ UNIVERSAL = 0,
+ APPLICATION = 1,
+ ASNCONTEXT = 2,
+ PRIVATE = 3
+};
+
+
+/* ASN.1 tags. */
+enum
+{
+ TAG_NONE = 0,
+ TAG_BOOLEAN = 1,
+ TAG_INTEGER = 2,
+ TAG_BIT_STRING = 3,
+ TAG_OCTET_STRING = 4,
+ TAG_NULL = 5,
+ TAG_OBJECT_ID = 6,
+ TAG_OBJECT_DESCRIPTOR = 7,
+ TAG_EXTERNAL = 8,
+ TAG_REAL = 9,
+ TAG_ENUMERATED = 10,
+ TAG_EMBEDDED_PDV = 11,
+ TAG_UTF8_STRING = 12,
+ TAG_REALTIVE_OID = 13,
+ TAG_SEQUENCE = 16,
+ TAG_SET = 17,
+ TAG_NUMERIC_STRING = 18,
+ TAG_PRINTABLE_STRING = 19,
+ TAG_TELETEX_STRING = 20,
+ TAG_VIDEOTEX_STRING = 21,
+ TAG_IA5_STRING = 22,
+ TAG_UTC_TIME = 23,
+ TAG_GENERALIZED_TIME = 24,
+ TAG_GRAPHIC_STRING = 25,
+ TAG_VISIBLE_STRING = 26,
+ TAG_GENERAL_STRING = 27,
+ TAG_UNIVERSAL_STRING = 28,
+ TAG_CHARACTER_STRING = 29,
+ TAG_BMP_STRING = 30
+};
+
+/* ASN.1 Parser object. */
+struct tag_info
+{
+ int class; /* Object class. */
+ unsigned long tag; /* The tag of the object. */
+ unsigned long length; /* Length of the values. */
+ int nhdr; /* Length of the header (TL). */
+ unsigned int ndef:1; /* The object has an indefinite length. */
+ unsigned int cons:1; /* This is a constructed object. */
+};
+
+
+
+/* Print a error message and exit the process with an error code. */
+static void
+die (const char *format, ...)
+{
+ va_list arg_ptr;
+
+ va_start (arg_ptr, format);
+ fputs (PGM ": ", stderr);
+ vfprintf (stderr, format, arg_ptr);
+ va_end (arg_ptr);
+ exit (1);
+}
+
+
+static void
+showhex (const char *prefix, const void *buffer, size_t length)
+{
+ const unsigned char *p = buffer;
+
+ if (prefix)
+ fprintf (stderr, PGM ": %s: ", prefix);
+ while (length-- )
+ fprintf (stderr, "%02X", *p++);
+ if (prefix)
+ putc ('\n', stderr);
+}
+
+
+/* Convert STRING consisting of hex characters into its binary
+ representation and store that at BUFFER. BUFFER needs to be of
+ LENGTH bytes. The function checks that the STRING will convert
+ exactly to LENGTH bytes. The string is delimited by either end of
+ string or a white space character. The function returns -1 on
+ error or the length of the parsed string. */
+static int
+hex2bin (const char *string, void *buffer, size_t length)
+{
+ int i;
+ const char *s = string;
+
+ for (i=0; i < length; )
+ {
+ if (!hexdigitp (s) || !hexdigitp (s+1))
+ return -1; /* Invalid hex digits. */
+ ((unsigned char*)buffer)[i++] = xtoi_2 (s);
+ s += 2;
+ }
+ if (*s && (!my_isascii (*s) || !isspace (*s)) )
+ return -1; /* Not followed by Nul or white space. */
+ if (i != length)
+ return -1; /* Not of expected length. */
+ if (*s)
+ s++; /* Skip the delimiter. */
+ return s - string;
+}
+
+
+/* Convert STRING consisting of hex characters into its binary
+ representation and return it as an allocated buffer. The valid
+ length of the buffer is returned at R_LENGTH. The string is
+ delimited by end of string. The function returns NULL on
+ error. */
+static void *
+hex2buffer (const char *string, size_t *r_length)
+{
+ const char *s;
+ unsigned char *buffer;
+ size_t length;
+
+ buffer = gcry_xmalloc (strlen(string)/2+1);
+ length = 0;
+ for (s=string; *s; s +=2 )
+ {
+ if (!hexdigitp (s) || !hexdigitp (s+1))
+ return NULL; /* Invalid hex digits. */
+ ((unsigned char*)buffer)[length++] = xtoi_2 (s);
+ }
+ *r_length = length;
+ return buffer;
+}
+
+/* Read a file from stream FP into a newly allocated buffer and return
+ that buffer. The valid length of the buffer is stored at R_LENGTH.
+ Returns NULL on failure. If decode is set, the file is assumed to
+ be hex encoded and the decoded content is returned. */
+static void *
+read_file (FILE *fp, int decode, size_t *r_length)
+{
+ char *buffer;
+ size_t buflen;
+ size_t nread, bufsize = 0;
+
+ *r_length = 0;
+#define NCHUNK 8192
+#ifdef HAVE_DOSISH_SYSTEM
+ setmode (fileno(fp), O_BINARY);
+#endif
+ buffer = NULL;
+ buflen = 0;
+ do
+ {
+ bufsize += NCHUNK;
+ if (!buffer)
+ buffer = gcry_xmalloc (bufsize);
+ else
+ buffer = gcry_xrealloc (buffer, bufsize);
+
+ nread = fread (buffer + buflen, 1, NCHUNK, fp);
+ if (nread < NCHUNK && ferror (fp))
+ {
+ gcry_free (buffer);
+ return NULL;
+ }
+ buflen += nread;
+ }
+ while (nread == NCHUNK);
+#undef NCHUNK
+ if (decode)
+ {
+ const char *s;
+ char *p;
+
+ for (s=buffer,p=buffer,nread=0; nread+1 < buflen; s += 2, nread +=2 )
+ {
+ if (!hexdigitp (s) || !hexdigitp (s+1))
+ {
+ gcry_free (buffer);
+ return NULL; /* Invalid hex digits. */
+ }
+ *(unsigned char*)p++ = xtoi_2 (s);
+ }
+ if (nread != buflen)
+ {
+ gcry_free (buffer);
+ return NULL; /* Odd number of hex digits. */
+ }
+ buflen = p - buffer;
+ }
+
+ *r_length = buflen;
+ return buffer;
+}
+
+/* Do in-place decoding of base-64 data of LENGTH in BUFFER. Returns
+ the new length of the buffer. Dies on error. */
+static size_t
+base64_decode (char *buffer, size_t length)
+{
+ static unsigned char const asctobin[128] =
+ {
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3e, 0xff, 0xff, 0xff, 0x3f,
+ 0x34, 0x35, 0x36, 0x37, 0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0xff, 0xff,
+ 0xff, 0xff, 0xff, 0xff, 0xff, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06,
+ 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10, 0x11, 0x12,
+ 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0xff, 0xff, 0xff, 0xff, 0xff,
+ 0xff, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20, 0x21, 0x22, 0x23, 0x24,
+ 0x25, 0x26, 0x27, 0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
+ 0x31, 0x32, 0x33, 0xff, 0xff, 0xff, 0xff, 0xff
+ };
+
+ int idx = 0;
+ unsigned char val = 0;
+ int c = 0;
+ char *d, *s;
+ int lfseen = 1;
+
+ /* Find BEGIN line. */
+ for (s=buffer; length; length--, s++)
+ {
+ if (lfseen && *s == '-' && length > 11 && !memcmp (s, "-----BEGIN ", 11))
+ {
+ for (; length && *s != '\n'; length--, s++)
+ ;
+ break;
+ }
+ lfseen = (*s == '\n');
+ }
+
+ /* Decode until pad character or END line. */
+ for (d=buffer; length; length--, s++)
+ {
+ if (lfseen && *s == '-' && length > 9 && !memcmp (s, "-----END ", 9))
+ break;
+ if ((lfseen = (*s == '\n')) || *s == ' ' || *s == '\r' || *s == '\t')
+ continue;
+ if (*s == '=')
+ {
+ /* Pad character: stop */
+ if (idx == 1)
+ *d++ = val;
+ break;
+ }
+
+ if ( (*s & 0x80) || (c = asctobin[*(unsigned char *)s]) == 0xff)
+ die ("invalid base64 character %02X at pos %d detected\n",
+ *(unsigned char*)s, (int)(s-buffer));
+
+ switch (idx)
+ {
+ case 0:
+ val = c << 2;
+ break;
+ case 1:
+ val |= (c>>4)&3;
+ *d++ = val;
+ val = (c<<4)&0xf0;
+ break;
+ case 2:
+ val |= (c>>2)&15;
+ *d++ = val;
+ val = (c<<6)&0xc0;
+ break;
+ case 3:
+ val |= c&0x3f;
+ *d++ = val;
+ break;
+ }
+ idx = (idx+1) % 4;
+ }
+
+ return d - buffer;
+}
+
+
+/* Parse the buffer at the address BUFFER which consists of the number
+ of octets as stored at BUFLEN. Return the tag and the length part
+ from the TLV triplet. Update BUFFER and BUFLEN on success. Checks
+ that the encoded length does not exhaust the length of the provided
+ buffer. */
+static int
+parse_tag (unsigned char const **buffer, size_t *buflen, struct tag_info *ti)
+{
+ int c;
+ unsigned long tag;
+ const unsigned char *buf = *buffer;
+ size_t length = *buflen;
+
+ ti->length = 0;
+ ti->ndef = 0;
+ ti->nhdr = 0;
+
+ /* Get the tag */
+ if (!length)
+ return -1; /* Premature EOF. */
+ c = *buf++; length--;
+ ti->nhdr++;
+
+ ti->class = (c & 0xc0) >> 6;
+ ti->cons = !!(c & 0x20);
+ tag = (c & 0x1f);
+
+ if (tag == 0x1f)
+ {
+ tag = 0;
+ do
+ {
+ tag <<= 7;
+ if (!length)
+ return -1; /* Premature EOF. */
+ c = *buf++; length--;
+ ti->nhdr++;
+ tag |= (c & 0x7f);
+ }
+ while ( (c & 0x80) );
+ }
+ ti->tag = tag;
+
+ /* Get the length */
+ if (!length)
+ return -1; /* Premature EOF. */
+ c = *buf++; length--;
+ ti->nhdr++;
+
+ if ( !(c & 0x80) )
+ ti->length = c;
+ else if (c == 0x80)
+ ti->ndef = 1;
+ else if (c == 0xff)
+ return -1; /* Forbidden length value. */
+ else
+ {
+ unsigned long len = 0;
+ int count = c & 0x7f;
+
+ for (; count; count--)
+ {
+ len <<= 8;
+ if (!length)
+ return -1; /* Premature EOF. */
+ c = *buf++; length--;
+ ti->nhdr++;
+ len |= (c & 0xff);
+ }
+ ti->length = len;
+ }
+
+ if (ti->class == UNIVERSAL && !ti->tag)
+ ti->length = 0;
+
+ if (ti->length > length)
+ return -1; /* Data larger than buffer. */
+
+ *buffer = buf;
+ *buflen = length;
+ return 0;
+}
+
+
+/* Read the file FNAME assuming it is a PEM encoded private key file
+ and return an S-expression. With SHOW set, the key parameters are
+ printed. */
+static gcry_sexp_t
+read_key_file (const char *fname, int show)
+{
+ gcry_error_t err;
+ FILE *fp;
+ char *buffer;
+ size_t buflen;
+ const unsigned char *der;
+ size_t derlen;
+ struct tag_info ti;
+ gcry_mpi_t keyparms[8];
+ int idx;
+ gcry_sexp_t s_key;
+
+ fp = fopen (fname, binary_input?"rb":"r");
+ if (!fp)
+ die ("can't open `%s': %s\n", fname, strerror (errno));
+ buffer = read_file (fp, 0, &buflen);
+ if (!buffer)
+ die ("error reading `%s'\n", fname);
+ fclose (fp);
+
+ buflen = base64_decode (buffer, buflen);
+
+ /* Parse the ASN.1 structure. */
+ der = (const unsigned char*)buffer;
+ derlen = buflen;
+ if ( parse_tag (&der, &derlen, &ti)
+ || ti.tag != TAG_SEQUENCE || ti.class || !ti.cons || ti.ndef)
+ goto bad_asn1;
+ if ( parse_tag (&der, &derlen, &ti)
+ || ti.tag != TAG_INTEGER || ti.class || ti.cons || ti.ndef)
+ goto bad_asn1;
+ if (ti.length != 1 || *der)
+ goto bad_asn1; /* The value of the first integer is no 0. */
+ der += ti.length; derlen += ti.length;
+
+ for (idx=0; idx < DIM(keyparms); idx++)
+ {
+ if ( parse_tag (&der, &derlen, &ti)
+ || ti.tag != TAG_INTEGER || ti.class || ti.cons || ti.ndef)
+ goto bad_asn1;
+ if (show)
+ {
+ char prefix[2];
+
+ prefix[0] = idx < 8? "nedpq12u"[idx] : '?';
+ prefix[1] = 0;
+ showhex (prefix, der, ti.length);
+ }
+ err = gcry_mpi_scan (keyparms+idx, GCRYMPI_FMT_USG, der, ti.length,NULL);
+ if (err)
+ die ("error scanning RSA parameter %d: %s\n", idx, gpg_strerror (err));
+ der += ti.length; derlen += ti.length;
+ }
+ if (idx != DIM(keyparms))
+ die ("not enough RSA key parameters\n");
+
+ gcry_free (buffer);
+
+ /* Convert from OpenSSL parameter ordering to the OpenPGP order. */
+ /* First check that p < q; if not swap p and q and recompute u. */
+ if (gcry_mpi_cmp (keyparms[3], keyparms[4]) > 0)
+ {
+ gcry_mpi_swap (keyparms[3], keyparms[4]);
+ gcry_mpi_invm (keyparms[7], keyparms[3], keyparms[4]);
+ }
+
+ /* Build the S-expression. */
+ err = gcry_sexp_build (&s_key, NULL,
+ "(private-key(rsa(n%m)(e%m)(d%m)(p%m)(q%m)(u%m)))",
+ keyparms[0], keyparms[1], keyparms[2],
+ keyparms[3], keyparms[4], keyparms[7] );
+ if (err)
+ die ("error building S-expression: %s\n", gpg_strerror (err));
+
+ for (idx=0; idx < DIM(keyparms); idx++)
+ gcry_mpi_release (keyparms[idx]);
+
+ return s_key;
+
+ bad_asn1:
+ die ("invalid ASN.1 structure in `%s'\n", fname);
+ return NULL; /*NOTREACHED*/
+}
+
+
+static void
+print_buffer (const void *buffer, size_t length)
+{
+ int writerr = 0;
+
+ if (base64_output)
+ {
+ static const unsigned char bintoasc[64+1] =
+ ("ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "abcdefghijklmnopqrstuvwxyz"
+ "0123456789+/");
+ const unsigned char *p;
+ unsigned char inbuf[4];
+ char outbuf[4];
+ int idx, quads;
+
+ idx = quads = 0;
+ for (p = buffer; length; p++, length--)
+ {
+ inbuf[idx++] = *p;
+ if (idx > 2)
+ {
+ outbuf[0] = bintoasc[(*inbuf>>2)&077];
+ outbuf[1] = bintoasc[(((*inbuf<<4)&060)
+ |((inbuf[1] >> 4)&017))&077];
+ outbuf[2] = bintoasc[(((inbuf[1]<<2)&074)
+ |((inbuf[2]>>6)&03))&077];
+ outbuf[3] = bintoasc[inbuf[2]&077];
+ if (fwrite (outbuf, 4, 1, stdout) != 1)
+ writerr = 1;
+ idx = 0;
+ if (++quads >= (64/4))
+ {
+ if (fwrite ("\n", 1, 1, stdout) != 1)
+ writerr = 1;
+ quads = 0;
+ }
+ }
+ }
+ if (idx)
+ {
+ outbuf[0] = bintoasc[(*inbuf>>2)&077];
+ if (idx == 1)
+ {
+ outbuf[1] = bintoasc[((*inbuf<<4)&060)&077];
+ outbuf[2] = outbuf[3] = '=';
+ }
+ else
+ {
+ outbuf[1] = bintoasc[(((*inbuf<<4)&060)
+ |((inbuf[1]>>4)&017))&077];
+ outbuf[2] = bintoasc[((inbuf[1]<<2)&074)&077];
+ outbuf[3] = '=';
+ }
+ if (fwrite (outbuf, 4, 1, stdout) != 1)
+ writerr = 1;
+ quads++;
+ }
+ if (quads && fwrite ("\n", 1, 1, stdout) != 1)
+ writerr = 1;
+ }
+ else if (binary_output)
+ {
+ if (fwrite (buffer, length, 1, stdout) != 1)
+ writerr++;
+ }
+ else
+ {
+ const unsigned char *p = buffer;
+
+ while (length-- && !ferror (stdout) )
+ printf ("%02X", *p++);
+ if (ferror (stdout))
+ writerr++;
+ }
+ if (!writerr && fflush (stdout) == EOF)
+ writerr++;
+ if (writerr)
+ {
+#ifndef HAVE_W32_SYSTEM
+ if (loop_mode && errno == EPIPE)
+ loop_mode = 0;
+ else
+#endif
+ die ("writing output failed: %s\n", strerror (errno));
+ }
+}
+
+
+
+static gcry_error_t
+init_external_rng_test (void **r_context,
+ unsigned int flags,
+ const void *key, size_t keylen,
+ const void *seed, size_t seedlen,
+ const void *dt, size_t dtlen)
+{
+ return gcry_control (58,
+ r_context, flags,
+ key, keylen,
+ seed, seedlen,
+ dt, dtlen);
+}
+
+static gcry_error_t
+run_external_rng_test (void *context, void *buffer, size_t buflen)
+{
+ return gcry_control (59, context, buffer, buflen);
+}
+
+static void
+deinit_external_rng_test (void *context)
+{
+ gcry_control (60, context);
+}
+
+
+/* Given an OpenSSL cipher name NAME, return the Libgcrypt algirithm
+ identified and store the libgcrypt mode at R_MODE. Returns 0 on
+ error. */
+static int
+map_openssl_cipher_name (const char *name, int *r_mode)
+{
+ static struct {
+ const char *name;
+ int algo;
+ int mode;
+ } table[] =
+ {
+ { "bf-cbc", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CBC },
+ { "bf", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CBC },
+ { "bf-cfb", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_CFB },
+ { "bf-ecb", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_ECB },
+ { "bf-ofb", GCRY_CIPHER_BLOWFISH, GCRY_CIPHER_MODE_OFB },
+
+ { "cast-cbc", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_CBC },
+ { "cast", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_CBC },
+ { "cast5-cbc", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_CBC },
+ { "cast5-cfb", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_CFB },
+ { "cast5-ecb", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_ECB },
+ { "cast5-ofb", GCRY_CIPHER_CAST5, GCRY_CIPHER_MODE_OFB },
+
+ { "des-cbc", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_CBC },
+ { "des", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_CBC },
+ { "des-cfb", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_CFB },
+ { "des-ofb", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_OFB },
+ { "des-ecb", GCRY_CIPHER_DES, GCRY_CIPHER_MODE_ECB },
+
+ { "des-ede3-cbc", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_CBC },
+ { "des-ede3 ", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_ECB },
+ { "des3 ", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_CBC },
+ { "des-ede3-cfb", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_CFB },
+ { "des-ede3-ofb", GCRY_CIPHER_3DES, GCRY_CIPHER_MODE_OFB },
+
+ { "rc4", GCRY_CIPHER_ARCFOUR, GCRY_CIPHER_MODE_STREAM },
+
+ { "aes-128-cbc", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC },
+ { "aes-128", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CBC },
+ { "aes-128-cfb", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_CFB },
+ { "aes-128-ecb", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_ECB },
+ { "aes-128-ofb", GCRY_CIPHER_AES128, GCRY_CIPHER_MODE_OFB },
+
+ { "aes-192-cbc", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CBC },
+ { "aes-192", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CBC },
+ { "aes-192-cfb", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_CFB },
+ { "aes-192-ecb", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_ECB },
+ { "aes-192-ofb", GCRY_CIPHER_AES192, GCRY_CIPHER_MODE_OFB },
+
+ { "aes-256-cbc", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC },
+ { "aes-256", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CBC },
+ { "aes-256-cfb", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_CFB },
+ { "aes-256-ecb", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_ECB },
+ { "aes-256-ofb", GCRY_CIPHER_AES256, GCRY_CIPHER_MODE_OFB },
+
+ { NULL, 0 , 0 }
+ };
+ int idx;
+
+ for (idx=0; table[idx].name; idx++)
+ if (!strcmp (name, table[idx].name))
+ {
+ *r_mode = table[idx].mode;
+ return table[idx].algo;
+ }
+ *r_mode = 0;
+ return 0;
+}
+
+
+
+/* Run an encrypt or decryption operations. If DATA is NULL the
+ function reads its input in chunks of size DATALEN from fp and
+ processes it and writes it out until EOF. */
+static void
+run_encrypt_decrypt (int encrypt_mode,
+ int cipher_algo, int cipher_mode,
+ const void *iv_buffer, size_t iv_buflen,
+ const void *key_buffer, size_t key_buflen,
+ const void *data, size_t datalen, FILE *fp)
+{
+ gpg_error_t err;
+ gcry_cipher_hd_t hd;
+ void *outbuf;
+ size_t outbuflen;
+ void *inbuf;
+ size_t inbuflen;
+
+ err = gcry_cipher_open (&hd, cipher_algo, cipher_mode, 0);
+ if (err)
+ die ("gcry_cipher_open failed for algo %d, mode %d: %s\n",
+ cipher_algo, cipher_mode, gpg_strerror (err));
+
+ err = gcry_cipher_setkey (hd, key_buffer, key_buflen);
+ if (err)
+ die ("gcry_cipher_setkey failed with keylen %u: %s\n",
+ (unsigned int)key_buflen, gpg_strerror (err));
+
+ err = gcry_cipher_setiv (hd, iv_buffer, iv_buflen);
+ if (err)
+ die ("gcry_cipher_setiv failed with ivlen %u: %s\n",
+ (unsigned int)iv_buflen, gpg_strerror (err));
+
+ inbuf = data? NULL : gcry_xmalloc (datalen);
+ outbuflen = datalen;
+ outbuf = gcry_xmalloc (outbuflen);
+
+ do
+ {
+ if (inbuf)
+ {
+ int nread = fread (inbuf, 1, datalen, fp);
+ if (nread < (int)datalen && ferror (fp))
+ die ("error reading input\n");
+ data = inbuf;
+ inbuflen = nread;
+ }
+ else
+ inbuflen = datalen;
+
+ if (encrypt_mode)
+ err = gcry_cipher_encrypt (hd, outbuf, outbuflen, data, inbuflen);
+ else
+ err = gcry_cipher_decrypt (hd, outbuf, outbuflen, data, inbuflen);
+ if (err)
+ die ("gcry_cipher_%scrypt failed: %s\n",
+ encrypt_mode? "en":"de", gpg_strerror (err));
+ print_buffer (outbuf, outbuflen);
+ }
+ while (inbuf);
+
+ gcry_cipher_close (hd);
+ gcry_free (outbuf);
+ gcry_free (inbuf);
+}
+
+
+
+/* Run a digest operation. */
+static void
+run_digest (int digest_algo, const void *data, size_t datalen)
+{
+ gpg_error_t err;
+ gcry_md_hd_t hd;
+ const unsigned char *digest;
+ unsigned int digestlen;
+
+ err = gcry_md_open (&hd, digest_algo, 0);
+ if (err)
+ die ("gcry_md_open failed for algo %d: %s\n",
+ digest_algo, gpg_strerror (err));
+
+ gcry_md_write (hd, data, datalen);
+ digest = gcry_md_read (hd, digest_algo);
+ digestlen = gcry_md_get_algo_dlen (digest_algo);
+ print_buffer (digest, digestlen);
+ gcry_md_close (hd);
+}
+
+
+/* Run a HMAC operation. */
+static void
+run_hmac (int digest_algo, const void *key, size_t keylen,
+ const void *data, size_t datalen)
+{
+ gpg_error_t err;
+ gcry_md_hd_t hd;
+ const unsigned char *digest;
+ unsigned int digestlen;
+
+ err = gcry_md_open (&hd, digest_algo, GCRY_MD_FLAG_HMAC);
+ if (err)
+ die ("gcry_md_open failed for HMAC algo %d: %s\n",
+ digest_algo, gpg_strerror (err));
+
+ gcry_md_setkey (hd, key, keylen);
+ if (err)
+ die ("gcry_md_setkey failed for HMAC algo %d: %s\n",
+ digest_algo, gpg_strerror (err));
+
+ gcry_md_write (hd, data, datalen);
+ digest = gcry_md_read (hd, digest_algo);
+ digestlen = gcry_md_get_algo_dlen (digest_algo);
+ print_buffer (digest, digestlen);
+ gcry_md_close (hd);
+}
+
+
+static size_t
+compute_tag_length (size_t n)
+{
+ int needed = 0;
+
+ if (n < 128)
+ needed += 2; /* Tag and one length byte. */
+ else if (n < 256)
+ needed += 3; /* Tag, number of length bytes, 1 length byte. */
+ else if (n < 65536)
+ needed += 4; /* Tag, number of length bytes, 2 length bytes. */
+ else
+ die ("DER object too long to encode\n");
+
+ return needed;
+}
+
+static unsigned char *
+store_tag_length (unsigned char *p, int tag, size_t n)
+{
+ if (tag == TAG_SEQUENCE)
+ tag |= 0x20; /* constructed */
+
+ *p++ = tag;
+ if (n < 128)
+ *p++ = n;
+ else if (n < 256)
+ {
+ *p++ = 0x81;
+ *p++ = n;
+ }
+ else if (n < 65536)
+ {
+ *p++ = 0x82;
+ *p++ = n >> 8;
+ *p++ = n;
+ }
+
+ return p;
+}
+
+
+/* Generate an RSA key of size KEYSIZE using the public exponent
+ PUBEXP and print it to stdout in the OpenSSL format. The format
+ is:
+
+ SEQUENCE {
+ INTEGER (0) -- Unknown constant.
+ INTEGER -- n
+ INTEGER -- e
+ INTEGER -- d
+ INTEGER -- p
+ INTEGER -- q (with p < q)
+ INTEGER -- dmp1 = d mod (p-1)
+ INTEGER -- dmq1 = d mod (q-1)
+ INTEGER -- u = p^{-1} mod q
+ }
+
+*/
+static void
+run_rsa_gen (int keysize, int pubexp)
+{
+ gpg_error_t err;
+ gcry_sexp_t keyspec, key, l1;
+ const char keyelems[] = "nedpq..u";
+ gcry_mpi_t keyparms[8];
+ size_t keyparmslen[8];
+ int idx;
+ size_t derlen, needed, n;
+ unsigned char *derbuf, *der;
+
+ err = gcry_sexp_build (&keyspec, NULL,
+ "(genkey (rsa (nbits %d)(rsa-use-e %d)))",
+ keysize, pubexp);
+ if (err)
+ die ("gcry_sexp_build failed for RSA key generation: %s\n",
+ gpg_strerror (err));
+
+ err = gcry_pk_genkey (&key, keyspec);
+ if (err)
+ die ("gcry_pk_genkey failed for RSA: %s\n", gpg_strerror (err));
+
+ gcry_sexp_release (keyspec);
+
+ l1 = gcry_sexp_find_token (key, "private-key", 0);
+ if (!l1)
+ die ("private key not found in genkey result\n");
+ gcry_sexp_release (key);
+ key = l1;
+
+ l1 = gcry_sexp_find_token (key, "rsa", 0);
+ if (!l1)
+ die ("returned private key not formed as expected\n");
+ gcry_sexp_release (key);
+ key = l1;
+
+ /* Extract the parameters from the S-expression and store them in a
+ well defined order in KEYPARMS. */
+ for (idx=0; idx < DIM(keyparms); idx++)
+ {
+ if (keyelems[idx] == '.')
+ {
+ keyparms[idx] = gcry_mpi_new (0);
+ continue;
+ }
+ l1 = gcry_sexp_find_token (key, keyelems+idx, 1);
+ if (!l1)
+ die ("no %c parameter in returned private key\n", keyelems[idx]);
+ keyparms[idx] = gcry_sexp_nth_mpi (l1, 1, GCRYMPI_FMT_USG);
+ if (!keyparms[idx])
+ die ("no value for %c parameter in returned private key\n",
+ keyelems[idx]);
+ gcry_sexp_release (l1);
+ }
+
+ gcry_sexp_release (key);
+
+ /* Check that p < q; if not swap p and q and recompute u. */
+ if (gcry_mpi_cmp (keyparms[3], keyparms[4]) > 0)
+ {
+ gcry_mpi_swap (keyparms[3], keyparms[4]);
+ gcry_mpi_invm (keyparms[7], keyparms[3], keyparms[4]);
+ }
+
+ /* Compute the additional parameters. */
+ gcry_mpi_sub_ui (keyparms[5], keyparms[3], 1);
+ gcry_mpi_mod (keyparms[5], keyparms[2], keyparms[5]);
+ gcry_mpi_sub_ui (keyparms[6], keyparms[4], 1);
+ gcry_mpi_mod (keyparms[6], keyparms[2], keyparms[6]);
+
+ /* Compute the length of the DER encoding. */
+ needed = compute_tag_length (1) + 1;
+ for (idx=0; idx < DIM(keyparms); idx++)
+ {
+ err = gcry_mpi_print (GCRYMPI_FMT_STD, NULL, 0, &n, keyparms[idx]);
+ if (err)
+ die ("error formatting parameter: %s\n", gpg_strerror (err));
+ keyparmslen[idx] = n;
+ needed += compute_tag_length (n) + n;
+ }
+
+ /* Store the key parameters. */
+ derlen = compute_tag_length (needed) + needed;
+ der = derbuf = gcry_xmalloc (derlen);
+
+ der = store_tag_length (der, TAG_SEQUENCE, needed);
+ der = store_tag_length (der, TAG_INTEGER, 1);
+ *der++ = 0;
+ for (idx=0; idx < DIM(keyparms); idx++)
+ {
+ der = store_tag_length (der, TAG_INTEGER, keyparmslen[idx]);
+ err = gcry_mpi_print (GCRYMPI_FMT_STD, der,
+ keyparmslen[idx], NULL, keyparms[idx]);
+ if (err)
+ die ("error formatting parameter: %s\n", gpg_strerror (err));
+ der += keyparmslen[idx];
+ }
+
+ /* Print the stuff. */
+ for (idx=0; idx < DIM(keyparms); idx++)
+ gcry_mpi_release (keyparms[idx]);
+
+ assert (der - derbuf == derlen);
+
+ if (base64_output)
+ puts ("-----BEGIN RSA PRIVATE KEY-----");
+ print_buffer (derbuf, derlen);
+ if (base64_output)
+ puts ("-----END RSA PRIVATE KEY-----");
+
+ gcry_free (derbuf);
+}
+
+
+
+/* Sign DATA of length DATALEN using the key taken from the PEM
+ encoded KEYFILE and the hash algorithm HASHALGO. */
+static void
+run_rsa_sign (const void *data, size_t datalen,
+ int hashalgo, int pkcs1, const char *keyfile)
+
+{
+ gpg_error_t err;
+ gcry_sexp_t s_data, s_key, s_sig, s_tmp;
+ gcry_mpi_t sig_mpi = NULL;
+ unsigned char *outbuf;
+ size_t outlen;
+
+/* showhex ("D", data, datalen); */
+
+ if (pkcs1)
+ err = gcry_sexp_build (&s_data, NULL,
+ "(data (flags pkcs1)(hash %s %b))",
+ gcry_md_algo_name (hashalgo), (int)datalen, data);
+ else
+ {
+ gcry_mpi_t tmp;
+
+ err = gcry_mpi_scan (&tmp, GCRYMPI_FMT_USG, data, datalen,NULL);
+ if (!err)
+ {
+ err = gcry_sexp_build (&s_data, NULL,
+ "(data (flags raw)(value %m))", tmp);
+ gcry_mpi_release (tmp);
+ }
+ }
+ if (err)
+ die ("gcry_sexp_build failed for RSA data input: %s\n",
+ gpg_strerror (err));
+
+ s_key = read_key_file (keyfile, 0);
+
+ err = gcry_pk_sign (&s_sig, s_data, s_key);
+ if (err)
+ {
+ gcry_sexp_release (read_key_file (keyfile, 1));
+ die ("gcry_pk_signed failed (datalen=%d,keyfile=%s): %s\n",
+ (int)datalen, keyfile, gpg_strerror (err));
+ }
+ gcry_sexp_release (s_key);
+ gcry_sexp_release (s_data);
+
+ s_tmp = gcry_sexp_find_token (s_sig, "sig-val", 0);
+ if (s_tmp)
+ {
+ gcry_sexp_release (s_sig);
+ s_sig = s_tmp;
+ s_tmp = gcry_sexp_find_token (s_sig, "rsa", 0);
+ if (s_tmp)
+ {
+ gcry_sexp_release (s_sig);
+ s_sig = s_tmp;
+ s_tmp = gcry_sexp_find_token (s_sig, "s", 0);
+ if (s_tmp)
+ {
+ gcry_sexp_release (s_sig);
+ s_sig = s_tmp;
+ sig_mpi = gcry_sexp_nth_mpi (s_sig, 1, GCRYMPI_FMT_USG);
+ }
+ }
+ }
+ gcry_sexp_release (s_sig);
+
+ if (!sig_mpi)
+ die ("no value in returned S-expression\n");
+ err = gcry_mpi_aprint (GCRYMPI_FMT_STD, &outbuf, &outlen, sig_mpi);
+ if (err)
+ die ("gcry_mpi_aprint failed: %s\n", gpg_strerror (err));
+ gcry_mpi_release (sig_mpi);
+
+ print_buffer (outbuf, outlen);
+ gcry_free (outbuf);
+}
+
+
+
+
+static void
+usage (int show_help)
+{
+ if (!show_help)
+ {
+ fputs ("usage: " PGM
+ " [OPTION] [FILE] (try --help for more information)\n", stderr);
+ exit (2);
+ }
+ fputs
+ ("Usage: " PGM " [OPTIONS] MODE [FILE]\n"
+ "Run a crypto operation using hex encoded input and output.\n"
+ "MODE:\n"
+ " encrypt, decrypt, digest, random, hmac-sha, rsa-{gen,sign,verify}\n"
+ "OPTIONS:\n"
+ " --verbose print additional information\n"
+ " --binary input and output is in binary form\n"
+ " --no-fips do not force FIPS mode\n"
+ " --key KEY use the hex encoded KEY\n"
+ " --iv IV use the hex encoded IV\n"
+ " --dt DT use the hex encoded DT for the RNG\n"
+ " --algo NAME use algorithm NAME\n"
+ " --keysize N use a keysize of N bits\n"
+ " --chunk N read in chunks of N bytes (implies --binary)\n"
+ " --pkcs1 use PKCS#1 encoding\n"
+ " --loop enable random loop mode\n"
+ " --progress print pogress indicators\n"
+ " --help print this text\n"
+ "With no FILE, or when FILE is -, read standard input.\n"
+ "Report bugs to " PACKAGE_BUGREPORT ".\n" , stdout);
+ exit (0);
+}
+
+int
+main (int argc, char **argv)
+{
+ int last_argc = -1;
+ gpg_error_t err;
+ int no_fips = 0;
+ int progress = 0;
+ int use_pkcs1 = 0;
+ const char *mode_string;
+ const char *key_string = NULL;
+ const char *iv_string = NULL;
+ const char *dt_string = NULL;
+ const char *algo_string = NULL;
+ const char *keysize_string = NULL;
+ FILE *input;
+ void *data;
+ size_t datalen;
+ size_t chunksize = 0;
+
+
+ if (argc)
+ { argc--; argv++; }
+
+ while (argc && last_argc != argc )
+ {
+ last_argc = argc;
+ if (!strcmp (*argv, "--"))
+ {
+ argc--; argv++;
+ break;
+ }
+ else if (!strcmp (*argv, "--help"))
+ {
+ usage (1);
+ }
+ else if (!strcmp (*argv, "--version"))
+ {
+ fputs (PGM " (Libgcrypt) " PACKAGE_VERSION "\n", stdout);
+ exit (0);
+ }
+ else if (!strcmp (*argv, "--verbose"))
+ {
+ verbose++;
+ argc--; argv++;
+ }
+ else if (!strcmp (*argv, "--binary"))
+ {
+ binary_input = binary_output = 1;
+ argc--; argv++;
+ }
+ else if (!strcmp (*argv, "--no-fips"))
+ {
+ no_fips++;
+ argc--; argv++;
+ }
+ else if (!strcmp (*argv, "--loop"))
+ {
+ loop_mode = 1;
+ argc--; argv++;
+ }
+ else if (!strcmp (*argv, "--progress"))
+ {
+ progress = 1;
+ argc--; argv++;
+ }
+ else if (!strcmp (*argv, "--key"))
+ {
+ argc--; argv++;
+ if (!argc)
+ usage (0);
+ key_string = *argv;
+ argc--; argv++;
+ }
+ else if (!strcmp (*argv, "--iv"))
+ {
+ argc--; argv++;
+ if (!argc)
+ usage (0);
+ iv_string = *argv;
+ argc--; argv++;
+ }
+ else if (!strcmp (*argv, "--dt"))
+ {
+ argc--; argv++;
+ if (!argc)
+ usage (0);
+ dt_string = *argv;
+ argc--; argv++;
+ }
+ else if (!strcmp (*argv, "--algo"))
+ {
+ argc--; argv++;
+ if (!argc)
+ usage (0);
+ algo_string = *argv;
+ argc--; argv++;
+ }
+ else if (!strcmp (*argv, "--keysize"))
+ {
+ argc--; argv++;
+ if (!argc)
+ usage (0);
+ keysize_string = *argv;
+ argc--; argv++;
+ }
+ else if (!strcmp (*argv, "--chunk"))
+ {
+ argc--; argv++;
+ if (!argc)
+ usage (0);
+ chunksize = atoi (*argv);
+ binary_input = binary_output = 1;
+ argc--; argv++;
+ }
+ else if (!strcmp (*argv, "--pkcs1"))
+ {
+ use_pkcs1 = 1;
+ argc--; argv++;
+ }
+ }
+
+ if (!argc || argc > 2)
+ usage (0);
+ mode_string = *argv;
+ if (argc == 2 && strcmp (argv[1], "-"))
+ {
+ input = fopen (argv[1], binary_input? "rb":"r");
+ if (!input)
+ die ("can't open `%s': %s\n", argv[1], strerror (errno));
+ }
+ else
+ input = stdin;
+
+#ifndef HAVE_W32_SYSTEM
+ if (loop_mode)
+ signal (SIGPIPE, SIG_IGN);
+#endif
+
+ if (verbose)
+ fprintf (stderr, PGM ": started (mode=%s)\n", mode_string);
+
+ gcry_control (GCRYCTL_SET_VERBOSITY, (int)verbose);
+ if (!no_fips)
+ gcry_control (GCRYCTL_FORCE_FIPS_MODE, 0);
+ if (!gcry_check_version ("1.4.3"))
+ die ("Libgcrypt is not sufficient enough\n");
+ if (verbose)
+ fprintf (stderr, PGM ": using Libgcrypt %s\n", gcry_check_version (NULL));
+ if (no_fips)
+ gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
+ gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
+
+ /* Most operations need some input data. */
+ if (!chunksize
+ && strcmp (mode_string, "random")
+ && strcmp (mode_string, "rsa-gen") )
+ {
+ data = read_file (input, !binary_input, &datalen);
+ if (!data)
+ die ("error reading%s input\n", binary_input?"":" and decoding");
+ if (verbose)
+ fprintf (stderr, PGM ": %u bytes of input data\n",
+ (unsigned int)datalen);
+ }
+ else
+ {
+ data = NULL;
+ datalen = 0;
+ }
+
+
+ if (!strcmp (mode_string, "encrypt") || !strcmp (mode_string, "decrypt"))
+ {
+ int cipher_algo, cipher_mode;
+ void *iv_buffer, *key_buffer;
+ size_t iv_buflen, key_buflen;
+
+ if (!algo_string)
+ die ("option --algo is required in this mode\n");
+ cipher_algo = map_openssl_cipher_name (algo_string, &cipher_mode);
+ if (!cipher_algo)
+ die ("cipher algorithm `%s' is not supported\n", algo_string);
+ if (!iv_string)
+ die ("option --iv is required in this mode\n");
+ iv_buffer = hex2buffer (iv_string, &iv_buflen);
+ if (!iv_buffer)
+ die ("invalid value for IV\n");
+ if (!key_string)
+ die ("option --key is required in this mode\n");
+ key_buffer = hex2buffer (key_string, &key_buflen);
+ if (!key_buffer)
+ die ("invalid value for KEY\n");
+
+ run_encrypt_decrypt ((*mode_string == 'e'),
+ cipher_algo, cipher_mode,
+ iv_buffer, iv_buflen,
+ key_buffer, key_buflen,
+ data, data? datalen:chunksize, input);
+ gcry_free (key_buffer);
+ gcry_free (iv_buffer);
+ }
+ else if (!strcmp (mode_string, "digest"))
+ {
+ int algo;
+
+ if (!algo_string)
+ die ("option --algo is required in this mode\n");
+ algo = gcry_md_map_name (algo_string);
+ if (!algo)
+ die ("digest algorithm `%s' is not supported\n", algo_string);
+
+ run_digest (algo, data, datalen);
+ }
+ else if (!strcmp (mode_string, "random"))
+ {
+ void *context;
+ unsigned char key[16];
+ unsigned char seed[16];
+ unsigned char dt[16];
+ unsigned char buffer[16];
+ size_t count = 0;
+
+ if (hex2bin (key_string, key, 16) < 0 )
+ die ("value for --key are not 32 hex digits\n");
+ if (hex2bin (iv_string, seed, 16) < 0 )
+ die ("value for --iv are not 32 hex digits\n");
+ if (hex2bin (dt_string, dt, 16) < 0 )
+ die ("value for --dt are not 32 hex digits\n");
+
+ /* The flag value 1 disables the dup check, so that the RNG
+ returns all generated data. */
+ err = init_external_rng_test (&context, 1, key, 16, seed, 16, dt, 16);
+ if (err)
+ die ("init external RNG test failed: %s\n", gpg_strerror (err));
+
+ do
+ {
+ err = run_external_rng_test (context, buffer, sizeof buffer);
+ if (err)
+ die ("running external RNG test failed: %s\n", gpg_strerror (err));
+ print_buffer (buffer, sizeof buffer);
+ if (progress)
+ {
+ if (!(++count % 1000))
+ fprintf (stderr, PGM ": %lu random bytes so far\n",
+ (unsigned long int)count * sizeof buffer);
+ }
+ }
+ while (loop_mode);
+
+ if (progress)
+ fprintf (stderr, PGM ": %lu random bytes\n",
+ (unsigned long int)count * sizeof buffer);
+
+ deinit_external_rng_test (context);
+ }
+ else if (!strcmp (mode_string, "hmac-sha"))
+ {
+ int algo;
+ void *key_buffer;
+ size_t key_buflen;
+
+ if (!data)
+ die ("no data available (do not use --chunk)\n");
+ if (!algo_string)
+ die ("option --algo is required in this mode\n");
+ switch (atoi (algo_string))
+ {
+ case 1: algo = GCRY_MD_SHA1; break;
+ case 224: algo = GCRY_MD_SHA224; break;
+ case 256: algo = GCRY_MD_SHA256; break;
+ case 384: algo = GCRY_MD_SHA384; break;
+ case 512: algo = GCRY_MD_SHA512; break;
+ default: algo = 0; break;
+ }
+ if (!algo)
+ die ("no digest algorithm found for hmac type `%s'\n", algo_string);
+ if (!key_string)
+ die ("option --key is required in this mode\n");
+ key_buffer = hex2buffer (key_string, &key_buflen);
+ if (!key_buffer)
+ die ("invalid value for KEY\n");
+
+ run_hmac (algo, key_buffer, key_buflen, data, datalen);
+
+ gcry_free (key_buffer);
+ }
+ else if (!strcmp (mode_string, "rsa-gen"))
+ {
+ int keysize;
+
+ if (!binary_output)
+ base64_output = 1;
+
+ keysize = keysize_string? atoi (keysize_string) : 0;
+ if (keysize < 128 || keysize > 16384)
+ die ("invalid keysize specified; needs to be 128 .. 16384\n");
+ run_rsa_gen (keysize, 65537);
+ }
+ else if (!strcmp (mode_string, "rsa-sign"))
+ {
+ int algo;
+
+ if (!key_string)
+ die ("option --key is required in this mode\n");
+ if (access (key_string, R_OK))
+ die ("option --key needs to specify an existing keyfile\n");
+ if (!algo_string)
+ die ("option --algo is required in this mode\n");
+ algo = gcry_md_map_name (algo_string);
+ if (!algo)
+ die ("digest algorithm `%s' is not supported\n", algo_string);
+ if (!data)
+ die ("no data available (do not use --chunk)\n");
+
+ run_rsa_sign (data, datalen, algo, use_pkcs1, key_string);
+
+ }
+ else if (!strcmp (mode_string, "rsa-verify"))
+ {
+ }
+ else
+ usage (0);
+
+ gcry_free (data);
+
+ /* Because Libgcrypt does not enforce FIPS mode in all cases we let
+ the process die if Libgcrypt is not anymore in FIPS mode after
+ the actual operation. */
+ if (!no_fips && !gcry_fips_mode_active ())
+ die ("FIPS mode is not anymore active\n");
+
+ if (verbose)
+ fputs (PGM ": ready\n", stderr);
+
+ return 0;
+}
+
diff --git a/tests/fipsrngdrv.c b/tests/fipsrngdrv.c
index d10c9cac..de2ad1ff 100644
--- a/tests/fipsrngdrv.c
+++ b/tests/fipsrngdrv.c
@@ -1,265 +1,272 @@
/* fipsrngdrv.c - A driver to test the FIPS RNG.
Copyright (C) 2008 Free Software Foundation, Inc.
This file is part of Libgcrypt.
Libgcrypt is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation; either version 2.1 of
the License, or (at your option) any later version.
Libgcrypt is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this program; if not, see <http://www.gnu.org/licenses/>.
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
#include <errno.h>
#include <ctype.h>
#ifndef HAVE_W32_SYSTEM
# include <signal.h>
#endif
#include <gcrypt.h>
#define PGM "fipsrngdrv"
#define my_isascii(c) (!((c) & 0x80))
#define digitp(p) (*(p) >= '0' && *(p) <= '9')
#define hexdigitp(a) (digitp (a) \
|| (*(a) >= 'A' && *(a) <= 'F') \
|| (*(a) >= 'a' && *(a) <= 'f'))
#define xtoi_1(p) (*(p) <= '9'? (*(p)- '0'): \
*(p) <= 'F'? (*(p)-'A'+10):(*(p)-'a'+10))
#define xtoi_2(p) ((xtoi_1(p) * 16) + xtoi_1((p)+1))
static void
die (const char *format, ...)
{
va_list arg_ptr;
va_start (arg_ptr, format);
fputs (PGM ": ", stderr);
vfprintf (stderr, format, arg_ptr);
va_end (arg_ptr);
exit (1);
}
/* Convert STRING consisting of hex characters into its binary
representation and store that at BUFFER. BUFFER needs to be of
LENGTH bytes. The function checks that the STRING will convert
exactly to LENGTH bytes. The string is delimited by either end of
string or a white space character. The function returns -1 on
error or the length of the parsed string. */
static int
hex2bin (const char *string, void *buffer, size_t length)
{
int i;
const char *s = string;
for (i=0; i < length; )
{
if (!hexdigitp (s) || !hexdigitp (s+1))
return -1; /* Invalid hex digits. */
((unsigned char*)buffer)[i++] = xtoi_2 (s);
s += 2;
}
if (*s && (!my_isascii (*s) || !isspace (*s)) )
return -1; /* Not followed by Nul or white space. */
if (i != length)
return -1; /* Not of expected length. */
if (*s)
s++; /* Skip the delimiter. */
return s - string;
}
static gcry_error_t
init_external_test (void **r_context,
unsigned int flags,
const void *key, size_t keylen,
const void *seed, size_t seedlen,
const void *dt, size_t dtlen)
{
return gcry_control (58,
r_context, flags,
key, keylen,
seed, seedlen,
dt, dtlen);
}
static gcry_error_t
run_external_test (void *context, void *buffer, size_t buflen)
{
return gcry_control (59, context, buffer, buflen);
}
static void
deinit_external_test (void *context)
{
gcry_control (60, context);
}
static void
print_buffer (const unsigned char *buffer, size_t length)
{
while (length--)
printf ("%02X", *buffer++);
}
int
main (int argc, char **argv)
{
int last_argc = -1;
int verbose = 0;
int binary = 0;
int loop = 0;
int progress = 0;
+ int no_fips = 0;
unsigned char key[16];
unsigned char seed[16];
unsigned char dt[16];
void *context;
gpg_error_t err;
unsigned char buffer[16];
if (argc)
{ argc--; argv++; }
while (argc && last_argc != argc )
{
last_argc = argc;
if (!strcmp (*argv, "--"))
{
argc--; argv++;
break;
}
else if (!strcmp (*argv, "--help"))
{
fputs ("usage: " PGM
" [--verbose] [--binary] [--loop] [--progress] KEY V DT\n",
stdout);
exit (0);
}
else if (!strcmp (*argv, "--verbose"))
{
verbose++;
argc--; argv++;
}
+ else if (!strcmp (*argv, "--no-fips"))
+ {
+ no_fips++;
+ argc--; argv++;
+ }
else if (!strcmp (*argv, "--binary"))
{
binary = 1;
argc--; argv++;
}
else if (!strcmp (*argv, "--loop"))
{
loop = 1;
argc--; argv++;
}
else if (!strcmp (*argv, "--progress"))
{
progress = 1;
argc--; argv++;
}
}
if (!argc)
{
memcpy (key, "1234567890123456", 16);
memcpy (seed, "abcdefghijklmnop", 16);
memcpy (dt, "XXXXXXXXXXXXXXXX", 16);
}
else if (argc == 3)
{
if ( hex2bin (argv[0], key, 16) < 0
|| hex2bin (argv[1], seed, 16) < 0
|| hex2bin (argv[2], dt, 16) < 0 )
die ("args are not 32 hex digits each\n");
}
else
die ("invalid usage (try --help)\n");
#ifndef HAVE_W32_SYSTEM
if (loop)
signal (SIGPIPE, SIG_IGN);
#endif
if (verbose)
fputs (PGM ": started\n", stderr);
gcry_control (GCRYCTL_SET_VERBOSITY, (int)verbose);
- gcry_control (GCRYCTL_FORCE_FIPS_MODE, 0);
+ if (!no_fips)
+ gcry_control (GCRYCTL_FORCE_FIPS_MODE, 0);
if (!gcry_check_version ("1.4.3"))
die ("version mismatch\n");
gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
/* The flag value 1 disables the dup check, so that the RNG returns
all generated data. */
err = init_external_test (&context, 1, key, 16, seed, 16, dt, 16);
if (err)
die ("init external test failed: %s\n", gpg_strerror (err));
do
{
int writerr = 0;
err = run_external_test (context, buffer, sizeof buffer);
if (err)
die ("run external test failed: %s\n", gpg_strerror (err));
if (binary)
{
if (fwrite (buffer, 16, 1, stdout) != 1)
writerr = 1;
else
fflush (stdout);
}
else
{
print_buffer (buffer, sizeof buffer);
if (putchar ('\n') == EOF)
writerr = 1;
}
if (writerr)
{
#ifndef HAVE_W32_SYSTEM
if (loop && errno == EPIPE)
break;
#endif
die ("writing output failed: %s\n", strerror (errno));
}
if (progress)
{
putc ('.', stderr);
fflush (stderr);
}
}
while (loop);
if (progress)
putc ('\n', stderr);
deinit_external_test (context);
if (verbose)
fputs (PGM ": ready\n", stderr);
return 0;
}

File Metadata

Mime Type
text/x-diff
Expires
Sat, May 10, 9:08 AM (21 h, 48 m)
Storage Engine
local-disk
Storage Format
Raw Data
Storage Handle
00/30/f135e183a29c0f11d673a8babbfc

Event Timeline